@ziggs-ai/agent-sdk 0.48.15 → 0.48.17

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.17
6
+
7
+ ## 0.48.16
8
+
5
9
  ## 0.48.15
6
10
 
7
11
  ## 0.48.14
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,
@@ -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;
@@ -2,6 +2,14 @@ import type { TaskUpdateState } from '@ziggs-ai/contracts';
2
2
  import type { WriteSource } from '@ziggs-ai/api-client';
3
3
  import { type HeldTaskCreate, type Task } from '@ziggs-ai/api-client';
4
4
  import type { CountTasksFilters, CreateTaskData, TaskChargeStatement } from '@ziggs-ai/api-client';
5
+ /**
6
+ * What goes back to the delegator as one output: the summary, the result's
7
+ * other fields, and the bodies of the outputs the task made. An agent that
8
+ * puts its drafts in the result (`{ summary, rows: [...] }`) and records no
9
+ * output of its own used to return the summary line alone, and the delegator
10
+ * had nothing to review.
11
+ */
12
+ export declare function delegatedResultText(result: unknown, bodies: readonly string[]): string;
5
13
  export declare class TaskService {
6
14
  private creds;
7
15
  constructor(operatorKey: string, agentId: string);
@@ -1,5 +1,30 @@
1
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
+ /**
4
+ * What goes back to the delegator as one output: the summary, the result's
5
+ * other fields, and the bodies of the outputs the task made. An agent that
6
+ * puts its drafts in the result (`{ summary, rows: [...] }`) and records no
7
+ * output of its own used to return the summary line alone, and the delegator
8
+ * had nothing to review.
9
+ */
10
+ export function delegatedResultText(result, bodies) {
11
+ const summary = result?.summary;
12
+ const head = typeof summary === 'string' ? summary : safeJsonStringify(result);
13
+ const rest = typeof summary === 'string' && result && typeof result === 'object' && !Array.isArray(result)
14
+ ? Object.fromEntries(Object.entries(result)
15
+ .filter(([key, value]) => key !== 'summary' && value !== undefined && value !== null && value !== ''))
16
+ : {};
17
+ let fields;
18
+ if (Object.keys(rest).length) {
19
+ try {
20
+ fields = `## Result\n\n${JSON.stringify(rest, null, 2)}`;
21
+ }
22
+ catch {
23
+ fields = `## Result\n\n${String(safeJsonStringify(rest))}`;
24
+ }
25
+ }
26
+ return [head, fields, ...bodies].filter((part) => !!part && !!String(part).trim()).join('\n\n');
27
+ }
3
28
  function safeJsonStringify(value) {
4
29
  if (value === null || value === undefined)
5
30
  return value;
@@ -99,14 +124,12 @@ export class TaskService {
99
124
  const task = await getTask(taskId, this.creds);
100
125
  if (!task?.delegation || task.delegation.returnedArtifactId)
101
126
  return undefined;
102
- const summary = result?.summary;
103
- const head = typeof summary === 'string' ? summary : safeJsonStringify(result);
104
127
  const artifacts = new ArtifactsClient(this.creds.operatorKey, this.creds.agentId);
105
128
  // Only one output goes back to the delegator, so it carries the bodies of
106
129
  // the other outputs this task made: the pages or drafts themselves, not
107
130
  // only the line that names them.
108
131
  const bodies = await this.outputBodies(artifacts, taskId);
109
- const text = [head, ...bodies].filter((part) => !!part && !!String(part).trim()).join('\n\n');
132
+ const text = delegatedResultText(result, bodies);
110
133
  if (!text.trim())
111
134
  return undefined;
112
135
  const recorded = await artifacts.writeStrict({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ziggs-ai/agent-sdk",
3
- "version": "0.48.15",
3
+ "version": "0.48.17",
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.13",
34
- "@ziggs-ai/contracts": "0.50.12",
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",