Skip to content

Latest commit

 

History

History
170 lines (127 loc) · 19.5 KB

tasks-background-execution.md

File metadata and controls

170 lines (127 loc) · 19.5 KB

Tasks and background execution

Canonical lifecycle

Tasks use Conversation-owned status; cards project it; Participants are Agents. Owning Routers complete delivered one-shot/Loop Tasks with no pending work or decision (excluding recurring, Triage, legacy Workflow; unbounded running Loops need a person's request). Messages reopen sandbox, report_to: parent_task, and named-Worker Collaborative review Tasks; non-system Messages to the Worker also reopen escalated sandbox/parent-reported Tasks (system/task_loop_wake keep escalated). Escalation means blocked work needs the initiator. Clients show escalated as Needs input; Routers set it on Worker question cards and restore active on ordinary Tasks on resume.

A Router prompt notice ends the source reply with each Task's confirmed status and its consequence. If the reply is already sent, follow up promptly. Report failed writes truthfully, suppress same-status retries, and explain reopening. Terminal Slack notices keep exact source/target, Session and installation checks. They add no internal-write authority and no exactly-once delivery.

Ordinary Tasks

Each Task has a primary Worker and may bind up to 6 Worker Sessions reusing task_worker_agent_id via Participant target_key slots (no new entity or DB migration). Routers delegate commands and own status; Workers publish Messages. A person's Task Message reaches both. The Worker answers; the Router acts only for status, memory or Router-only actions, then posts the result. One create-only metadata write commits a new Task and its first command. Earlier failures leave no Task; a same-request retry drops uncommitted Messages. After a grace period, SalixIM.TaskWorkerWatch reminds a silent Worker once (task_worker_nudge), then tells the initiator once (task_worker_stopped). Passive context_only Messages and secondary Workers' wake_reason: "all_sessions" Messages owe no reply. In a running Loop, Router notes owe no reply. Loop run wakes settled alone by end_turn(outcome: "done", no_reply: true) owe none (metadata.task_loop_quiet, via SalixAgent.Loops.TaskOwner). Each task_worker_nudge replies to its delegation (reply_to_message_id), and replies targeting the nudge move onto that delegation. Clients hide internal watch Messages (task_status_pending, task_worker_nudge, task_worker_stopped). If the Router stops after a Worker result on an active Task and all active Workers are idle, the watch tells the Router once per result (excluding recurring, Workflow, Triage, and active Loop Tasks). The watch covers only Salix Sessions reporting activity, not station Tasks. For a QQ card, it also posts working, blocked and paused notices. Provider cards and client timeouts cannot complete, cancel, or reopen Tasks. Telegram review cards complete Tasks through owner review only.

Multi-session Tasks

A Router may create a multi-session Task (sessions 1..6, initial_wake: primary | all) or add a secondary Session (im_api.internal.task.add_session, Router-only). Exclusions in v1: Loop (including ended), Collaborative (People), Triage, Scheduled, legacy Task Graph, and TaskRun.switch on multi-session Tasks return :bad_request. TaskRun.switch vs add_session exclusion is enforced at the ConversationActor commit boundary with an in-memory switch guard (not a cross-system 2PC lock); an owner restart mid-switch falls back to Station gone cleanup. Primary uses target_key: nil ("lead" alias) and notification_filter.messages: "all"; secondaries use unique slug target_key (^[a-z0-9][a-z0-9_-]{0,31}$, excluding all, router, delegator, lead) and notification_filter.messages: "mentioned". ConversationActor keeps visibility in delivery_filter/explicit mentions and freezes metadata.wake_targets using symmetric group-chat routing: slot names (lead, reviewer, ...) are plain participant names with no routing hierarchy; explicit mentions or leading @slot wake only the addressed participant(s) (never self); unaddressed messages or leading @all wake every other eligible participant. No worker-to-worker hop cap exists; a Worker ending a turn (all_done) never auto-sets pending_review or ready_for_review; when all active Worker Sessions settle idle (including after peer-only @slot exchanges that did not wake the Router), TaskWorkerWatch / StationTaskWatch notifies the Router so an agent decides status. Unwoken Sessions incur zero turns or attachment materialization; on wake, delivery prepends live Task Roster and bounded catch-up (<= 200 scan, <= 20 visible non-system messages, <= 16 KiB, filenames only, reference only). TaskExecution grants apply only to primary.

Station Tasks

A Task with runs_on uses a VMM, Cloudflare, physical Station, or a sandbox of its own; its Worker Session runs there. SalixWeb.StationTasks invites the station, sends Messages (task.put), and writes posts as the Worker (task.post). A desktop station must be connected at creation; a Group Cloud VM need not be (woken/created, then invited on connect). Its Worker participant gets no Salix deliveries or Session, so SalixIM.TaskWorkerWatch skips it.

SalixIM.StationTaskWatch watches it instead. A delegation is the latest non-context_only Message given to the Worker that it did not write; the first Worker Message after it answers it. task_worker_nudge replies to its delegation (reply_to_message_id), and replies targeting it move onto that delegation. One timer runs per active station Task with an unanswered delegation (no scan or poll). The owner hands each appended Message to the watch. Checks read the last 50 Messages, station standing (SalixIM.Ports.TaskStations.standing/2), and—once given—Session status (task.status), rechecking after recheck_ms. Delegations past the 50-Message window remain waited on. Stages and thresholds (config :salix_im, :station_task_watch):

Stage Meaning Default threshold
vm_not_ready Cloud VM/sandbox not ready, or no Cloud VM (Cloud VM notifies Router once: task_worker_stopped, vm_not_ready) 10m (vm_not_ready_ms)
station_offline Station connector offline 10m (station_offline_ms)
not_given Station not yet given the delegation 10m (not_given_ms)
running Session active or waiting on work; not a stall 2h (running_ms), station_task_running info
idle_no_reply Session idle with nothing pending and no post, or missing Session 10m (idle_no_reply_ms)
cannot_start Pending Messages cannot start a turn; last_failure explains 10m (cannot_start_ms), or immediate for sign-in/quota/billing
given_no_reply Delegation given, status unknown (pre-task.status, 10s timeout, idle with pending) 30m (given_no_reply_ms)

Unreadable standing is logged and rechecked after recheck_ms. For idle_no_reply, when delegation age and Session for_ms reach idle_no_reply_ms, the watch appends one task_worker_nudge (station_task_nudged); idle that long again without reply appends task_worker_stopped (stopped_after_reminder) to the Router. cannot_start skips the reminder and sends task_worker_stopped (cannot_start + last_failure). running is never reminded. Failed appends retry up to 5 times; missing Routers still log and count. If task.put answers gone, Salix removes the station (:not_station); an unanswered delegation appends task_worker_stopped (station_left) and logs station_task_stalled. place comes from runs_on (legacy: last standing or other). station_task_stalled and salix.station_tasks.stalled.total{phase, kind} record each delegation/stage once (group_id, conversation_id, worker_agent_id, stage, place, vm_status, station_state, pending_messages, last_failure, epoch_seq, age_ms). Recovery logs station_task_recovered and salix.station_tasks.first_reply.seconds{kind}. comma_alerting:station_task_stalled (P2) fires for cloud_vm/sandbox on all stages except running/given_no_reply. Station-reported failures answer the delegation; sandbox failed/lost ends the wait; offline desktop stations only log/count. Restarts rebuild state from Messages; delegations older than stale_ms (24h) log station_task_stale. SalixIM.StationTaskWatchRecovery starts owners on node boot and placement change (100 Tasks/page, station_task_watch_recovery); watch failures log station_task_watch_failed without stopping the owner.

Continuation and containment

Follow-ups use the intended Task, not the latest active. Resumed Tasks keep the new request's authority.

Schedules create bounded work through existing owners. Keep schedule identity, trigger occurrence and Task activation distinct for retries. An overdue trigger must not cause unbounded synchronous fan-out. A Task that is not active skips its windows and keeps its Schedule; only an ended Task or an unbound Schedule deletes it (rules).

Background loops

A Loop is Agent-owned C that spinfoam runs on its lease holder (not a Schedule, Session, or Task; no occurrences or history). Timers, events, and host capabilities drive it. Only agent.notify wakes its Session, deduplicating retries by loop:<id>:<dedup_key>.

loop.create records path, SHA-256, config, and creator authority; each load checks the hash and fails on change or deletion.

The minute sweep restarts stranded active Loops' owner Servers (one page/node/min). Every load bumps incarnation; host calls require the current one. loop.state.put returns as config.state on reload. Returning sets paused(exited), except a non-zero exit after a transient store error on a Loop built-in; faults reload at most 3x/hour, then failed. Each terminal outcome notifies the Session once. Archive pauses Loops (archive); unarchive resumes them. loop.pause with until_device_id waits until that device connects. A Worker's Task Loop belongs to that Task (one per Task); only its rounds manage it, and Task end deletes it. The Task keeps its row (trigger, limits, runs, checkpoint); loop.create replaces and restarts it unless ended or archive-paused. A Loop Task's Loop starts pending, gets its program from the Worker, and ends (ended) on Task end or archive.

A Loop's row may hold a trigger (every_minutes, or cron + IANA timezone) and limits (max_runs, ends_at, stop_condition). loop.next_run records the trigger's next time after after_ms (default unreached next_run_at; after missed ones, the latest). Each delivered agent.notify increments run_count; reaching max_runs ends the Loop. The first wake, loop.next_run, or load at/after ends_at ends it; each node's minute sweep ends one page of the rest. Guest waits return after at most 24h.

Capabilities are a closed allowlist: agent.notify, loop.state.put, loop.state.get, loop.ack, loop.log, loop.next_run, safety: read tools, env.*/device.*, ssh.*, im_api.internal.read_conversation, Feishu/Lark message reads marked loop_read (history, thread, message, search), composio.execute, web.http_request, decide, and im_api.internal.task.create once the Cloud VM retires (Loop Tasks). Spinfoam admits only allowlisted calls; Product Loops also enforce pinned source and consent. composio.execute permits provider writes; ssh.* permits commands, terminal I/O, transfers, and host trust changes (ssh.download only to /drive). No other writes exist. Tools run through the normal dispatch boundary with the Loop's sealed origin, creator's tool disclosure, and delegated principal schedule|loop:<id>|<creator>. Per Loop, agent.notify admits 6 wakes/10m and im_api.* reads 300/15m; exhausting every window for 1h pauses it (budget); resume clears both windows. A tool reply is <= 16 KiB encoded; a longer one keeps a valid UTF-8 content prefix and truncated: true. Built-ins bypass dependency admission (full Tenant cannot refuse checkpoint/wake). Each guest has <= 1 in-flight host call; tool calls take a tool slot. loop.get exposes runtime.last_host_error; non-zero exits record it in failure and the exit notice.

External events reach a Loop via POST /v1/agent-groups/:group_id/loops/:loop_id/events (group API key). 202 means PostgreSQL kept the event, not that the guest ran it. The guest calls loop.ack after a quiet decision or durable downstream handoff (ACK + pending removal share one incarnation-fenced transaction). Event payloads are data: no authority and cannot widen the allowlist.

loop.webhook enables/rotates/revokes a Loop's secret URL (enable keeps an existing URL); only the owning Agent manages or reads it (loop.list/loop.get). The 256-bit secret authorizes that Loop only; unknown/revoked secrets get 404. Rotation/revocation affects later admissions only. Deletion removes it; pause/archive keep it (409).

POST /v1/loop-webhooks/:secret (application/json, JSON object <= 2 MiB, no Authorization header; Composio <= 512 KiB). Topic is webhook. Top-level _webhook is server-reserved (stripped on ingress). Objects pass through when the full envelope fits <= 16 KiB (adding serde_json expansion margin only for scientific-notation floats and out-of-64-bit ints), depth <= 32, and <= 4000 payload nodes (attaching _webhook.headers when routing headers fit); else webhook/Composio payloads compact to <= 12 KiB / 1024 nodes with _webhook (truncated, re-encoded original_bytes, allowlisted headers). Event ID uses Idempotency-Key (trimmed, <= 128B), else X-GitHub-Delivery / X-Delivery-Id (HTTP OWS SP/HTAB trimmed only, <= 128B; invalid/multi-value/whitespace/comma returns 422; GitHub Redeliver reuses its GUID), else a fresh ID. Non-webhook ingress (loop.send/Group-key/product) and historical pending replay keep original payloads without truncation (Group-key 64 KiB HTTP cap, 16 KiB payload). Each Loop keeps <= 32 pending 16 KiB-envelope events; repeated IDs keep original payload/deadline. New or pending duplicate events trigger best-effort immediate wake (locally when owned and served, else per-Agent coalesced Placement.ensure_started + run_on_owner Reconciler.adopt, 64 concurrent wakes/node; congestion/transient faults fall back to pending same-key retry or minute sweep). Replay cannot restart a failed call in the same object; guests own bounded retries. After 15m without ACK, the next owner sweep fails the Loop and keeps pending events. Explicit resume, not a process restart, grants 15m more. Pause keeps pending work; deletion discards it. Active Group payloads total <= 50 MiB, excluding metadata and paused Loops. ACK, Session admission, Message append, and external delivery are separate facts; use stable downstream dedup keys; external effects are not exactly once.

Redis admits 60 req/min per Loop and 6,000 globally (before secret lookup); limiting/full mailbox returns 429 (Retry-After), outages 503. Telemetry excludes secrets; forward repair keeps pending events and ACKs.

See Composio triggers.

loop.subscribe subscribes to a product event (meeting.completed: one per finished meeting, ids/counts only; Loop Tasks).

Each transition into active (create/resume/unarchive) is admitted atomically under the Group's lock; quota refusal keeps an unarchived Loop paused(quota). The spinfoam child restarts with backoff <= 5x/hour, then reports Loops unavailable. Code: SalixAgent.Loops, loops/.

Scripts

salix.call runs any canonical tool through the calling round's session tool dispatch. Disclosure and dependency admission apply as for a direct call.

Decision capability design

decide classifies runtime data, filters events, and selects data sources for scripts and Loops. It returns decisions without reading sources, running tools, or granting authority. The caller supplies bounded candidates and applies thresholds in code. Use choice for one candidate, separate noul questions for multiple matches, and score for ordered relevance. An explicit none choice means no suitable candidate. Uncertainty is a successful answer, not a transport error. Jev confidence describes a distribution, not correctness.

Dispatch and authority

The canonical registry tool is decide. Scripts reach it through salix.call. Loops call it through their allowlist and ordinary session tool dispatch. Agent disclosure, Loop incarnation checks, and dependency admission stay authoritative. The capability adds no entity, persistent decision record, permission grant, or speculative replay eligibility. A decision cannot authorize access.

The provider endpoint, model, and key are operator configuration, never tool arguments. The server loads decide.api_key, endpoint, model, and provider from config.json at startup. endpoint is the full request URL and can point to a Jev-compatible service. Cloudflare Clef uses a Workers AI ai/run URL, model clef, and provider cloudflare. An absent or empty api_key disables the provider. Invalid configuration returns not_configured. Provider traffic passes through the LLM metering and encrypted-archive seam with Agent, Session, round, Tenant, and billing context. No input, credentials, or raw provider errors enter metric labels or ordinary error messages. Provider bodies have a 64 KiB read cap. Oversized responses archive the bounded prefix with a truncation marker, then fail.

Archive

Archive is read-only and keeps Messages, history and resources. archived_from_status and archived_at define restore. Product authorization gates archive and restore. Archive unbinds a Task Schedule; restore does not rebind it. A local card is not archive state.

Telegram topics

Enable BotFather Threaded Mode and Disallow users to create new threads. General and unbound topics enter Router; bound topics enter their Task. telegram.open_task_topic adds a text Participant. User and Worker turns skip Router by default unless the Task ended. Router instructions skip Topic. Retirement restores normal routing. Explicit and saved targets stay unchanged. Comma owns history, files, approval and status controls. Service events keep Task status. Reserve before the creation HTTP call. Recover uncertain creation manually. Never retry uncertain sends. Disconnect revokes access. Task streams keep Worker identity during waits, except activity and typing.

Graph retirement release

The exclusive migration keeps Task IDs, history, files, Sessions, status and the responsible Worker. Graph state becomes historical metadata. Extra graph Agents become inactive. Worker and initiator get ordinary subscriptions. Only active Tasks get a deduplicated handoff. Missing ownership or conflicting history fails conversion. Late graph tool calls cannot advance state. External effects are not exactly-once.

  1. Follow human shutdown approval and recovery.
  2. Inspect affected Tasks with bounded reads.
  3. Back up affected Conversation and participant storage and record restore evidence.
  4. Run SalixIM.Release.retire_task_graphs(confirm_no_writers: true) in an approved mainline release.
  5. Keep writers stopped through conversion and projection writes (2,100 seconds, pages of at most 500 keys).

Before conversion, restore the saved snapshot if needed. After conversion, forward-repair with the same history and deduplication keys. Do not use the old runtime.