@ziggs-ai/agent-sdk 0.48.14 → 0.48.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.48.16
6
+
7
+ ## 0.48.15
8
+
5
9
  ## 0.48.14
6
10
 
7
11
  ## 0.48.13
package/dist/Agent.d.ts CHANGED
@@ -271,6 +271,8 @@ export declare class Agent {
271
271
  private stateTimers;
272
272
  /** The agent's own check-backs, kept so a restart re-arms them. */
273
273
  private wakeLedger;
274
+ /** Retries so far for an own wake whose turn failed, by wake id. */
275
+ private readonly wakeRetries;
274
276
  /** The per-agent inbox long-poll loop — this agent's sole wake source. */
275
277
  private inboxLoop;
276
278
  private inboxLoopEnabled;
@@ -498,6 +500,16 @@ export declare class Agent {
498
500
  * restart arms it again.
499
501
  */
500
502
  private armOwnWake;
503
+ /**
504
+ * An agent's own wake whose turn failed is armed again, after a pause that
505
+ * doubles each time. The wake is an appointment the agent is counting on:
506
+ * without this, a single failed turn (a tick timeout, a lost worker) drops
507
+ * it until the host restarts, and the agent waits for a wake that never
508
+ * comes. A wake the agent has since replaced with a newer one is left
509
+ * alone. After the last retry the wake stays saved, so a restart still
510
+ * arms it.
511
+ */
512
+ private retryOwnWake;
501
513
  /**
502
514
  * Arm again the check-backs this agent asked for before the process went
503
515
  * down. A wake whose time passed in the meantime fires on the next turn,
package/dist/Agent.js CHANGED
@@ -7,7 +7,7 @@ import { withAgreementContext } from './runtime/agreementContext.js';
7
7
  import { agreementLaneId, isContextAccessRequest } from '@ziggs-ai/api-client';
8
8
  import { createDeclaredPollRunner } from './platform/polls/declaredPollRunner.js';
9
9
  import { AsyncLocalStorage } from 'node:async_hooks';
10
- import { contextScopesFromWake, WakeEffects, workScopeFromWake } from './runtime/wakeEffects.js';
10
+ import { contextScopesFromWake, uniqueWorkScope, WakeEffects, workScopeFromWake } from './runtime/wakeEffects.js';
11
11
  import { ExecutionController, asWorkTool, executionControllers } from './runtime/executionController.js';
12
12
  export { workScopeFromWake } from './runtime/wakeEffects.js';
13
13
  import { ZiggsBrain } from './brain/ZiggsBrain.js';
@@ -197,6 +197,9 @@ function createBackendServices(options) {
197
197
  telemetryClient,
198
198
  };
199
199
  }
200
+ /** A failed own wake is armed again after 30 s, then 1, 2, 4 and 8 minutes. */
201
+ const WAKE_RETRY_BASE_MS = 30_000;
202
+ const WAKE_RETRY_LIMIT = 5;
200
203
  /**
201
204
  * One agent identity and its body: inbox, tools, contracts, memory and lanes.
202
205
  * The brain decides on each wake; platform services perform its effects.
@@ -226,6 +229,8 @@ export class Agent {
226
229
  stateTimers;
227
230
  /** The agent's own check-backs, kept so a restart re-arms them. */
228
231
  wakeLedger;
232
+ /** Retries so far for an own wake whose turn failed, by wake id. */
233
+ wakeRetries = new Map();
229
234
  /** The per-agent inbox long-poll loop — this agent's sole wake source. */
230
235
  inboxLoop = null;
231
236
  inboxLoopEnabled;
@@ -460,10 +465,14 @@ export class Agent {
460
465
  // cannot consume a timer armed while that work was running.
461
466
  this.stateTimers = new StateTimers((ev, laneKey) => {
462
467
  const work = this.eventQueue.enqueue(ev, laneKey).then(() => {
463
- if (ev.type === 'wake-at')
468
+ if (ev.type === 'wake-at') {
469
+ this.wakeRetries.delete(ev.wakeId);
464
470
  this.wakeLedger.done(laneKey, ev.wakeId);
471
+ }
465
472
  }).catch((err) => {
466
473
  runtimeLog.warn('Agent', `state-timer frame failed laneKey=${laneKey}: ${err?.message || err}`);
474
+ if (ev.type === 'wake-at')
475
+ this.retryOwnWake(ev, laneKey);
467
476
  });
468
477
  this.wakeLedger.track(work);
469
478
  });
@@ -1824,6 +1833,38 @@ export class Agent {
1824
1833
  });
1825
1834
  return { ...armed, durable: this.wakeLedger.durable };
1826
1835
  }
1836
+ /**
1837
+ * An agent's own wake whose turn failed is armed again, after a pause that
1838
+ * doubles each time. The wake is an appointment the agent is counting on:
1839
+ * without this, a single failed turn (a tick timeout, a lost worker) drops
1840
+ * it until the host restarts, and the agent waits for a wake that never
1841
+ * comes. A wake the agent has since replaced with a newer one is left
1842
+ * alone. After the last retry the wake stays saved, so a restart still
1843
+ * arms it.
1844
+ */
1845
+ retryOwnWake(ev, laneKey) {
1846
+ const armed = this.stateTimers.peek(laneKey);
1847
+ if (armed?.kind === 'wake-at' && armed.wakeId !== ev.wakeId) {
1848
+ this.wakeRetries.delete(ev.wakeId);
1849
+ return;
1850
+ }
1851
+ const attempt = (this.wakeRetries.get(ev.wakeId) ?? 0) + 1;
1852
+ if (attempt > WAKE_RETRY_LIMIT) {
1853
+ this.wakeRetries.delete(ev.wakeId);
1854
+ runtimeLog.warn('Agent', `wake-at laneKey=${laneKey} failed ${WAKE_RETRY_LIMIT} retries; kept for the next host start`);
1855
+ return;
1856
+ }
1857
+ this.wakeRetries.set(ev.wakeId, attempt);
1858
+ const delayMs = WAKE_RETRY_BASE_MS * 2 ** (attempt - 1);
1859
+ const scope = uniqueWorkScope([{ agreementId: ev.agreementId, taskId: ev.taskId }]);
1860
+ try {
1861
+ this.stateTimers.armWakeAt(laneKey, Date.now() + delayMs, ev.reason, scope, ev.wakeId);
1862
+ runtimeLog.info('Agent', `re-armed failed wake-at laneKey=${laneKey} in ${delayMs}ms (retry ${attempt}/${WAKE_RETRY_LIMIT})`);
1863
+ }
1864
+ catch (err) {
1865
+ runtimeLog.warn('Agent', `could not re-arm failed wake-at laneKey=${laneKey}: ${err?.message || err}`);
1866
+ }
1867
+ }
1827
1868
  /**
1828
1869
  * Arm again the check-backs this agent asked for before the process went
1829
1870
  * down. A wake whose time passed in the meantime fires on the next turn,
@@ -219,6 +219,33 @@ function proposalOutcomeLine(reason, agreementId) {
219
219
  'This wake does not carry the conversation that led to it; read that request (message_list) if you need it. ' +
220
220
  'Do not greet the provider or open a new conversation.';
221
221
  }
222
+ /**
223
+ * What the tasks this task handed out have done. A delegated task's result
224
+ * reaches the delegator only as a returned output artifact, and the wake that
225
+ * carries it is a reason to act, so each returned result is said in words with
226
+ * how to read it. Without this the delegator sees only its own task and
227
+ * concludes nothing has come back.
228
+ */
229
+ function renderDelegationLines(inputs, delegations, lines) {
230
+ const returnedNow = new Set((Array.isArray(inputs) ? inputs : [])
231
+ .filter((input) => input?.reason === 'delegation_returned' && typeof input.eventId === 'string')
232
+ .map((input) => String(input.eventId).replace(/^delegation-return:/, '')));
233
+ if (!Array.isArray(delegations) || delegations.length === 0)
234
+ return;
235
+ const rows = delegations;
236
+ for (const row of rows) {
237
+ if (typeof row?.taskId !== 'string')
238
+ continue;
239
+ const artifact = typeof row.returnedArtifactId === 'string' ? row.returnedArtifactId : null;
240
+ if (artifact)
241
+ lines.push(`Work signal: task ${row.taskId}, which you handed out from this task, ${returnedNow.has(row.taskId) ? 'just returned' : 'has returned'} its result as artifact ${artifact}. ` +
242
+ `Read it (context_read type "artifacts", via "artifact:${artifact}") and carry the work on with it.`);
243
+ else if (row.state === 'completed')
244
+ lines.push(`Delegated task ${row.taskId} is completed; its result has not been returned to this task yet.`);
245
+ else if (typeof row.state === 'string')
246
+ lines.push(`Delegated task ${row.taskId} is ${row.state}.`);
247
+ }
248
+ }
222
249
  /**
223
250
  * What arrived for this task since its last wake. A proposal made inside the
224
251
  * task reports its outcome here, on the task, where the work it is for can be
@@ -374,6 +401,7 @@ function renderEventLines(event, lines, now) {
374
401
  if (typeof result.taskId === 'string')
375
402
  lines.push(`Task: ${result.taskId}`);
376
403
  renderTaskInputLines(result.inputs, typeof result.taskId === 'string' ? result.taskId : undefined, lines);
404
+ renderDelegationLines(result.inputs, result.delegations, lines);
377
405
  if (typeof result.agreementId === 'string')
378
406
  lines.push(`Agreement: ${result.agreementId}`);
379
407
  if (typeof result.state === 'string')
@@ -1,4 +1,4 @@
1
- import { isBroadcastTarget, partyActorIds } from '@ziggs-ai/api-client';
1
+ import { partyActorIds } from '@ziggs-ai/api-client';
2
2
  export function getBatchEvents(rawEvent) {
3
3
  if (!rawEvent)
4
4
  return [];
@@ -13,7 +13,13 @@ export function isTaskResultRelevantToAgent(result, ownAgentId) {
13
13
  const parties = partiesOf(result);
14
14
  return !!(result['creatorIsYou'] || result['providerIsYou'] || result['payerIsYou'] || result['proposedToIsYou'] ||
15
15
  partyActorIds(parties).includes(ownAgentId) ||
16
- isBroadcastTarget(parties?.proposedTo?.principal));
16
+ // An open request carries its seats and names nobody on its proposed-to side.
17
+ (claimSeatsOf(result) != null &&
18
+ !!parties?.proposedTo && !parties.proposedTo.principal && !parties.proposedTo.actor));
19
+ }
20
+ /** The seats an offer carries, on a task_result payload's agreement. */
21
+ function claimSeatsOf(result) {
22
+ return result['agreement']?.claimSeats;
17
23
  }
18
24
  /** The agreement's party slots on a task_result payload, when it carries one. */
19
25
  export function partiesOf(result) {
@@ -85,6 +85,7 @@ export declare class StateTimers {
85
85
  kind: 'liveness' | 'wake-at';
86
86
  firesAt: number;
87
87
  reason: string | null;
88
+ wakeId: string | null;
88
89
  } | null;
89
90
  /**
90
91
  * Consume the timer for a frame that survived stripStale. Liveness tracks
@@ -54,6 +54,7 @@ export class StateTimers {
54
54
  this._timers.set(laneKey, {
55
55
  epoch,
56
56
  kind: 'liveness',
57
+ wakeId: null,
57
58
  state,
58
59
  reason: null,
59
60
  timeoutMs,
@@ -101,6 +102,7 @@ export class StateTimers {
101
102
  this._timers.set(laneKey, {
102
103
  epoch,
103
104
  kind: 'wake-at',
105
+ wakeId,
104
106
  state: '',
105
107
  reason,
106
108
  timeoutMs: delayMs,
@@ -113,7 +115,7 @@ export class StateTimers {
113
115
  /** What is armed on this lane, if anything. Read by the specs and by `wake_at`. */
114
116
  peek(laneKey) {
115
117
  const t = this._timers.get(laneKey);
116
- return t ? { kind: t.kind, firesAt: t.firesAt, reason: t.reason } : null;
118
+ return t ? { kind: t.kind, firesAt: t.firesAt, reason: t.reason, wakeId: t.wakeId } : null;
117
119
  }
118
120
  /**
119
121
  * Consume the timer for a frame that survived stripStale. Liveness tracks
@@ -96,6 +96,14 @@ export interface InboxPassResult {
96
96
  alreadyRunning: number;
97
97
  /** Assigned rows left for a later pass because every wake slot was busy. */
98
98
  deferred: number;
99
+ /**
100
+ * Assigned task receipts whose task is not this agent's move yet: handed to
101
+ * someone else, or a run of it is in progress. Left pending, not failed: the
102
+ * receipt becomes ready when the task comes back, and its wake carries it
103
+ * then. Until something new arrives the loop holds its read instead of
104
+ * reading the same rows again.
105
+ */
106
+ waiting: number;
99
107
  }
100
108
  /** How many assigned wakes one agent runs at once unless told otherwise. */
101
109
  export declare const DEFAULT_INBOX_CONCURRENCY = 4;
@@ -237,6 +237,7 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
237
237
  let dispatched = 0;
238
238
  let alreadyRunning = 0;
239
239
  let deferred = 0;
240
+ let waiting = 0;
240
241
  // A pass with its own dispatch waits for its wakes; the loop's does not.
241
242
  const detached = opts.dispatch !== undefined;
242
243
  const dispatch = opts.dispatch ?? new InboxDispatch(deps.concurrency);
@@ -472,7 +473,13 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
472
473
  handledSoFar.add(deliveryHandlingId(receipt));
473
474
  continue;
474
475
  }
475
- if (receipt.executionBlocked || receipt.actionState !== 'ready')
476
+ if (receipt.executionBlocked)
477
+ continue;
478
+ if (receipt.actionState === 'waiting') {
479
+ waiting++;
480
+ continue;
481
+ }
482
+ if (receipt.actionState !== 'ready')
476
483
  continue;
477
484
  const id = receipt.action.id;
478
485
  const existing = taskActions.get(id);
@@ -610,10 +617,11 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
610
617
  acked = true;
611
618
  log(label, `acked up to ${envelope.ackTo}`);
612
619
  }
613
- else if (envelope.ackTo && !failures && (runningHere || alreadyRunning || deferred)) {
614
- // Nothing failed: those rows are still running, or wait for a slot. Each
615
- // running wake acknowledges its own row when it finishes.
616
- log(label, `${runningHere + alreadyRunning} assigned wake(s) still running, ${deferred} waiting for a slot; each is acknowledged when it finishes`);
620
+ else if (envelope.ackTo && !failures && (runningHere || alreadyRunning || deferred || waiting)) {
621
+ // Nothing failed: those rows are still running, wait for a slot, or wait
622
+ // for their task to come back. Each is acknowledged by the wake that
623
+ // handles it.
624
+ log(label, `${runningHere + alreadyRunning} assigned wake(s) still running, ${deferred} waiting for a slot, ${waiting} task receipt(s) waiting for their task; each is acknowledged when it is handled`);
617
625
  }
618
626
  else if (envelope.ackTo) {
619
627
  warn(label, `holding the watermark at ${envelope.ackTo} — ${failures} handover(s) failed this pass, so the ` +
@@ -633,6 +641,7 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
633
641
  dispatched,
634
642
  alreadyRunning,
635
643
  deferred,
644
+ waiting,
636
645
  };
637
646
  }
638
647
  /**
@@ -713,6 +722,10 @@ export function runInboxLoop(deps, opts = {}) {
713
722
  let running = true;
714
723
  let consecutiveErrors = 0;
715
724
  let heldPasses = 0;
725
+ // The last pass left task receipts waiting for their task. Nothing here can
726
+ // move them, so the next read waits for new mail rather than answering at
727
+ // once with the same rows.
728
+ let waitingRows = false;
716
729
  let lastPassAt = null;
717
730
  let lastAttemptAt = null;
718
731
  let first = true;
@@ -735,11 +748,12 @@ export function runInboxLoop(deps, opts = {}) {
735
748
  signal: shutdown.signal,
736
749
  dispatch,
737
750
  ...(held ? { waitSignal: held.signal } : {}),
738
- ...(!now && seen && dispatch.size > 0 && !heldPasses ? { seen } : {}),
751
+ ...(!now && seen && (dispatch.size > 0 || waitingRows) && !heldPasses ? { seen } : {}),
739
752
  });
740
753
  held = null;
741
754
  if (pass.bellAt)
742
755
  seen = pass.bellAt;
756
+ waitingRows = pass.waiting > 0;
743
757
  lastPassAt = Date.now();
744
758
  first = false;
745
759
  consecutiveErrors = 0;
@@ -42,6 +42,15 @@ export declare class TaskService {
42
42
  * Either step failing leaves the completion itself untouched.
43
43
  */
44
44
  private delegatedOutput;
45
+ /** The text of the outputs this agent recorded on the task, each under its name. */
46
+ private outputBodies;
47
+ /**
48
+ * Return the completed task's output to the work that handed it out. The
49
+ * run that completed it can end, or its audience change, before the return
50
+ * lands ("Execution context is no longer current", "The work audience or
51
+ * authority changed"); returning its own finished output does not need that
52
+ * run, so the return is tried once more outside it.
53
+ */
45
54
  private returnDelegatedOutput;
46
55
  /**
47
56
  * Say who this task is waiting on, with no other progress to post.
@@ -1,4 +1,4 @@
1
- import { createTask, getTask, getActiveTasksForAgent, getSubtasks, updateTaskState, updateTaskPlanStep, updateTaskPlanSteps, cancelTask, reportTask, setTaskSatisfaction, countTasks, acknowledgeTaskControl, presentTaskOutcome, returnTaskResult, ArtifactsClient, } from '@ziggs-ai/api-client';
1
+ import { createTask, getTask, getActiveTasksForAgent, getSubtasks, updateTaskState, updateTaskPlanStep, updateTaskPlanSteps, cancelTask, reportTask, setTaskSatisfaction, countTasks, acknowledgeTaskControl, presentTaskOutcome, returnTaskResult, ArtifactsClient, withWorkExecution, ARTIFACT_INLINE_TEXT_MAX_CHARS, } from '@ziggs-ai/api-client';
2
2
  import { runtimeLog } from '../../shared/runtimeLog.js';
3
3
  function safeJsonStringify(value) {
4
4
  if (value === null || value === undefined)
@@ -100,12 +100,20 @@ export class TaskService {
100
100
  if (!task?.delegation || task.delegation.returnedArtifactId)
101
101
  return undefined;
102
102
  const summary = result?.summary;
103
- const text = typeof summary === 'string' ? summary : safeJsonStringify(result);
104
- if (!text || !String(text).trim())
103
+ const head = typeof summary === 'string' ? summary : safeJsonStringify(result);
104
+ const artifacts = new ArtifactsClient(this.creds.operatorKey, this.creds.agentId);
105
+ // Only one output goes back to the delegator, so it carries the bodies of
106
+ // the other outputs this task made: the pages or drafts themselves, not
107
+ // only the line that names them.
108
+ const bodies = await this.outputBodies(artifacts, taskId);
109
+ const text = [head, ...bodies].filter((part) => !!part && !!String(part).trim()).join('\n\n');
110
+ if (!text.trim())
105
111
  return undefined;
106
- const recorded = await new ArtifactsClient(this.creds.operatorKey, this.creds.agentId).writeStrict({
112
+ const recorded = await artifacts.writeStrict({
107
113
  taskId,
108
- text: String(text),
114
+ text: text.length > ARTIFACT_INLINE_TEXT_MAX_CHARS
115
+ ? `${text.slice(0, ARTIFACT_INLINE_TEXT_MAX_CHARS - 80)}\n\n[cut: the outputs are longer than one result can carry]`
116
+ : text,
109
117
  name: `Result of task ${taskId}`,
110
118
  ...(idempotencyKey ? { idempotencyKey: `${idempotencyKey}:output` } : {}),
111
119
  });
@@ -116,9 +124,39 @@ export class TaskService {
116
124
  return undefined;
117
125
  }
118
126
  }
127
+ /** The text of the outputs this agent recorded on the task, each under its name. */
128
+ async outputBodies(artifacts, taskId) {
129
+ try {
130
+ const listed = await artifacts.list({ taskId });
131
+ return listed.artifacts
132
+ .filter((a) => a.linkRole === 'output' && a.sender?.id === this.creds.agentId && !!a.text?.trim())
133
+ .map((a) => `## ${a.name?.trim() || a.artifactId}\n\n${a.text.trim()}`);
134
+ }
135
+ catch (error) {
136
+ runtimeLog.warn('TaskService', `Outputs of ${taskId} not read for its result: ${error.message}`);
137
+ return [];
138
+ }
139
+ }
140
+ /**
141
+ * Return the completed task's output to the work that handed it out. The
142
+ * run that completed it can end, or its audience change, before the return
143
+ * lands ("Execution context is no longer current", "The work audience or
144
+ * authority changed"); returning its own finished output does not need that
145
+ * run, so the return is tried once more outside it.
146
+ */
119
147
  async returnDelegatedOutput(taskId, artifactId) {
148
+ const attempt = () => returnTaskResult(taskId, artifactId, this.creds);
149
+ const outsideRun = () => withWorkExecution(undefined, () => returnTaskResult(taskId, artifactId, { ...this.creds, executionContextId: undefined }));
120
150
  try {
121
- const returned = await returnTaskResult(taskId, artifactId, this.creds);
151
+ let returned;
152
+ try {
153
+ returned = await attempt();
154
+ }
155
+ catch (error) {
156
+ if (!/no longer current|stale|authority changed|fresh authorized execution/i.test(error.message))
157
+ throw error;
158
+ returned = await outsideRun();
159
+ }
122
160
  runtimeLog.info('TaskService', `Delegated result returned: ${taskId} → ${returned.parentTaskId} (${artifactId}, ${returned.outcome})`);
123
161
  }
124
162
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ziggs-ai/agent-sdk",
3
- "version": "0.48.14",
3
+ "version": "0.48.16",
4
4
  "description": "Agent framework SDK for building autonomous agents on the Ziggs platform",
5
5
  "homepage": "https://ziggsai.com/docs",
6
6
  "bugs": {
@@ -30,8 +30,8 @@
30
30
  "@anthropic-ai/claude-agent-sdk": "^0.3.284",
31
31
  "@anthropic-ai/sdk": "^0.110.0",
32
32
  "@modelcontextprotocol/sdk": "^1.29.0",
33
- "@ziggs-ai/api-client": "0.42.12",
34
- "@ziggs-ai/contracts": "0.50.8",
33
+ "@ziggs-ai/api-client": "0.42.14",
34
+ "@ziggs-ai/contracts": "0.50.20",
35
35
  "ajv": "^8.17.1",
36
36
  "dotenv": "^17.2.3",
37
37
  "openai": "^4.0.0",