@ziggs-ai/agent-sdk 0.44.1 → 0.45.0

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,13 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.45.0
6
+
7
+ - A message wake runs on its thread's lane. The lane is named from the thread's first message, the work (agreement and task) and every reader, so a later message in the same thread, under the same work, read by the same people, lands on the same lane, and the agent's Claude session, saved session state and notes carry over between messages. A reader joining or leaving, or another agreement or task, starts a new lane: an agent carries over only what everyone reading can read. Notes on a thread lane are kept under `thread:<digest>`. Task wakes and messages with no known thread keep their execution lane. The default session resolver names a thread `thr-<rootMessageId>` before falling back to `msgn-<messageId>`. Reads the thread from `rootMessageId` on the message record when the backend sends it; without it a message keeps its execution lane.
8
+ - The inbox runs wakes side by side. Different threads and tasks run at once, up to `inboxConcurrency` (an Agent option, else `ZIGGS_AGENT_INBOX_CONCURRENCY`, else 4); one lane still runs one wake at a time. Assigned messages are handed over oldest first, so a thread reaches its lane in the order it was sent. The loop keeps reading while wakes run (every 3 seconds while busy, so a new thread starts without waiting for a running wake), never hands over a row whose wake is still running, and each wake acknowledges its own row when it finishes.
9
+ - `laneKeyFor(agentId, sessionId, wake?)` takes `{ execution, threadRootId }` in place of an execution context id. `threadLaneId` is exported.
10
+ - `EventQueue.enqueue(event, laneKey, execution?)` names the execution an event was handed over under. Events under two executions are never merged into one dispatch.
11
+
5
12
  ## 0.44.1
6
13
 
7
14
  - `task_set_result` takes `charge: { amount, basis }` on a completion, passed to `updateTaskState`. Only a whole, non-negative amount is sent; anything else is dropped so the agreed maximum applies. Requires api-client 0.40.1.
package/dist/Agent.d.ts CHANGED
@@ -196,6 +196,12 @@ export interface AgentOptions {
196
196
  * Disable for offline tests or callers that deliver wakes themselves.
197
197
  */
198
198
  inboxCatchUp?: boolean;
199
+ /**
200
+ * How many assigned wakes run at once. Different threads and tasks run side
201
+ * by side up to this bound; one lane still runs one wake at a time. Defaults
202
+ * to `ZIGGS_AGENT_INBOX_CONCURRENCY`, else 4.
203
+ */
204
+ inboxConcurrency?: number;
199
205
  }
200
206
  /**
201
207
  * One wake, as the brain received it.
@@ -213,6 +219,8 @@ export interface WakeRecord {
213
219
  sessionId: string;
214
220
  laneKey: string;
215
221
  executionContext?: WorkExecutionContext;
222
+ /** The thread a message wake belongs to, when it runs on a thread lane. */
223
+ threadRootId?: string;
216
224
  /** The event frame that woke the agent. */
217
225
  event: unknown;
218
226
  /** FSM context carried into the tick — undefined on a cold lane. */
package/dist/Agent.js CHANGED
@@ -21,7 +21,7 @@ export { DEFAULT_MODEL, resolveFleetModel } from './shared/fleetModel.js';
21
21
  import { contextReadTool, openTool, accessExplainTool } from './platform/tools/tier2/contextTools.js';
22
22
  import { EventQueue } from './platform/EventQueue.js';
23
23
  import { StateTimers } from './platform/StateTimers.js';
24
- import { laneKeyFor } from './platform/laneKey.js';
24
+ import { laneKeyFor, runInLane, threadLaneId } from './platform/laneKey.js';
25
25
  import { WakeLedger } from './platform/WakeLedger.js';
26
26
  import { WAKE_TOOLS } from './platform/tools/tier1/wakeTools.js';
27
27
  import { createZiggsEffectHandler } from './platform/ZiggsEffectHandler.js';
@@ -57,7 +57,10 @@ async function loadConnectionPool() {
57
57
  const mod = await import(/* @vite-ignore */ modPath);
58
58
  return mod.ConnectionPool;
59
59
  }
60
- const DEFAULT_SESSION_RESOLVER = (normalized) => normalized.addressId ?? (normalized.event.agreementId ? `agrn-${normalized.event.agreementId}` : normalized.event.messageId ? `msgn-${normalized.event.messageId}` : null);
60
+ const DEFAULT_SESSION_RESOLVER = (normalized) => normalized.addressId
61
+ ?? (normalized.event.agreementId ? `agrn-${normalized.event.agreementId}`
62
+ : normalized.event.threadRootId ? `thr-${normalized.event.threadRootId}`
63
+ : normalized.event.messageId ? `msgn-${normalized.event.messageId}` : null);
61
64
  /**
62
65
  * one lane key per unit of work, derived the same way as inbox wakes.
63
66
  *
@@ -280,6 +283,7 @@ export class Agent {
280
283
  metricsTap: resolved.metricsTap,
281
284
  wakeTap: resolved.wakeTap,
282
285
  inboxCatchUp: resolved.inboxCatchUp,
286
+ inboxConcurrency: resolved.inboxConcurrency,
283
287
  telemetryIngest: resolved.telemetryIngest,
284
288
  brain: resolved.brain,
285
289
  polls: resolved.polls,
@@ -444,7 +448,7 @@ export class Agent {
444
448
  toolManager: services.toolManager,
445
449
  promptBuilder: services.promptBuilder,
446
450
  });
447
- this.eventQueue = new EventQueue((event, laneKey) => this._processEvent(event, laneKey));
451
+ this.eventQueue = new EventQueue((event, laneKey, execution) => this._processEvent(event, laneKey, execution));
448
452
  // Timer dispatch is at-least-once. Only successful work checkpoints this
449
453
  // exact wake; a crash/failure leaves it durable, and an older completion
450
454
  // cannot consume a timer armed while that work was running.
@@ -619,7 +623,7 @@ export class Agent {
619
623
  if (!sessionId)
620
624
  return;
621
625
  const executionContext = event.executionContext;
622
- const laneKey = laneKeyFor(ownAgentId, sessionId, executionContext?.contextId);
626
+ const laneKey = laneKeyFor(ownAgentId, sessionId, { execution: executionContext });
623
627
  if (!this.sessions.has(laneKey)) {
624
628
  this.sessions.set(laneKey, { sessionId, ownAgentId, executionContext });
625
629
  }
@@ -637,7 +641,7 @@ export class Agent {
637
641
  agreementId,
638
642
  // Claimer/buyer — the canonical reply command explicitly names the requester.
639
643
  ...(actorId ? { senderId: actorId } : {}),
640
- }, laneKey);
644
+ }, laneKey, executionContext);
641
645
  }
642
646
  /** Wire entry. Normalize → resolve session → enqueue on the right lane. */
643
647
  async handleMessage(text, metadata = {}) {
@@ -696,10 +700,16 @@ export class Agent {
696
700
  return;
697
701
  }
698
702
  const executionContext = metadata.executionContext;
699
- const laneKey = laneKeyFor(ownAgentId, sessionId, executionContext?.contextId);
703
+ // A request in a thread runs on the thread's lane, so the agent keeps what
704
+ // it knew from the thread's earlier messages (see laneKeyFor).
705
+ const threadRootId = normalized.event.threadRootId;
706
+ const laneKey = laneKeyFor(ownAgentId, sessionId, { execution: executionContext, threadRootId });
700
707
  if (!this.sessions.has(laneKey)) {
701
708
  this.sessions.set(laneKey, { sessionId, ownAgentId, executionContext });
702
709
  }
710
+ const laneId = threadLaneId(executionContext ?? currentWorkExecution(), threadRootId);
711
+ if (laneId && threadRootId)
712
+ this.sessions.get(laneKey).thread = { rootMessageId: threadRootId, laneId };
703
713
  if (roomlessAgreementId)
704
714
  this.sessions.get(laneKey).roomlessAgreementId = roomlessAgreementId;
705
715
  // The inbox loop owns ack (act-before-ack, delivery law); the agent only
@@ -710,7 +720,7 @@ export class Agent {
710
720
  // the same message being processed twice; leaving it set on a failed wake
711
721
  // would make the redelivery this rejection buys us a no-op.
712
722
  try {
713
- await this.eventQueue.enqueue({ ...normalized.event, addressId: normalized.addressId }, laneKey);
723
+ await this.eventQueue.enqueue({ ...normalized.event, addressId: normalized.addressId }, laneKey, executionContext);
714
724
  }
715
725
  catch (err) {
716
726
  if (messageId)
@@ -756,6 +766,10 @@ export class Agent {
756
766
  }
757
767
  memoryForWake(session, event) {
758
768
  const execution = currentWorkExecution();
769
+ // A thread lane keeps its notes for the thread, under the same digest that
770
+ // names the lane: same thread, same work, same readers.
771
+ if (execution && session.thread)
772
+ return partitionMemoryStore(this.memory, `thread:${session.thread.laneId.slice('thr-'.length)}`);
759
773
  if (execution)
760
774
  return partitionMemoryStore(this.memory, `execution:${execution.contextId}`);
761
775
  const fromEvent = hireIdsFromEvent(event);
@@ -1095,11 +1109,18 @@ export class Agent {
1095
1109
  ...(inputRooms ? { inputRooms } : {}),
1096
1110
  };
1097
1111
  }
1098
- async _processEvent(event, laneKey) {
1099
- const context = this.sessions.get(laneKey)?.executionContext;
1100
- if (!context)
1101
- return this._processEventInContext(event, laneKey);
1102
- return runWorkExecution(context, this.options.operatorKey, () => this._processEventInContext(event, laneKey), resolveBackendUrl());
1112
+ async _processEvent(event, laneKey, execution) {
1113
+ const session = this.sessions.get(laneKey);
1114
+ // Each message of a thread is its own execution. The lane is serialized
1115
+ // here, so this wake's authority can replace the last one's safely.
1116
+ if (session && execution)
1117
+ session.executionContext = execution;
1118
+ const context = session?.executionContext;
1119
+ return runInLane(this.options.agentId, laneKey, () => {
1120
+ if (!context)
1121
+ return this._processEventInContext(event, laneKey);
1122
+ return runWorkExecution(context, this.options.operatorKey, () => this._processEventInContext(event, laneKey), resolveBackendUrl());
1123
+ });
1103
1124
  }
1104
1125
  async _processEventInContext(event, laneKey) {
1105
1126
  const session = this.sessions.get(laneKey);
@@ -1223,6 +1244,7 @@ export class Agent {
1223
1244
  try {
1224
1245
  this.options.wakeTap({
1225
1246
  executionContext: session.executionContext,
1247
+ ...(session.thread ? { threadRootId: session.thread.rootMessageId } : {}),
1226
1248
  agentId: identity.agentId,
1227
1249
  sessionId: identity.sessionId,
1228
1250
  laneKey,
@@ -1588,9 +1610,11 @@ export class Agent {
1588
1610
  runtimeLog.info(this.options.name || 'agent', `replay: no wake on ${record.sessionId} — ${suppressed.because}`);
1589
1611
  return { state: record.state };
1590
1612
  }
1613
+ const replayThread = threadLaneId(record.executionContext, record.threadRootId);
1591
1614
  const memory = this.memoryForWake({
1592
1615
  sessionId: record.sessionId,
1593
1616
  ctx: record.ctx,
1617
+ ...(replayThread ? { thread: { laneId: replayThread } } : {}),
1594
1618
  }, record.event);
1595
1619
  // Same watchdog as a live wake, for the same reason: an unaborted Claude
1596
1620
  // query outlives the promise that abandoned it and keeps spending.
@@ -1682,6 +1706,7 @@ export class Agent {
1682
1706
  ownAgentId: this.options.agentId,
1683
1707
  seen: this.seenMessages,
1684
1708
  label,
1709
+ concurrency: this.options.inboxConcurrency,
1685
1710
  onMessage: (text, metadata) => {
1686
1711
  return this.handleMessage(text, metadata);
1687
1712
  },
@@ -1725,6 +1750,7 @@ export class Agent {
1725
1750
  // The conversation the lane's messages came from, so a restarted host
1726
1751
  // answers there too instead of reading the lane name as an address.
1727
1752
  const addressId = this.sessions.get(laneKey)?.addressId;
1753
+ const thread = this.sessions.get(laneKey)?.thread;
1728
1754
  this.wakeLedger.arm({
1729
1755
  laneKey,
1730
1756
  sessionId,
@@ -1733,6 +1759,7 @@ export class Agent {
1733
1759
  reason,
1734
1760
  ...(scope ? { scope } : {}),
1735
1761
  ...(addressId ? { addressId } : {}),
1762
+ ...(thread ? { threadRootId: thread.rootMessageId } : {}),
1736
1763
  executionContext: currentWorkExecution() ? { ...currentWorkExecution(), attemptId: undefined } : undefined,
1737
1764
  });
1738
1765
  return { ...armed, durable: this.wakeLedger.durable };
@@ -1756,12 +1783,15 @@ export class Agent {
1756
1783
  return;
1757
1784
  }
1758
1785
  for (const wake of pending) {
1759
- if (wake.laneKey !== laneKeyFor(agentId, wake.sessionId, wake.executionContext?.contextId))
1786
+ if (wake.laneKey !== laneKeyFor(agentId, wake.sessionId, { execution: wake.executionContext, threadRootId: wake.threadRootId }))
1760
1787
  continue;
1761
1788
  if (this.stateTimers.peek(wake.laneKey))
1762
1789
  continue;
1763
1790
  if (!this.sessions.has(wake.laneKey)) {
1764
- this.sessions.set(wake.laneKey, { sessionId: wake.sessionId, ownAgentId: agentId, executionContext: wake.executionContext, ...(wake.addressId ? { addressId: wake.addressId } : {}) });
1791
+ const laneId = threadLaneId(wake.executionContext, wake.threadRootId);
1792
+ this.sessions.set(wake.laneKey, { sessionId: wake.sessionId, ownAgentId: agentId, executionContext: wake.executionContext,
1793
+ ...(laneId && wake.threadRootId ? { thread: { rootMessageId: wake.threadRootId, laneId } } : {}),
1794
+ ...(wake.addressId ? { addressId: wake.addressId } : {}) });
1765
1795
  }
1766
1796
  try {
1767
1797
  this.stateTimers.armWakeAt(wake.laneKey, wake.firesAt, wake.reason, wake.scope, wake.wakeId);
@@ -1812,7 +1842,7 @@ export class Agent {
1812
1842
  }
1813
1843
  const selected = currentWorkExecution();
1814
1844
  const sessionId = laneSessionIdForTask(full);
1815
- const laneKey = laneKeyFor(agentId, sessionId, selected?.contextId);
1845
+ const laneKey = laneKeyFor(agentId, sessionId, { execution: selected });
1816
1846
  if (!this.sessions.has(laneKey)) {
1817
1847
  this.sessions.set(laneKey, { sessionId, ownAgentId: agentId, executionContext: currentWorkExecution() });
1818
1848
  }
@@ -1827,7 +1857,7 @@ export class Agent {
1827
1857
  state,
1828
1858
  providerIsYou: true,
1829
1859
  },
1830
- }, laneKey);
1860
+ }, laneKey, selected);
1831
1861
  }
1832
1862
  /**
1833
1863
  * Stop taking work. Timers and polls stop at once; the inbox loop cancels
package/dist/index.d.ts CHANGED
@@ -31,7 +31,8 @@ export { EventQueue } from './platform/EventQueue.js';
31
31
  export type { EventQueueBusyLane, WaitForIdleResult } from './platform/EventQueue.js';
32
32
  export { StateTimers, MAX_WAKE_DELAY_MS } from './platform/StateTimers.js';
33
33
  export type { StateTimeoutEvent, WakeAtEvent, TimerEvent } from './platform/StateTimers.js';
34
- export { laneKeyFor } from './platform/laneKey.js';
34
+ export { laneKeyFor, threadLaneId } from './platform/laneKey.js';
35
+ export type { LaneWake, LaneExecution } from './platform/laneKey.js';
35
36
  export { wakeAtTool, WAKE_TOOLS } from './platform/tools/tier1/wakeTools.js';
36
37
  export type { WakeSchedulerPort } from './platform/tools/tier1/wakeTools.js';
37
38
  export { OutboxBuffer } from './platform/OutboxBuffer.js';
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ export { handlerBrain, ziggsBrain, claudeBrain, isBrainSelection, isClaudeCognit
31
31
  export { createZiggsEffectHandler } from './platform/ZiggsEffectHandler.js';
32
32
  export { EventQueue } from './platform/EventQueue.js';
33
33
  export { StateTimers, MAX_WAKE_DELAY_MS } from './platform/StateTimers.js';
34
- export { laneKeyFor } from './platform/laneKey.js';
34
+ export { laneKeyFor, threadLaneId } from './platform/laneKey.js';
35
35
  // "wake me at", for both brains.
36
36
  export { wakeAtTool, WAKE_TOOLS } from './platform/tools/tier1/wakeTools.js';
37
37
  export { OutboxBuffer } from './platform/OutboxBuffer.js';
@@ -13,6 +13,11 @@ export interface NormalizedEvent {
13
13
  * redelivery, so it anchors the wake's idempotency keys (deliveryWriteKeys).
14
14
  */
15
15
  messageId?: string;
16
+ /**
17
+ * The first message of the thread this message belongs to (its own id
18
+ * when it replies to nothing). It names the thread lane; it grants nothing.
19
+ */
20
+ threadRootId?: string;
16
21
  timestamp: number;
17
22
  /**
18
23
  * `notification` = lifecycle / status notice. Not counterparty
@@ -51,6 +56,8 @@ interface WireMetadata {
51
56
  taskId?: string;
52
57
  addressId?: string;
53
58
  messageId?: string;
59
+ /** The thread's first message, as the inbox read it from the message record. */
60
+ threadRootId?: string;
54
61
  entryType?: string;
55
62
  contentType?: string;
56
63
  operation?: string;
@@ -115,6 +115,7 @@ export function normalizeIncomingEvent({ text, metadata = {} }) {
115
115
  receiverId: receiverId || undefined,
116
116
  assigneeId: typeof metadata.assigneeId === 'string' ? metadata.assigneeId : undefined,
117
117
  messageId: typeof metadata.messageId === 'string' && metadata.messageId ? metadata.messageId : undefined,
118
+ ...(typeof metadata.threadRootId === 'string' && metadata.threadRootId ? { threadRootId: metadata.threadRootId } : {}),
118
119
  timestamp: Date.now(),
119
120
  ...(entryType ? { entryType } : {}),
120
121
  ...(metadata.intent === 'fyi' || metadata.intent === 'request' ? { intent: metadata.intent } : {}),
@@ -1,4 +1,9 @@
1
- export type ProcessEventFn = (event: unknown, laneKey: string) => Promise<void>;
1
+ import type { WorkExecutionContext } from '@ziggs-ai/api-client';
2
+ /**
3
+ * Runs one dispatch for a lane. `execution` is the execution the events in it
4
+ * were handed over under, when they named one.
5
+ */
6
+ export type ProcessEventFn = (event: unknown, laneKey: string, execution?: WorkExecutionContext) => Promise<void>;
2
7
  export interface EventQueueOptions {
3
8
  maxQueueLengthPerLane?: number;
4
9
  }
@@ -21,6 +26,11 @@ export interface WaitForIdleResult {
21
26
  * per laneKey at a time; multiple events arriving while busy are merged
22
27
  * into a single { type: 'batch', events: [...] } frame on the next pass.
23
28
  *
29
+ * Events handed over under different executions are never merged: each
30
+ * message of a thread is its own execution with its own authority, and one
31
+ * dispatch runs under one. An event that names no execution (a timer) joins
32
+ * whatever runs next.
33
+ *
24
34
  * `enqueue` REJECTS when the dispatch failed. It used to log the error
25
35
  * and resolve, which made every caller — including the inbox loop, whose next
26
36
  * statement is the ack — unable to tell a handled event from a lost one. A
@@ -33,7 +43,7 @@ export declare class EventQueue {
33
43
  private _state;
34
44
  private _metrics;
35
45
  constructor(processEventFn: ProcessEventFn, options?: EventQueueOptions);
36
- enqueue(event: unknown, laneKey: string): Promise<void>;
46
+ enqueue(event: unknown, laneKey: string, execution?: WorkExecutionContext): Promise<void>;
37
47
  private _processIfNeeded;
38
48
  private _processLoop;
39
49
  private _trimQueueIfNeeded;
@@ -5,6 +5,11 @@ import { runtimeLog } from '../shared/runtimeLog.js';
5
5
  * per laneKey at a time; multiple events arriving while busy are merged
6
6
  * into a single { type: 'batch', events: [...] } frame on the next pass.
7
7
  *
8
+ * Events handed over under different executions are never merged: each
9
+ * message of a thread is its own execution with its own authority, and one
10
+ * dispatch runs under one. An event that names no execution (a timer) joins
11
+ * whatever runs next.
12
+ *
8
13
  * `enqueue` REJECTS when the dispatch failed. It used to log the error
9
14
  * and resolve, which made every caller — including the inbox loop, whose next
10
15
  * statement is the ack — unable to tell a handled event from a lost one. A
@@ -24,7 +29,7 @@ export class EventQueue {
24
29
  ? Math.max(1, options.maxQueueLengthPerLane)
25
30
  : 100;
26
31
  }
27
- enqueue(event, laneKey) {
32
+ enqueue(event, laneKey, execution) {
28
33
  if (!laneKey) {
29
34
  runtimeLog.warn('EventQueue', 'enqueue called without laneKey, skipping');
30
35
  return Promise.resolve();
@@ -38,6 +43,7 @@ export class EventQueue {
38
43
  this._metrics.enqueued += 1;
39
44
  state.events.push({
40
45
  event,
46
+ ...(execution ? { execution } : {}),
41
47
  settle: (err) => (err === undefined ? resolve() : reject(err)),
42
48
  });
43
49
  this._trimQueueIfNeeded(state, laneKey);
@@ -56,9 +62,11 @@ export class EventQueue {
56
62
  if (!state)
57
63
  return;
58
64
  while (state.events.length > 0) {
59
- const batch = state.events.splice(0, state.events.length);
65
+ const batch = state.events.splice(0, sameExecutionRun(state.events));
60
66
  const events = batch.map(e => e.event);
61
67
  const settlers = batch.map(e => e.settle);
68
+ // Entries of one run share a context id; the newest copy is the one handed over last.
69
+ const execution = batch.map(e => e.execution).filter(Boolean).at(-1);
62
70
  const coalesced = events.length === 1
63
71
  ? events[0]
64
72
  : { type: 'batch', events };
@@ -66,7 +74,7 @@ export class EventQueue {
66
74
  // for all of it, so a failure belongs to every event that was merged in.
67
75
  let failure;
68
76
  try {
69
- await this._processEvent(coalesced, laneKey);
77
+ await this._processEvent(coalesced, laneKey, execution);
70
78
  }
71
79
  catch (error) {
72
80
  failure = error ?? new Error('processEvent failed');
@@ -141,3 +149,18 @@ export class EventQueue {
141
149
  };
142
150
  }
143
151
  }
152
+ /** How many leading entries can run as one dispatch: those under one execution, or none. */
153
+ function sameExecutionRun(entries) {
154
+ let contextId;
155
+ let n = 0;
156
+ for (; n < entries.length; n++) {
157
+ const id = entries[n].execution?.contextId;
158
+ if (id === undefined)
159
+ continue;
160
+ if (contextId === undefined)
161
+ contextId = id;
162
+ else if (id !== contextId)
163
+ break;
164
+ }
165
+ return n;
166
+ }
@@ -12,6 +12,8 @@ export interface SavedWake {
12
12
  /** The conversation the lane's own messages came from, when it has one. */
13
13
  addressId?: string;
14
14
  executionContext?: WorkExecutionContext;
15
+ /** The thread a thread lane carries, so a restart names the same lane. */
16
+ threadRootId?: string;
15
17
  }
16
18
  /**
17
19
  * Where an agent's own check-backs are kept, so a restart does not lose them.
@@ -63,6 +63,7 @@ export class WakeLedger {
63
63
  ...(saved.scope ? { scope: saved.scope } : {}),
64
64
  ...(typeof saved.addressId === 'string' && saved.addressId ? { addressId: saved.addressId } : {}),
65
65
  ...(saved.executionContext ? { executionContext: saved.executionContext } : {}),
66
+ ...(typeof saved.threadRootId === 'string' && saved.threadRootId ? { threadRootId: saved.threadRootId } : {}),
66
67
  });
67
68
  }
68
69
  return out;
@@ -97,6 +97,11 @@ export declare function executeToolWithSideEffects(deps: Pick<ZiggsEffectDeps, '
97
97
  * session-coupled deps (the `agents` roster) without forcing the Agent to
98
98
  * pass them through. Cache is bounded with simple LRU eviction (re-set on
99
99
  * read promotes the entry; oldest entry drops when size exceeds the cap).
100
+ *
101
+ * Inside a running wake the cache and the outbox are kept per lane as well:
102
+ * two lanes can share a session id (two threads under one agreement, read by
103
+ * different people) and run at the same time, and one must never see the
104
+ * other's roster or unsynced sends.
100
105
  */
101
106
  export declare function createZiggsEffectHandler(deps: ZiggsEffectDeps): EffectHandler;
102
107
  export {};
@@ -1,5 +1,6 @@
1
1
  import { MessageRecordsClient } from '@ziggs-ai/api-client';
2
2
  import { OutboxBuffer } from './OutboxBuffer.js';
3
+ import { currentLaneKey } from './laneKey.js';
3
4
  import { runtimeLog } from '../shared/runtimeLog.js';
4
5
  import { resolveBackendUrl } from '../shared/backendUrl.js';
5
6
  import { toolFailureText } from '../brain/toolFailureText.js';
@@ -287,14 +288,24 @@ export async function executeToolWithSideEffects(deps, eff, effect, roster) {
287
288
  * session-coupled deps (the `agents` roster) without forcing the Agent to
288
289
  * pass them through. Cache is bounded with simple LRU eviction (re-set on
289
290
  * read promotes the entry; oldest entry drops when size exceeds the cap).
291
+ *
292
+ * Inside a running wake the cache and the outbox are kept per lane as well:
293
+ * two lanes can share a session id (two threads under one agreement, read by
294
+ * different people) and run at the same time, and one must never see the
295
+ * other's roster or unsynced sends.
290
296
  */
291
297
  export function createZiggsEffectHandler(deps) {
292
298
  const contextCache = new Map();
293
299
  const outbox = new OutboxBuffer();
300
+ const scoped = (sessionId) => {
301
+ const lane = currentLaneKey();
302
+ return lane ? `${lane}\n${sessionId}` : sessionId;
303
+ };
294
304
  const cachePut = (sessionId, snap) => {
295
- if (contextCache.has(sessionId))
296
- contextCache.delete(sessionId);
297
- contextCache.set(sessionId, snap);
305
+ const key = scoped(sessionId);
306
+ if (contextCache.has(key))
307
+ contextCache.delete(key);
308
+ contextCache.set(key, snap);
298
309
  if (contextCache.size > CONTEXT_CACHE_MAX) {
299
310
  const oldest = contextCache.keys().next().value;
300
311
  if (oldest !== undefined)
@@ -302,10 +313,11 @@ export function createZiggsEffectHandler(deps) {
302
313
  }
303
314
  };
304
315
  const cacheGet = (sessionId) => {
305
- const snap = contextCache.get(sessionId);
316
+ const key = scoped(sessionId);
317
+ const snap = contextCache.get(key);
306
318
  if (snap !== undefined) {
307
- contextCache.delete(sessionId);
308
- contextCache.set(sessionId, snap);
319
+ contextCache.delete(key);
320
+ contextCache.set(key, snap);
309
321
  }
310
322
  return snap;
311
323
  };
@@ -335,7 +347,7 @@ export function createZiggsEffectHandler(deps) {
335
347
  unavailable: packets.some(p => p.unavailable),
336
348
  };
337
349
  const me = snap.agents.find((a) => a?.isYou)?.agentId || null;
338
- outbox.merge(effect.sessionId, snap.history, me);
350
+ outbox.merge(scoped(effect.sessionId), snap.history, me);
339
351
  cachePut(effect.sessionId, snap);
340
352
  return snap;
341
353
  }
@@ -399,7 +411,7 @@ export function createZiggsEffectHandler(deps) {
399
411
  }
400
412
  case 'send-message': {
401
413
  const sent = await deps.messageSender(effect.command);
402
- outbox.track(effect.sessionId, { text: effect.command.content.text, receiverId: sent.message.recipients[0]?.ref });
414
+ outbox.track(scoped(effect.sessionId), { text: effect.command.content.text, receiverId: sent.message.recipients[0]?.ref });
403
415
  return { ...sent, ok: true };
404
416
  }
405
417
  case 'record-event': {
@@ -36,6 +36,11 @@ export interface InboxLoopDeps {
36
36
  /** Host-only control observation for blocked task assignments; never a model wake. */
37
37
  onTaskControlCheck?: (taskId: string) => Promise<void>;
38
38
  label?: string;
39
+ /**
40
+ * How many assigned wakes run at once. Defaults to
41
+ * `ZIGGS_AGENT_INBOX_CONCURRENCY`, else {@link DEFAULT_INBOX_CONCURRENCY}.
42
+ */
43
+ concurrency?: number;
39
44
  }
40
45
  export interface InboxPassResult {
41
46
  /** Delivery references this envelope carried. */
@@ -62,26 +67,92 @@ export interface InboxPassResult {
62
67
  * again once it can run, so it neither holds the watermark nor slows the loop.
63
68
  */
64
69
  blocked: number;
70
+ /** Assigned messages and tasks whose wake this pass started. */
71
+ dispatched: number;
72
+ /**
73
+ * Assigned rows this pass skipped because a wake an earlier pass started for
74
+ * them is still running. The server lists a row until it is handled, so it
75
+ * comes back on every read while its wake runs; it is never handed over twice.
76
+ */
77
+ alreadyRunning: number;
78
+ /** Assigned rows left for a later pass because every wake slot was busy. */
79
+ deferred: number;
80
+ }
81
+ /** How many assigned wakes one agent runs at once unless told otherwise. */
82
+ export declare const DEFAULT_INBOX_CONCURRENCY = 4;
83
+ /**
84
+ * The wake bound for one agent: `explicit`, else `ZIGGS_AGENT_INBOX_CONCURRENCY`,
85
+ * else {@link DEFAULT_INBOX_CONCURRENCY}. Never below one.
86
+ */
87
+ export declare function inboxConcurrency(explicit?: number): number;
88
+ /** A dispatched job's place in the handover order. */
89
+ export interface HandoverTurn {
90
+ /** Resolves once every job dispatched before this one has handed over (or given up). */
91
+ ready: Promise<void>;
92
+ /** Say the handover has started, letting the next job hand over. */
93
+ done: () => void;
94
+ }
95
+ /**
96
+ * The wakes one inbox loop has handed over and not yet seen finish.
97
+ *
98
+ * Bounded: at most `limit` run at once. Keyed by what the server lists again
99
+ * while the work is pending (a receipt, a task), so a row that comes back on
100
+ * the next read while its wake still runs is never handed over twice. Ordered
101
+ * jobs hand over in the order they were dispatched: messages are dispatched
102
+ * oldest first, so the messages of one thread reach their lane in the order
103
+ * they were sent, and the lane runs them one at a time. Different threads run
104
+ * side by side.
105
+ */
106
+ export declare class InboxDispatch {
107
+ readonly limit: number;
108
+ private readonly running;
109
+ private lastTurn;
110
+ private readonly listeners;
111
+ private failed;
112
+ constructor(limit?: number);
113
+ /** Wakes running now. */
114
+ get size(): number;
115
+ get full(): boolean;
116
+ has(key: string): boolean;
117
+ /**
118
+ * Run `job` under `key`. It resolves `true` when its work was handed over
119
+ * and finished, `false` when it was not handled. An ordered job waits for
120
+ * `turn.ready` before it hands over and calls `turn.done()` once it has.
121
+ */
122
+ start(key: string, job: (turn: HandoverTurn) => Promise<boolean>, ordered?: boolean): Promise<void>;
123
+ /** Jobs that were not handled since the last call. The loop backs off on them. */
124
+ takeFailures(): number;
125
+ /** Resolves when any running job finishes, `ms` passes (if given), or `signal` aborts. */
126
+ settledOr(ms?: number, signal?: AbortSignal): Promise<void>;
127
+ /** Resolves when nothing is running. */
128
+ idle(): Promise<void>;
65
129
  }
66
130
  /**
67
131
  * One long-poll pass: hold up to `waitSeconds` for new inbox content, then read
68
132
  * the deltas, deliver them into the host, and ack. Returns what it delivered.
69
133
  * Reused each iteration of {@link runInboxLoop}; also usable as a single catch-up
70
134
  * read (`waitSeconds: 0`) at bootstrap.
135
+ *
136
+ * Assigned messages and tasks run as wakes, up to the agent's bound at once.
137
+ * Without `opts.dispatch` the pass waits for every wake it started before it
138
+ * returns. With one (the loop's own), the pass returns as soon as its wakes
139
+ * are started: each wake acknowledges its own row when it finishes, and rows
140
+ * the dispatch is still running are skipped.
71
141
  */
72
142
  export declare function pollInboxOnce(deps: InboxLoopDeps, waitSeconds?: number, opts?: {
73
143
  forceAck?: boolean;
74
144
  signal?: AbortSignal;
145
+ dispatch?: InboxDispatch;
75
146
  }): Promise<InboxPassResult>;
76
147
  export interface InboxLoopHandle {
77
148
  /**
78
- * Stop reading. An idle long-poll is cancelled at once; a pass already
79
- * handed to the host runs on so it can acknowledge what it finished, and
80
- * the host lease is released after that. A pass still running when
81
- * `timeoutMs` is up does not hold the lease: it is released anyway, and the
82
- * next host is handed whatever was not acknowledged. Resolves `true` when
83
- * the pass finished inside the bound, `false` when the lease was released
84
- * out from under it.
149
+ * Stop reading. An idle long-poll is cancelled at once; a pass and the
150
+ * wakes already handed to the host run on so they can acknowledge what they
151
+ * finished, and the host lease is released after that. Work still running
152
+ * when `timeoutMs` is up does not hold the lease: it is released anyway, and
153
+ * the next host is handed whatever was not acknowledged. Resolves `true`
154
+ * when everything finished inside the bound, `false` when the lease was
155
+ * released out from under it.
85
156
  */
86
157
  stop(timeoutMs?: number): Promise<boolean>;
87
158
  /** True while the loop is running. */
@@ -100,6 +171,12 @@ export interface InboxLoopHandle {
100
171
  */
101
172
  readonly lastAttemptAt: number | null;
102
173
  }
174
+ /**
175
+ * Whether a pass changed anything. One that only found rows already running
176
+ * (or waiting for a slot) did not, and reading again at once would find them
177
+ * again: the server lists a row until its wake has handled it.
178
+ */
179
+ export declare function passMadeProgress(pass: Pick<InboxPassResult, 'dispatched' | 'messagesDelivered' | 'resourceEvents' | 'tasksDelivered' | 'requestsTriaged'>): boolean;
103
180
  /** Count held windows so retries can back off without discarding mail. */
104
181
  export declare function heldPassAfter(prev: number, pass: Pick<InboxPassResult, 'acked' | 'failures' | 'truncated'>): number;
105
182
  /** How long `stop()` waits for a pass in flight before releasing the lease anyway. */
@@ -111,6 +188,14 @@ export declare const INBOX_STOP_TIMEOUT_MS = 30000;
111
188
  * there is nothing to resynchronize (the watermark is server-side), so recovery
112
189
  * is just the next iteration.
113
190
  *
191
+ * Wakes do not hold the loop: a pass starts its wakes (up to the agent's
192
+ * bound) and the loop reads again, so a new thread is taken up while another
193
+ * is still being answered. The server keeps listing a row until it is handled,
194
+ * so while wakes run a read can come back at once with nothing new in it; then
195
+ * the loop waits for one of them to finish, or a few seconds, before reading
196
+ * again. A message from someone else is taken up within that recheck, not
197
+ * after the running wake.
198
+ *
114
199
  * The FIRST pass is an immediate read. A held poll only answers to new mail, so
115
200
  * a host that just started (or restarted after a crash) would otherwise sit
116
201
  * waiting while the work it was already assigned — open tasks, pending
@@ -118,4 +203,5 @@ export declare const INBOX_STOP_TIMEOUT_MS = 30000;
118
203
  */
119
204
  export declare function runInboxLoop(deps: InboxLoopDeps, opts?: {
120
205
  waitSeconds?: number;
206
+ busyRecheckMs?: number;
121
207
  }): InboxLoopHandle;
@@ -3,6 +3,105 @@ import { deliveryHandlingId, withWorkExecution } from '@ziggs-ai/api-client';
3
3
  import { MessageRecordsClient, InboxClient, planInboxAck, planPartialInboxAck, } from '@ziggs-ai/api-client';
4
4
  import { runtimeLog } from '../shared/runtimeLog.js';
5
5
  import { isRateLimited } from '@ziggs-ai/api-client';
6
+ /** How many assigned wakes one agent runs at once unless told otherwise. */
7
+ export const DEFAULT_INBOX_CONCURRENCY = 4;
8
+ /**
9
+ * The wake bound for one agent: `explicit`, else `ZIGGS_AGENT_INBOX_CONCURRENCY`,
10
+ * else {@link DEFAULT_INBOX_CONCURRENCY}. Never below one.
11
+ */
12
+ export function inboxConcurrency(explicit) {
13
+ const env = process.env.ZIGGS_AGENT_INBOX_CONCURRENCY;
14
+ const raw = explicit ?? (env ? Number(env) : NaN);
15
+ return Number.isFinite(raw) ? Math.max(1, Math.floor(raw)) : DEFAULT_INBOX_CONCURRENCY;
16
+ }
17
+ /**
18
+ * The wakes one inbox loop has handed over and not yet seen finish.
19
+ *
20
+ * Bounded: at most `limit` run at once. Keyed by what the server lists again
21
+ * while the work is pending (a receipt, a task), so a row that comes back on
22
+ * the next read while its wake still runs is never handed over twice. Ordered
23
+ * jobs hand over in the order they were dispatched: messages are dispatched
24
+ * oldest first, so the messages of one thread reach their lane in the order
25
+ * they were sent, and the lane runs them one at a time. Different threads run
26
+ * side by side.
27
+ */
28
+ export class InboxDispatch {
29
+ limit;
30
+ running = new Map();
31
+ lastTurn = Promise.resolve();
32
+ listeners = new Set();
33
+ failed = 0;
34
+ constructor(limit) {
35
+ this.limit = inboxConcurrency(limit);
36
+ }
37
+ /** Wakes running now. */
38
+ get size() {
39
+ return this.running.size;
40
+ }
41
+ get full() {
42
+ return this.running.size >= this.limit;
43
+ }
44
+ has(key) {
45
+ return this.running.has(key);
46
+ }
47
+ /**
48
+ * Run `job` under `key`. It resolves `true` when its work was handed over
49
+ * and finished, `false` when it was not handled. An ordered job waits for
50
+ * `turn.ready` before it hands over and calls `turn.done()` once it has.
51
+ */
52
+ start(key, job, ordered = false) {
53
+ let done;
54
+ const handedOver = new Promise((resolve) => { done = resolve; });
55
+ const turn = { ready: ordered ? this.lastTurn : Promise.resolve(), done };
56
+ if (ordered)
57
+ this.lastTurn = handedOver;
58
+ const run = (async () => {
59
+ try {
60
+ if (!(await job(turn)))
61
+ this.failed++;
62
+ }
63
+ catch (err) {
64
+ this.failed++;
65
+ runtimeLog.warn('inboxLoop', `${key} failed: ${err?.message ?? err}`);
66
+ }
67
+ finally {
68
+ done();
69
+ this.running.delete(key);
70
+ for (const listener of [...this.listeners])
71
+ listener();
72
+ }
73
+ })();
74
+ this.running.set(key, run);
75
+ return run;
76
+ }
77
+ /** Jobs that were not handled since the last call. The loop backs off on them. */
78
+ takeFailures() {
79
+ const failed = this.failed;
80
+ this.failed = 0;
81
+ return failed;
82
+ }
83
+ /** Resolves when any running job finishes, `ms` passes (if given), or `signal` aborts. */
84
+ settledOr(ms, signal) {
85
+ if (this.running.size === 0 || signal?.aborted)
86
+ return Promise.resolve();
87
+ return new Promise((resolve) => {
88
+ const finish = () => {
89
+ clearTimeout(timer);
90
+ this.listeners.delete(finish);
91
+ signal?.removeEventListener('abort', finish);
92
+ resolve();
93
+ };
94
+ const timer = ms === undefined ? undefined : setTimeout(finish, Math.max(0, ms));
95
+ this.listeners.add(finish);
96
+ signal?.addEventListener('abort', finish, { once: true });
97
+ });
98
+ }
99
+ /** Resolves when nothing is running. */
100
+ async idle() {
101
+ while (this.running.size)
102
+ await Promise.allSettled([...this.running.values()]);
103
+ }
104
+ }
6
105
  function log(label, msg) {
7
106
  runtimeLog.info(label, msg);
8
107
  }
@@ -41,28 +140,33 @@ function proposalIsMine(proposal, ownAgentId) {
41
140
  }
42
141
  /** Read the exact request this agent was assigned and hand it to the host.
43
142
  * Historical lookup is optional context, never handoff. A request's wake is
44
- * its receipt: one receipt, one wake. */
45
- async function deliverAssignedMessage(deps, ref, reader, attempt, handledIds) {
143
+ * its receipt: one receipt, one wake. The message's thread rides along as
144
+ * `threadRootId`, so the host can keep the thread on one lane. */
145
+ async function deliverAssignedMessage(deps, ref, reader, attempt, handledIds, turn) {
46
146
  const receiptId = deliveryHandlingId(ref);
47
- if (deps.seen.has(receiptId)) {
48
- handledIds.add(receiptId);
49
- return false;
50
- }
51
147
  const handled = await attempt(`message ${ref.resourceId}`, () => (async () => {
52
148
  if (!ref.action)
53
149
  throw new Error('Assigned message has no domain action');
54
150
  const execution = await prepareWorkExecution(ref.action, deps.creds.operatorKey, deps.ownAgentId, deps.baseUrl);
55
151
  return withWorkExecution(execution, async () => {
56
152
  const row = await reader.get(ref.resourceId);
153
+ // A backend that does not name the thread yet leaves this message on its own lane.
154
+ const root = row.rootMessageId;
155
+ const threadRootId = typeof root === 'string' && root ? root : undefined;
57
156
  const metadata = { messageId: row.messageId, ...(row.mandate ?? {}),
58
157
  sender: { id: row.sender.ref, type: row.sender.kind }, receiver: { id: deps.ownAgentId, type: 'agent' },
59
- entryType: 'message', intent: row.intent, timestamp: row.timestamp, roomless: true };
60
- await deps.onMessage(row.content.text, {
158
+ entryType: 'message', intent: row.intent, timestamp: row.timestamp, roomless: true,
159
+ ...(threadRootId ? { threadRootId } : {}) };
160
+ // Hand over in dispatch order; only the read above runs ahead.
161
+ await turn.ready;
162
+ const handover = deps.onMessage(row.content.text, {
61
163
  ...metadata, assigneeId: deps.ownAgentId, receiptId,
62
164
  executionContext: execution,
63
165
  ...(ref.agreementId ? { agreementId: ref.agreementId } : {}),
64
166
  ...(ref.taskId ? { taskId: ref.taskId } : {}),
65
167
  });
168
+ turn.done();
169
+ await handover;
66
170
  });
67
171
  })());
68
172
  if (handled) {
@@ -76,6 +180,12 @@ async function deliverAssignedMessage(deps, ref, reader, attempt, handledIds) {
76
180
  * the deltas, deliver them into the host, and ack. Returns what it delivered.
77
181
  * Reused each iteration of {@link runInboxLoop}; also usable as a single catch-up
78
182
  * read (`waitSeconds: 0`) at bootstrap.
183
+ *
184
+ * Assigned messages and tasks run as wakes, up to the agent's bound at once.
185
+ * Without `opts.dispatch` the pass waits for every wake it started before it
186
+ * returns. With one (the loop's own), the pass returns as soon as its wakes
187
+ * are started: each wake acknowledges its own row when it finishes, and rows
188
+ * the dispatch is still running are skipped.
79
189
  */
80
190
  export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
81
191
  const label = deps.label ?? 'inboxLoop';
@@ -92,6 +202,31 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
92
202
  let tasksDelivered = 0;
93
203
  let requestsTriaged = 0;
94
204
  let failures = 0;
205
+ let dispatched = 0;
206
+ let alreadyRunning = 0;
207
+ let deferred = 0;
208
+ // A pass with its own dispatch waits for its wakes; the loop's does not.
209
+ const detached = opts.dispatch !== undefined;
210
+ const dispatch = opts.dispatch ?? new InboxDispatch(deps.concurrency);
211
+ /** Wakes this pass started that have not finished. */
212
+ let runningHere = 0;
213
+ /** Whether another wake may start now. A detached pass leaves the row for later. */
214
+ const roomForWake = async () => {
215
+ if (!dispatch.full)
216
+ return true;
217
+ if (detached) {
218
+ deferred++;
219
+ return false;
220
+ }
221
+ while (dispatch.full)
222
+ await dispatch.settledOr();
223
+ return true;
224
+ };
225
+ const startWake = (key, job, ordered = false) => {
226
+ dispatched++;
227
+ runningHere++;
228
+ void dispatch.start(key, job, ordered).finally(() => { runningHere--; });
229
+ };
95
230
  // a handover that failed must not be acked, and must not be
96
231
  // remembered as seen — otherwise the redelivery the held watermark buys is
97
232
  // dropped as a duplicate. One failure does not abandon the rest of the
@@ -134,20 +269,15 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
134
269
  warn(label, `${unreceipted.length} assigned deliver${unreceipted.length === 1 ? 'y has' : 'ies have'} no receiptId; skipped (${unreceipted.map(d => `${d.kind} ${d.resourceId}`).join(', ')})`);
135
270
  }
136
271
  const mine = (d) => d.assigneeId === deps.ownAgentId && Boolean(d.receiptId);
137
- // Give the mark back in steps instead of once at the end of the pass.
138
- //
139
- // A pass that acks only when it finishes freezes the watermark for its whole
140
- // length, and the server hands an unanswered row to the person's stand-in
141
- // after 90s. Measured, a single turn is ~19s but an uninterrupted stretch is
142
- // ~86s median, so the pass — not the turn — is what crosses the window. Each
143
- // row now carries a token for its own position; `planPartialInboxAck` says
144
- // how far those tokens can safely be taken given what is finished.
272
+ // Give the mark back as each wake finishes instead of once at the end.
145
273
  //
146
- // A mark is global, so it can only be released in timestamp order, while
147
- // chats are worked newest-first. One chat in the pass — the ordinary case,
148
- // and the one the window actually bites — releases as soon as it is done.
149
- // Several, and the oldest is worked last, so the release waits for it: no
150
- // worse than acking at the end, which is what this replaced.
274
+ // A pass that acks only when it finishes holds every finished row behind its
275
+ // slowest wake, while the server and the person's stand-in read an
276
+ // unacknowledged row as unanswered. Measured, a single turn is ~19s but an
277
+ // uninterrupted stretch is ~86s median, so the pass, not the turn, is what
278
+ // crosses a 90 s window. A row is settled by its own receipt id, in any
279
+ // order (`planPartialInboxAck`), so each wake acknowledges its row the moment
280
+ // it finishes, whatever else is still running beside it.
151
281
  // Blocked work is the server's to retry, not a handover that failed here:
152
282
  // it stays pending without ringing, so holding the mark or backing off for
153
283
  // it would only delay the work that can run.
@@ -194,12 +324,15 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
194
324
  step.handledDeliveryIds = step.handledDeliveryIds.filter(id => !acknowledged.has(id));
195
325
  if (!step.handledDeliveryIds.length)
196
326
  return;
327
+ // Claimed before the call: wakes finish side by side, and each sends only
328
+ // the rows nobody is acknowledging yet.
329
+ step.handledDeliveryIds.forEach(id => acknowledged.add(id));
197
330
  try {
198
331
  noteRefused(await inbox.ack(step.ackTo, { handledDeliveryIds: step.handledDeliveryIds }));
199
- step.handledDeliveryIds.forEach(id => acknowledged.add(id));
200
332
  log(label, `acked up to ${step.ackTo} (mid-pass)`);
201
333
  }
202
334
  catch (err) {
335
+ step.handledDeliveryIds.forEach(id => acknowledged.delete(id));
203
336
  // Never fatal: the end-of-pass ack is still coming, and the watermark is
204
337
  // monotonic, so a lost step costs nothing but the exposure it would have
205
338
  // closed.
@@ -210,15 +343,46 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
210
343
  // agent and a message action. A message that is a task's input carries the
211
344
  // task action instead and reaches the task executor below. Every assigned
212
345
  // request is fetched by resource identity; navigation is optional.
346
+ //
347
+ // Oldest first: the messages of one thread must reach their lane in the
348
+ // order they were sent. Each runs as its own wake beside the others.
213
349
  const assigned = envelope.deliveries
214
350
  .filter(d => d.kind === 'message' && d.action?.kind === 'message' && d.actionState !== 'settled' && d.actionState !== 'waiting' && mine(d) && !d.outOfReach && !d.executionBlocked)
215
- .sort((a, b) => b.ts.localeCompare(a.ts));
351
+ .sort((a, b) => a.ts.localeCompare(b.ts));
216
352
  const records = new MessageRecordsClient(deps.creds.operatorKey, deps.creds.agentId, deps.baseUrl);
353
+ let heldBack = false;
217
354
  for (const delivery of assigned) {
218
- if (await deliverAssignedMessage(deps, delivery, records, attempt, handledSoFar))
219
- messagesDelivered++;
220
- await ackWhatIsFinished();
355
+ const receiptId = deliveryHandlingId(delivery);
356
+ // Before the seen check: the host marks a message seen when its wake
357
+ // starts, and a running wake is not a handled one.
358
+ if (dispatch.has(receiptId)) {
359
+ alreadyRunning++;
360
+ continue;
361
+ }
362
+ if (deps.seen.has(receiptId)) {
363
+ handledSoFar.add(receiptId);
364
+ continue;
365
+ }
366
+ // Once one message is left for later, so is every newer one: a slot that
367
+ // frees meanwhile must not let a later message of its thread overtake it.
368
+ if (heldBack) {
369
+ deferred++;
370
+ continue;
371
+ }
372
+ if (!(await roomForWake())) {
373
+ heldBack = true;
374
+ continue;
375
+ }
376
+ startWake(receiptId, async (turn) => {
377
+ const handled = await deliverAssignedMessage(deps, delivery, records, attempt, handledSoFar, turn);
378
+ if (handled)
379
+ messagesDelivered++;
380
+ await ackWhatIsFinished();
381
+ return handled;
382
+ }, true);
221
383
  }
384
+ if (!detached)
385
+ await dispatch.idle();
222
386
  // Everything that is not chat text is handed over as a resource event, from
223
387
  // the delivery itself — the reference already carries the ids the host needs,
224
388
  // so nothing has to be re-derived to name what changed.
@@ -299,6 +463,13 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
299
463
  for (const { task, receipts } of taskActions.values()) {
300
464
  if (task.executionBlocked)
301
465
  continue;
466
+ // One wake per task at a time. While it runs, the task and its receipts
467
+ // stay listed; they are taken up again once it has finished.
468
+ const runKey = `task:${task.taskId}`;
469
+ if (dispatch.has(runKey)) {
470
+ alreadyRunning++;
471
+ continue;
472
+ }
302
473
  const key = `task:${task.taskId}:${task.updatedAt ?? ''}:${task.executionContext?.contextId ?? ''}`;
303
474
  const receiptKeys = receipts.map(receipt => `task-receipt:${deliveryHandlingId(receipt)}`);
304
475
  // A timestamp is not a causal sequence: a new input can share its owner's
@@ -309,18 +480,25 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
309
480
  }
310
481
  if (!deps.onTask)
311
482
  continue; // Unsupported work stays pending; delivery is not completion.
312
- const handled = await attempt(`task ${task.taskId}`, async () => {
313
- const executionContext = await prepareWorkExecution({ kind: 'task', id: task.taskId }, deps.creds.operatorKey, deps.ownAgentId, deps.baseUrl);
314
- return withWorkExecution(executionContext, () => deps.onTask({ ...task, executionContext }, receipts.map(receipt => ({ kind: receipt.kind, id: receipt.resourceId, eventId: receipt.eventId ?? receipt.receiptId }))));
483
+ if (!(await roomForWake()))
484
+ continue;
485
+ startWake(runKey, async () => {
486
+ const handled = await attempt(`task ${task.taskId}`, async () => {
487
+ const executionContext = await prepareWorkExecution({ kind: 'task', id: task.taskId }, deps.creds.operatorKey, deps.ownAgentId, deps.baseUrl);
488
+ return withWorkExecution(executionContext, () => deps.onTask({ ...task, executionContext }, receipts.map(receipt => ({ kind: receipt.kind, id: receipt.resourceId, eventId: receipt.eventId ?? receipt.receiptId }))));
489
+ });
490
+ if (handled) {
491
+ deps.seen.mark(key);
492
+ receiptKeys.forEach(id => deps.seen.mark(id));
493
+ tasksDelivered++;
494
+ receipts.forEach(receipt => handledSoFar.add(deliveryHandlingId(receipt)));
495
+ }
496
+ await ackWhatIsFinished();
497
+ return handled;
315
498
  });
316
- if (handled) {
317
- deps.seen.mark(key);
318
- receiptKeys.forEach(id => deps.seen.mark(id));
319
- tasksDelivered++;
320
- receipts.forEach(receipt => handledSoFar.add(deliveryHandlingId(receipt)));
321
- }
322
- await ackWhatIsFinished();
323
499
  }
500
+ if (!detached)
501
+ await dispatch.idle();
324
502
  await ackWhatIsFinished();
325
503
  if (envelope.truncatedTasks) {
326
504
  warn(label, `inbox truncatedTasks=${envelope.truncatedTasks} (more assigned tasks than one pass surfaces — they appear as earlier ones close)`);
@@ -397,6 +575,11 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
397
575
  acked = true;
398
576
  log(label, `acked up to ${envelope.ackTo}`);
399
577
  }
578
+ else if (envelope.ackTo && !failures && (runningHere || alreadyRunning || deferred)) {
579
+ // Nothing failed: those rows are still running, or wait for a slot. Each
580
+ // running wake acknowledges its own row when it finishes.
581
+ log(label, `${runningHere + alreadyRunning} assigned wake(s) still running, ${deferred} waiting for a slot; each is acknowledged when it finishes`);
582
+ }
400
583
  else if (envelope.ackTo) {
401
584
  warn(label, `holding the watermark at ${envelope.ackTo} — ${failures} handover(s) failed this pass, so the ` +
402
585
  'window will be redelivered');
@@ -411,6 +594,9 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
411
594
  truncated: envelope.deliveriesCapped,
412
595
  failures,
413
596
  blocked,
597
+ dispatched,
598
+ alreadyRunning,
599
+ deferred,
414
600
  };
415
601
  }
416
602
  /**
@@ -419,8 +605,19 @@ export async function pollInboxOnce(deps, waitSeconds = 0, opts = {}) {
419
605
  * some defaults ship with. Lower it if your deployment sits behind a shorter one.
420
606
  */
421
607
  const DEFAULT_WAIT_SECONDS = 110;
608
+ /** While wakes run, how soon to read again for a new thread. The server keeps
609
+ * listing the running rows, so a held read cannot wait for new mail then. */
610
+ const BUSY_RECHECK_MS = 3_000;
422
611
  const ERROR_BACKOFF_BASE_MS = 1_000;
423
612
  const ERROR_BACKOFF_MAX_MS = 30_000;
613
+ /**
614
+ * Whether a pass changed anything. One that only found rows already running
615
+ * (or waiting for a slot) did not, and reading again at once would find them
616
+ * again: the server lists a row until its wake has handled it.
617
+ */
618
+ export function passMadeProgress(pass) {
619
+ return pass.dispatched + pass.messagesDelivered + pass.resourceEvents + pass.tasksDelivered + pass.requestsTriaged > 0;
620
+ }
424
621
  /** Count held windows so retries can back off without discarding mail. */
425
622
  export function heldPassAfter(prev, pass) {
426
623
  return pass.failures > 0 || (!pass.acked && pass.truncated) ? prev + 1 : 0;
@@ -458,6 +655,14 @@ function withinMs(promise, ms) {
458
655
  * there is nothing to resynchronize (the watermark is server-side), so recovery
459
656
  * is just the next iteration.
460
657
  *
658
+ * Wakes do not hold the loop: a pass starts its wakes (up to the agent's
659
+ * bound) and the loop reads again, so a new thread is taken up while another
660
+ * is still being answered. The server keeps listing a row until it is handled,
661
+ * so while wakes run a read can come back at once with nothing new in it; then
662
+ * the loop waits for one of them to finish, or a few seconds, before reading
663
+ * again. A message from someone else is taken up within that recheck, not
664
+ * after the running wake.
665
+ *
461
666
  * The FIRST pass is an immediate read. A held poll only answers to new mail, so
462
667
  * a host that just started (or restarted after a crash) would otherwise sit
463
668
  * waiting while the work it was already assigned — open tasks, pending
@@ -466,6 +671,8 @@ function withinMs(promise, ms) {
466
671
  export function runInboxLoop(deps, opts = {}) {
467
672
  const label = deps.label ?? 'inboxLoop';
468
673
  const waitSeconds = opts.waitSeconds ?? DEFAULT_WAIT_SECONDS;
674
+ const busyRecheckMs = Math.min(opts.busyRecheckMs ?? BUSY_RECHECK_MS, waitSeconds * 1000);
675
+ const dispatch = new InboxDispatch(deps.concurrency);
469
676
  let running = true;
470
677
  let consecutiveErrors = 0;
471
678
  let heldPasses = 0;
@@ -481,13 +688,16 @@ export function runInboxLoop(deps, opts = {}) {
481
688
  while (running) {
482
689
  try {
483
690
  lastAttemptAt = Date.now();
484
- const pass = await pollInboxOnce(deps, first ? 0 : waitSeconds, { signal: shutdown.signal });
691
+ const pass = await pollInboxOnce(deps, first ? 0 : waitSeconds, { signal: shutdown.signal, dispatch });
485
692
  lastPassAt = Date.now();
486
693
  first = false;
487
694
  consecutiveErrors = 0;
488
- heldPasses = heldPassAfter(heldPasses, pass);
695
+ // A wake that failed after its pass returned still backs the loop off.
696
+ heldPasses = heldPassAfter(heldPasses, { ...pass, failures: pass.failures + dispatch.takeFailures() });
489
697
  if (heldPasses)
490
698
  await sleep(Math.min(ERROR_BACKOFF_MAX_MS, ERROR_BACKOFF_BASE_MS * 2 ** Math.min(heldPasses - 1, 5)), shutdown.signal);
699
+ else if (dispatch.size > 0 && !passMadeProgress(pass))
700
+ await dispatch.settledOr(busyRecheckMs, shutdown.signal);
491
701
  }
492
702
  catch (err) {
493
703
  if (!running)
@@ -512,7 +722,9 @@ export function runInboxLoop(deps, opts = {}) {
512
722
  }
513
723
  }
514
724
  })();
515
- const done = main.finally(releaseOnce);
725
+ // The lease is released once the loop has stopped and every wake it started
726
+ // has finished and acknowledged (or `stop` ran out of patience).
727
+ const done = main.then(() => dispatch.idle()).finally(releaseOnce);
516
728
  return {
517
729
  get running() {
518
730
  return running;
@@ -1,11 +1,45 @@
1
+ import { type WorkExecutionContext } from '@ziggs-ai/api-client';
2
+ /** The parts of an execution a lane is named from. */
3
+ export type LaneExecution = Pick<WorkExecutionContext, 'contextId' | 'agreementId'> & Partial<Pick<WorkExecutionContext, 'action' | 'taskId' | 'audienceIds'>>;
4
+ /** What one wake's lane is computed from. */
5
+ export interface LaneWake {
6
+ /** The execution the wake runs under. Left out, the current one is used. */
7
+ execution?: LaneExecution;
8
+ /** The first message of the thread a message wake belongs to. */
9
+ threadRootId?: string;
10
+ }
11
+ /**
12
+ * The thread lane of a message wake: `thr-<digest>`, or undefined when this
13
+ * wake does not run on one.
14
+ *
15
+ * Only a wake whose action is a message, and whose thread is known, gets one.
16
+ * The digest covers the thread, the work and every reader, so a later message
17
+ * in the same thread, under the same work, read by the same people, lands on
18
+ * the same lane and the agent carries over what it knew. Anything else that
19
+ * changes (a reader joins or leaves, another agreement or task) gives a new
20
+ * lane: an agent may carry over only what everyone reading can read.
21
+ */
22
+ export declare function threadLaneId(execution: LaneExecution | undefined, threadRootId: string | undefined): string | undefined;
23
+ /** Run `work` as the wake of `laneKey`, so a lane named inside it names this one. */
24
+ export declare function runInLane<T>(agentId: string, laneKey: string, work: () => T): T;
25
+ /** The lane of the wake running now, if any. */
26
+ export declare function currentLaneKey(): string | undefined;
1
27
  /**
2
28
  * The lane key for one agent's one conversation.
3
29
  *
4
30
  * Stated once because three places used to spell it inline, and the wake
5
31
  * scheduler added a fourth: it has to name the lane it is arming a timer for,
6
32
  * and it only holds the agent id and the session id. A second copy of the
7
- * formula would be a bug the day the shape changes — a timer armed on
33
+ * formula would be a bug the day the shape changes: a timer armed on
8
34
  * `a:b` while the queue dispatches `a::b` simply never wakes anything, with
9
35
  * nothing in the logs to say so.
36
+ *
37
+ * - A message wake whose thread is known runs on its thread lane (see
38
+ * {@link threadLaneId}).
39
+ * - Any other wake under an execution runs on that execution's own lane.
40
+ * - A wake under none runs on its session.
41
+ *
42
+ * Called without `wake` inside a running wake, it names that wake's lane, which
43
+ * is how a timer armed from a tool finds the lane it was armed from.
10
44
  */
11
- export declare function laneKeyFor(agentId: string, sessionId: string, executionContextId?: string): string;
45
+ export declare function laneKeyFor(agentId: string, sessionId: string, wake?: LaneWake): string;
@@ -1,14 +1,62 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
3
  import { currentWorkExecution } from '@ziggs-ai/api-client';
4
+ /**
5
+ * The thread lane of a message wake: `thr-<digest>`, or undefined when this
6
+ * wake does not run on one.
7
+ *
8
+ * Only a wake whose action is a message, and whose thread is known, gets one.
9
+ * The digest covers the thread, the work and every reader, so a later message
10
+ * in the same thread, under the same work, read by the same people, lands on
11
+ * the same lane and the agent carries over what it knew. Anything else that
12
+ * changes (a reader joins or leaves, another agreement or task) gives a new
13
+ * lane: an agent may carry over only what everyone reading can read.
14
+ */
15
+ export function threadLaneId(execution, threadRootId) {
16
+ if (!threadRootId || execution?.action?.kind !== 'message')
17
+ return undefined;
18
+ const readers = [...new Set(execution.audienceIds ?? [])].sort();
19
+ const digest = createHash('sha256')
20
+ .update(JSON.stringify([threadRootId, execution.agreementId ?? null, execution.taskId ?? null, readers]))
21
+ .digest('hex')
22
+ .slice(0, 32);
23
+ return `thr-${digest}`;
24
+ }
25
+ /** The lane a wake is running on right now, for calls that hold only a session id. */
26
+ const runningLane = new AsyncLocalStorage();
27
+ /** Run `work` as the wake of `laneKey`, so a lane named inside it names this one. */
28
+ export function runInLane(agentId, laneKey, work) {
29
+ return runningLane.run({ agentId, laneKey }, work);
30
+ }
31
+ /** The lane of the wake running now, if any. */
32
+ export function currentLaneKey() {
33
+ return runningLane.getStore()?.laneKey;
34
+ }
2
35
  /**
3
36
  * The lane key for one agent's one conversation.
4
37
  *
5
38
  * Stated once because three places used to spell it inline, and the wake
6
39
  * scheduler added a fourth: it has to name the lane it is arming a timer for,
7
40
  * and it only holds the agent id and the session id. A second copy of the
8
- * formula would be a bug the day the shape changes — a timer armed on
41
+ * formula would be a bug the day the shape changes: a timer armed on
9
42
  * `a:b` while the queue dispatches `a::b` simply never wakes anything, with
10
43
  * nothing in the logs to say so.
44
+ *
45
+ * - A message wake whose thread is known runs on its thread lane (see
46
+ * {@link threadLaneId}).
47
+ * - Any other wake under an execution runs on that execution's own lane.
48
+ * - A wake under none runs on its session.
49
+ *
50
+ * Called without `wake` inside a running wake, it names that wake's lane, which
51
+ * is how a timer armed from a tool finds the lane it was armed from.
11
52
  */
12
- export function laneKeyFor(agentId, sessionId, executionContextId) {
13
- return `${agentId}:${executionContextId ?? currentWorkExecution()?.contextId ?? sessionId}`;
53
+ export function laneKeyFor(agentId, sessionId, wake) {
54
+ if (!wake) {
55
+ const running = runningLane.getStore();
56
+ if (running?.agentId === agentId)
57
+ return running.laneKey;
58
+ }
59
+ const execution = wake?.execution ?? currentWorkExecution();
60
+ const thread = threadLaneId(execution, wake?.threadRootId);
61
+ return `${agentId}:${thread ?? execution?.contextId ?? sessionId}`;
14
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ziggs-ai/agent-sdk",
3
- "version": "0.44.1",
3
+ "version": "0.45.0",
4
4
  "description": "Agent framework SDK for building autonomous agents on the Ziggs platform",
5
5
  "homepage": "https://ziggsai.com/docs",
6
6
  "bugs": {