@agentchatme/agent-core 0.0.13131111111131 → 0.2.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.
@@ -1,241 +1,393 @@
1
+ import { R as RunRunner, I as IntegrationClient, a as RunProfile, S as SocketState, T as TextsStore, b as IntegrationStatus, c as RunPrompts, d as TimerHandle, e as IntegrationLastRun, f as RunOutcome } from './prompts-B0UL03Hu.js';
2
+ export { D as DEFAULT_WAKE_DEBOUNCE_MS, g as RunKind, h as RunOutcomeState, i as RunPreflight, j as RunRequest, W as WakeCoalescer, k as WakeCoalescerOptions } from './prompts-B0UL03Hu.js';
3
+ import { BlockedInfo, RealtimeState, AgentChatClient } from 'agentchatme';
1
4
  import { EventEmitter } from 'node:events';
2
- import { z } from 'zod';
3
- import { T as TurnContext, a as TurnDisposition, R as RuntimeAdapter } from './adapter-types-DrrsKZYk.js';
4
- export { A as AutonomyMode, F as FullAutonomyTurnContext, P as PendingReason, b as PendingTurnRequest, S as SilentReason, c as TurnBatchContext, d as TurnMentionContext, e as TurnResult } from './adapter-types-DrrsKZYk.js';
5
5
 
6
- declare const SyncRowSchema: z.ZodObject<{
7
- id: z.ZodString;
8
- conversation_id: z.ZodString;
9
- delivery_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
- sender: z.ZodOptional<z.ZodString>;
11
- sender_handle: z.ZodOptional<z.ZodString>;
12
- seq: z.ZodOptional<z.ZodNumber>;
13
- type: z.ZodOptional<z.ZodString>;
14
- content: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
15
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
16
- status: z.ZodOptional<z.ZodString>;
17
- created_at: z.ZodOptional<z.ZodString>;
18
- }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
19
- id: z.ZodString;
20
- conversation_id: z.ZodString;
21
- delivery_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
22
- sender: z.ZodOptional<z.ZodString>;
23
- sender_handle: z.ZodOptional<z.ZodString>;
24
- seq: z.ZodOptional<z.ZodNumber>;
25
- type: z.ZodOptional<z.ZodString>;
26
- content: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
27
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
28
- status: z.ZodOptional<z.ZodString>;
29
- created_at: z.ZodOptional<z.ZodString>;
30
- }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
31
- id: z.ZodString;
32
- conversation_id: z.ZodString;
33
- delivery_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
34
- sender: z.ZodOptional<z.ZodString>;
35
- sender_handle: z.ZodOptional<z.ZodString>;
36
- seq: z.ZodOptional<z.ZodNumber>;
37
- type: z.ZodOptional<z.ZodString>;
38
- content: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
39
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
40
- status: z.ZodOptional<z.ZodString>;
41
- created_at: z.ZodOptional<z.ZodString>;
42
- }, z.ZodTypeAny, "passthrough">>;
43
- type SyncRow = z.infer<typeof SyncRowSchema>;
44
- declare function parseInbound(payload: unknown): SyncRow | null;
45
- declare function senderOf(row: SyncRow): string;
46
-
47
- type State = 'connecting' | 'ready' | 'reconnecting' | 'terminal' | 'closed';
48
- interface WsClientEvents {
49
- inbound: (row: SyncRow) => void;
50
- ready: () => void;
51
- terminal: (reason: string) => void;
52
- }
53
- declare class AgentWsClient extends EventEmitter {
54
- private readonly url;
55
- private readonly apiKey;
56
- private ws;
57
- private state;
58
- private attempt;
59
- private reconnectTimer;
60
- private livenessTimer;
61
- private ackRetryTimer;
62
- private stopped;
63
- private ackMode;
64
- private inboundPaused;
65
- private readonly pendingAcks;
66
- private readonly acksInFlight;
67
- constructor(url: string, apiKey: string);
68
- /** True only while the socket is live and ready. The heartbeat writer keys
69
- * off this, so a reconnecting/terminal daemon lets its heartbeat go stale
70
- * and the next session detects that always-on is actually down. */
71
- get connected(): boolean;
72
- start(): void;
73
- stop(): void;
74
- /**
75
- * Apply TCP backpressure while the model-turn queue is saturated. `ws`
76
- * delegates this to the underlying socket; no delivered frame is discarded.
77
- * A server heartbeat may close a very long pause, which is safe because all
78
- * unacked messages re-drain after reconnect.
79
- */
80
- pauseInbound(): void;
81
- resumeInbound(): void;
82
- getState(): State;
83
- /**
84
- * Confirm a message as handled: `{"type":"ack","message_id":"msg_..."}`.
85
- * Fire-and-forget by design — a dropped ack is loss-free (the delivery
86
- * stays 'stored' and re-drains on the next reconnect, where dedup absorbs
87
- * the replay). Acking by message id (not delivery id) is what lets a
88
- * real-time push — which carries no delivery_id — be acked at all.
89
- */
90
- ack(messageId: string): void;
91
- private flushAcks;
92
- private scheduleAckRetry;
93
- private open;
94
- private scheduleReconnect;
95
- private armLiveness;
96
- private clearTimers;
97
- }
98
-
99
- interface CoordConfig {
100
- apiKey: string;
101
- apiBase: string;
102
- /** Stable, replier-unique token, e.g. "daemon:<host>". Same token across a
103
- * restart on the same host so the daemon re-claims its own in-flight work. */
104
- holder: string;
105
- timeoutMs?: number;
106
- }
107
- interface ClaimOutcome {
108
- claimed: boolean;
109
- deferred: boolean;
110
- }
111
- interface ClaimBatchOutcome {
112
- claimedCount: number;
113
- deferred: boolean;
114
- }
115
- declare class ReplyCoord {
116
- private readonly cfg;
117
- constructor(cfg: CoordConfig);
118
- private req;
119
- /** Is the agent's live coding session actively working? Fail-open → FALSE. */
120
- isSessionActive(): Promise<boolean>;
121
- /**
122
- * Claim the sole right to reply to a message, atomically respecting any
123
- * foreground turn. Fail-open → claimed (reply anyway rather than drop).
124
- */
125
- claim(messageId: string): Promise<ClaimOutcome>;
126
- /**
127
- * Claim the contiguous oldest-first prefix of one conversation batch.
128
- * Falls back to ordered single-message claims against an older API server;
129
- * all other coordination failures remain fail-open.
130
- */
131
- claimBatch(messageIds: string[]): Promise<ClaimBatchOutcome>;
132
- }
133
-
134
- /** "the group \"Ops\" (grp_x)", or a bare "the group conversation grp_x" when
135
- * the server supplied no name, or "the direct conversation conv_x". */
136
- declare function describeConversation(ctx: TurnContext): string;
137
- /** Resolved sender identity: "Display Name (@handle)" or "@handle", flagging a
138
- * system agent so the model weights its words as platform-authored. */
139
- declare function describeSender(ctx: TurnContext): string;
140
- /** One canonical unattended-delivery prompt for every coding-agent host.
141
- * Host adapters only decide how to launch/resume their runtime; AgentChat's
142
- * message framing and agent-facing context contract must not drift. */
143
- declare function buildAgentChatTurnPrompt(ctx: TurnContext): string;
144
-
145
- /** Parse only an exact, standalone assistant-output marker. Adapters pass
146
- * assistant text here, never tool results or peer-authored delivery data. */
147
- declare function parseAgentChatTurnOutcome(text: string): TurnDisposition | null;
148
- /** Wire-observed sends are authoritative. A model cannot claim it replied
149
- * when no send completed, and a missing marker remains a valid silence. */
150
- declare function resolveTurnDisposition(sent: boolean, reported: TurnDisposition | null): TurnDisposition;
151
-
152
- interface RunDaemonOpts {
6
+ interface RunIntegrationOpts {
153
7
  /** THE identity home for the agent this daemon serves. */
154
8
  home: string;
155
- /** How to spawn one headless turn of this integration's coding agent. */
156
- adapter: RuntimeAdapter;
157
- /** Scratch dir override; defaults to `<home>/daemon-workdir`. */
158
- workdir?: string;
9
+ /** How to start one headless run of this integration's coding agent. */
10
+ runner: RunRunner;
11
+ /** How this integration names itself to the server: the texts runtime and its own version. */
12
+ client: IntegrationClient;
13
+ /** The one pointer line a run prompt ends with: how THIS runtime reaches its copy of the manual (`manualPointer(...)`). */
14
+ manualPointer: string;
15
+ /** Scratch dir for runs. The integration decides where; this package never derives one. */
16
+ workdir: string;
17
+ /** Defaults to `AGENTCHAT_RUN_PROFILE`, then `answer`. */
18
+ profile?: RunProfile;
19
+ /** Defaults to `AGENTCHAT_RUN_BUDGET_MS`, then 10 minutes. */
20
+ budgetMs?: number;
21
+ /** Ends the loop (tests). Production runs until SIGTERM/SIGINT. */
22
+ signal?: AbortSignal;
23
+ env?: NodeJS.ProcessEnv;
24
+ /** Test seam: what a signal-initiated shutdown calls last. Defaults to `process.exit`. */
25
+ exit?: (code: number) => void;
159
26
  }
160
27
  /**
161
- * Run the always-on daemon. Returns only on a condition that makes running
162
- * pointless — namely another daemon already holding this home's lock.
28
+ * Run the integration daemon. Returns only on a condition that makes running
29
+ * pointless — another daemon already holding this home's lock — or when
30
+ * `signal` aborts (tests).
163
31
  */
164
- declare function runDaemon(opts: RunDaemonOpts): Promise<number>;
32
+ declare function runIntegration(opts: RunIntegrationOpts): Promise<number>;
165
33
 
166
34
  interface DaemonConfig {
167
35
  apiKey: string;
168
36
  handle: string;
169
37
  apiBase: string;
170
- wsUrl: string;
38
+ /** `wss://api.agentchat.me` — the SDK's socket base; it appends `/v1/ws`. */
39
+ wsBase: string;
171
40
  /** The identity home. Credentials, leader lock, and heartbeat all live here. */
172
41
  home: string;
173
- /** Scratch dir for the adapter (spawned-turn cwd, generated MCP config). */
42
+ /** Scratch dir for runs (the headless run's cwd). */
174
43
  workdir: string;
175
44
  }
176
- /** `https://api.agentchat.me` → `wss://api.agentchat.me/v1/ws`. */
45
+ /** `https://api.agentchat.me` → `wss://api.agentchat.me`. */
46
+ declare function wsBaseFor(apiBase: string): string;
47
+ /** `https://api.agentchat.me` → `wss://api.agentchat.me/v1/ws`, for logs and checks. */
177
48
  declare function wsUrlFor(apiBase: string): string;
178
49
  interface ResolveDaemonOpts {
179
50
  /** THE identity home. Required — this module never derives one. */
180
51
  home: string;
181
- workdir?: string;
52
+ /** The run workdir. Required — this module never derives one either. */
53
+ workdir: string;
54
+ /** How to identify to the server when the handle has to be asked for. */
55
+ client: IntegrationClient;
182
56
  }
183
57
  /**
184
58
  * Resolve the identity the daemon runs as.
185
59
  *
186
60
  * Async because the handle is load-bearing at runtime — it filters this agent's
187
- * own outbound echoed back by server fan-out, and decides whether a group
188
- * mention names it. An env-only identity (`AGENTCHAT_API_KEY`, no credentials
189
- * file) has no handle on disk, so we ask the server rather than starting up
190
- * blind and replying to ourselves.
61
+ * own outbound echoed back by server fan-out. An env-only identity
62
+ * (`AGENTCHAT_API_KEY`, no credentials file) has no handle on disk, so we ask
63
+ * the server rather than starting up blind and waking on ourselves.
191
64
  */
192
65
  declare function resolveDaemonConfig(opts: ResolveDaemonOpts): Promise<DaemonConfig>;
193
66
 
194
- interface DaemonFailure {
195
- kind: 'socket-auth' | 'runtime';
196
- reason: string;
197
- }
198
- declare class Daemon {
199
- private readonly cfg;
200
- private readonly adapter;
201
- /** Called when the socket gives up for good (auth refused). The supervisor
202
- * above decides what happens next — this class does not end the process. */
203
- private readonly onTerminal?;
204
- private readonly ws;
205
- private readonly coord;
206
- private readonly seen;
207
- private readonly convQueues;
208
- private readonly convWorkers;
209
- private pending;
210
- private inFlight;
211
- private readonly waiters;
212
- private foregroundClaimsBlockedUntil;
213
- private foregroundDeferralRounds;
214
- private readonly foregroundDeferrals;
215
- private stopping;
67
+ interface MessageWake {
68
+ readonly source: 'message';
69
+ readonly sender: string | null;
70
+ readonly conversationId: string | null;
71
+ readonly messageId: string | null;
72
+ }
73
+ /** A `wake` frame: a deferred conversation's reminder came due. */
74
+ interface ReminderWake {
75
+ readonly source: 'reminder';
76
+ readonly conversationId: string;
77
+ readonly anchorMessageId: string;
78
+ readonly step: number;
79
+ }
80
+ type Wake = MessageWake | ReminderWake;
81
+ interface InviteWake {
82
+ readonly inviteId: string;
83
+ readonly groupId: string | null;
84
+ readonly groupName: string | null;
85
+ readonly inviterHandle: string | null;
86
+ }
87
+ interface IntegrationConnectionEvents {
88
+ wake: (wake: Wake) => void;
89
+ invite: (invite: InviteWake) => void;
90
+ /** This agent's own outbound, echoed back by server fan-out. Not a wake. */
91
+ echo: () => void;
92
+ state: (state: SocketState, previous: SocketState) => void;
93
+ /** `hello.ok` arrived: the connection is live. Once per (re)connection, after `state` → `ready`. */
94
+ ready: () => void;
95
+ /**
96
+ * The server refused the credential on the hello (the SDK is `blocked`,
97
+ * and so is `state`). Once per rejected attempt — the first one in a
98
+ * run and every 10–15 minutes after it, until a hello is accepted and
99
+ * `state` → `ready` lifts it. `detail` is the line `status` shows as the
100
+ * last error.
101
+ */
102
+ blocked: (detail: string, info: BlockedInfo) => void;
103
+ }
104
+ interface IntegrationConnectionOptions {
105
+ readonly apiKey: string;
106
+ /** `wss://api.agentchat.me` — the SDK appends `/v1/ws`. */
107
+ readonly wsBase: string;
108
+ /** This agent's handle, to recognise its own echo. Bare, any case. */
109
+ readonly selfHandle: string;
110
+ readonly client: IntegrationClient;
111
+ /** Test seams for the SDK's backoff; its defaults (500 ms → 30 s) otherwise. */
112
+ readonly reconnectIntervalMs?: number;
113
+ readonly maxReconnectIntervalMs?: number;
114
+ }
115
+ /**
116
+ * The SDK's connection state in the status file's vocabulary. Pure. `previous`
117
+ * is the status word in effect, which decides two things the SDK's state alone
118
+ * does not say: a `connecting` after a close is `reconnecting`, and the slow
119
+ * retry out of `blocked` (`connecting` again) stays `blocked` — only an
120
+ * accepted hello (`ready`) lifts it. `stopped` is `closed` from any state; a
121
+ * refusal stays visible as the last error, not as the socket word.
122
+ */
123
+ declare function socketStateOf(next: RealtimeState, previous: SocketState): SocketState;
124
+ declare class IntegrationConnection extends EventEmitter {
125
+ private readonly options;
126
+ private rt;
127
+ private _state;
128
+ private stopped;
129
+ /** Rejected hellos since the last accepted one: the first is an error line, the rest are info. */
130
+ private refusals;
131
+ private readonly selfHandle;
132
+ constructor(options: IntegrationConnectionOptions);
133
+ get state(): SocketState;
134
+ /** True only while the socket is live — `hello.ok` received, not merely open. */
135
+ get connected(): boolean;
136
+ on<E extends keyof IntegrationConnectionEvents>(event: E, listener: IntegrationConnectionEvents[E]): this;
137
+ /** Open the SDK's client. Once: it lives until `stop()`, reconnecting on its own. */
138
+ start(): void;
139
+ /** End the SDK's client. Final: a stopped connection is not restarted. */
140
+ stop(): void;
141
+ private setState;
142
+ /** The SDK is `blocked`: the server refused the credential on the hello. Fires per rejected attempt. */
143
+ private onBlocked;
144
+ /**
145
+ * A `message.new` frame. Only the sender (echo filter) and the ids (log
146
+ * line) are read. `content`, `metadata`, previews — never touched. The SDK
147
+ * acked it before this ran.
148
+ */
149
+ private onMessageFrame;
150
+ /** A `wake` frame, validated by the SDK. No message, nothing to ack. */
151
+ private onWakeFrame;
152
+ private onInviteFrame;
153
+ }
154
+
155
+ interface IntegrationOptions {
156
+ readonly cfg: DaemonConfig;
157
+ readonly runner: RunRunner;
158
+ /** How this integration names itself to the server (texts runtime + its version). */
159
+ readonly client: IntegrationClient;
160
+ /** The one pointer line a run prompt ends with (`manualPointer(...)`). */
161
+ readonly manualPointer: string;
162
+ readonly profile: RunProfile;
163
+ readonly budgetMs: number;
164
+ /** Injectable for tests; defaults to a real connection on the SDK socket. */
165
+ readonly connection?: IntegrationConnection;
166
+ /** Injectable for tests; defaults to an SDK client for `cfg`. */
167
+ readonly api?: AgentChatClient;
168
+ /** Injectable for tests; defaults to a store on `api` and the identity home. */
169
+ readonly texts?: TextsStore;
170
+ }
171
+ declare class Integration {
172
+ private readonly options;
173
+ private readonly api;
174
+ private readonly connection;
175
+ private readonly texts;
176
+ private readonly invoker;
216
177
  private heartbeatTimer;
217
- constructor(cfg: DaemonConfig, adapter: RuntimeAdapter, ws?: AgentWsClient, // injectable for tests; defaults to a real socket
218
- /** Called when the socket gives up for good (auth refused). The supervisor
219
- * above decides what happens next — this class does not end the process. */
220
- onTerminal?: ((failure: DaemonFailure) => void) | undefined);
178
+ private statusTimer;
179
+ private lastError;
180
+ private stopping;
181
+ constructor(options: IntegrationOptions);
221
182
  start(): Promise<void>;
183
+ /**
184
+ * Stop holding the socket and interrupt a run in flight (its process group
185
+ * is SIGTERMed by the runner). Synchronous; `settled()` or `stopAndWait()`
186
+ * tell when the run has actually ended.
187
+ */
188
+ stop(): void;
189
+ /**
190
+ * `stop()`, then wait up to `graceMs` for the interrupted run to end. What a
191
+ * shutdown awaits before the process exits, so a launchd/systemd stop
192
+ * reaches the child and the restarted daemon does not find a run still
193
+ * going. Resolves true when nothing is running any more.
194
+ */
195
+ stopAndWait(graceMs: number): Promise<boolean>;
196
+ /** A run in flight finishes on its own; this resolves when it has. */
197
+ settled(): Promise<void>;
198
+ snapshot(): IntegrationStatus;
199
+ /** The served texts plus the pointer line, or null while no text is in hand. */
200
+ private runPrompts;
201
+ /**
202
+ * The connect-time catch-up: one wake (the invoker counts the tray before
203
+ * any run, so an empty tray costs a count, not a run) and the pending invites.
204
+ */
205
+ private catchUp;
206
+ private writeStatus;
207
+ }
208
+
209
+ declare const OFFERED_INVITES_FILE = "invites.offered.json";
210
+ /** The seam the invoker uses; `OfferedInvites` is the on-disk implementation. */
211
+ interface OfferedInviteStore {
212
+ has(inviteId: string): boolean;
213
+ add(inviteId: string): void;
214
+ /** Forget an offer: the run recorded at start turned out never to have got going. */
215
+ remove(inviteId: string): void;
216
+ }
217
+ declare function offeredInvitesPath(home: string): string;
218
+ declare class OfferedInvites implements OfferedInviteStore {
219
+ private readonly home;
220
+ private readonly now;
221
+ private readonly entries;
222
+ /** `home === null` keeps the set in memory only (tests). */
223
+ constructor(home: string | null, entries?: Array<{
224
+ id: string;
225
+ at: string;
226
+ }>, now?: () => Date);
227
+ /** Read the set from the identity home; a missing or malformed file is an empty set. */
228
+ static load(home: string, now?: () => Date): OfferedInvites;
229
+ get size(): number;
230
+ has(inviteId: string): boolean;
231
+ add(inviteId: string): void;
232
+ remove(inviteId: string): void;
233
+ private persist;
234
+ }
235
+
236
+ declare const RETRY_LADDER_MS: readonly number[];
237
+ /** After the ladder is exhausted: how often the runtime is asked whether it is usable again. */
238
+ declare const PREFLIGHT_WATCH_MS: number;
239
+ interface IntegrationInvokerOptions {
240
+ readonly runner: RunRunner;
241
+ /** The run prompts, resolved per run; null when the served texts are not available yet. */
242
+ readonly prompts: () => Promise<RunPrompts | null>;
243
+ /** A run is killed past this and counts as failed. */
244
+ readonly budgetMs: number;
245
+ readonly debounceMs?: number;
246
+ readonly retryLadderMs?: readonly number[];
247
+ readonly preflightWatchMs?: number;
248
+ /**
249
+ * Is anything waiting on the tray? Asked before every wake run (never
250
+ * before an invite run). Resolves the answer; rejects when the count could
251
+ * not be read, and then the run starts anyway. Absent: every wake runs.
252
+ */
253
+ readonly trayHasWaiting?: () => Promise<boolean>;
254
+ /** Invites already offered to a run from this machine. Defaults to an in-memory set. */
255
+ readonly offeredInvites?: OfferedInviteStore;
256
+ /** Called after every state change (a status writer hangs off this). */
257
+ readonly onChange?: () => void;
258
+ readonly now?: () => number;
259
+ readonly setTimeout?: (fn: () => void, ms: number) => TimerHandle;
260
+ readonly clearTimeout?: (handle: TimerHandle) => void;
261
+ readonly runId?: () => string;
262
+ }
263
+ interface InvokerCounters {
264
+ readonly wakes: number;
265
+ readonly absorbed: number;
266
+ readonly invites: number;
267
+ readonly runsStarted: number;
268
+ readonly runsOk: number;
269
+ readonly runsFailed: number;
270
+ readonly runsTimedOut: number;
271
+ readonly runsNotStarted: number;
272
+ /** Wake cycles that found the tray empty and started no run. */
273
+ readonly runsSkippedEmpty: number;
274
+ readonly retryRung: number;
275
+ readonly retryDueAt: number | null;
276
+ readonly lastRun: IntegrationLastRun | null;
277
+ readonly running: boolean;
278
+ }
279
+ declare class IntegrationInvoker {
280
+ private readonly runner;
281
+ private readonly prompts;
282
+ private readonly budgetMs;
283
+ private readonly ladder;
284
+ private readonly preflightWatchMs;
285
+ private readonly now;
286
+ private readonly _setTimeout;
287
+ private readonly _clearTimeout;
288
+ private readonly onChange;
289
+ private readonly newRunId;
290
+ private readonly trayHasWaiting;
291
+ private readonly offered;
292
+ private readonly coalescer;
293
+ private cycleDue;
294
+ private running;
295
+ private inFlight;
296
+ private stopped;
297
+ /** Invites queued for a run, in arrival order. */
298
+ private readonly invites;
299
+ /** Invites whose run did not start; offered again on the next wake. */
300
+ private readonly invitesAwaitingRetry;
301
+ /**
302
+ * Invite ids this process has taken, offered or not. The on-disk store says
303
+ * what was OFFERED; this says what is already in hand here — queued, in
304
+ * flight, or awaiting its retry — so the connect-time listing and a live
305
+ * frame for the same invite cannot queue it twice.
306
+ */
307
+ private readonly taken;
308
+ private retryRung;
309
+ private preflightWatch;
310
+ private preflightWasDown;
311
+ private invitesSeen;
312
+ private runsStarted;
313
+ private runsOk;
314
+ private runsFailed;
315
+ private runsTimedOut;
316
+ private runsNotStarted;
317
+ private runsSkippedEmpty;
318
+ private lastRun;
319
+ constructor(options: IntegrationInvokerOptions);
320
+ /** A wake from the socket (a frame), the connect-time catch-up, or any other source. Coalesced, then run. */
321
+ wake(source: string): void;
322
+ /**
323
+ * The second wake kind. Offered once per machine: an invite already offered
324
+ * to a run, already queued, or awaiting its retry is not queued again.
325
+ * Returns true when newly queued.
326
+ */
327
+ invite(invite: InviteWake): boolean;
328
+ /**
329
+ * Cancel timers and interrupt a run in flight (its signal aborts; the
330
+ * runner SIGTERMs the run's process group). `settled()` resolves when the
331
+ * interrupted run has ended.
332
+ */
222
333
  stop(): void;
223
- private onInbound;
224
- /** Queue one already-tracked row and ensure exactly one worker for its conversation. */
225
- private enqueueExisting;
226
- /** Process bounded backlog snapshots, in arrival order within a conversation. */
227
- private drainConversation;
228
- private handleNextBatch;
229
- private waitForForegroundClaimWindow;
230
- private noteForegroundDeferral;
231
- private finishForegroundDeferral;
232
- private turnContext;
233
- private markHandled;
234
- private markNoLongerPending;
235
- /** Bound reconnect-dedup memory without ever evicting unfinished work. */
236
- private pruneSeen;
237
- private acquireSlot;
238
- private releaseSlot;
334
+ /** The promise of the work currently running, for tests and graceful stops. */
335
+ settled(): Promise<void>;
336
+ counters(): InvokerCounters;
337
+ private onWakeFired;
338
+ /** Run the worker if idle. One run at a time; work that lands mid-run runs afterwards. */
339
+ private schedule;
340
+ private drain;
341
+ /**
342
+ * The count before a wake run. True: start the run (something waits, or
343
+ * the count could not be read). False: the tray is empty — no run, nothing
344
+ * owed — or the invoker stopped while counting.
345
+ */
346
+ private trayOwesRun;
347
+ /**
348
+ * Nothing is owed any more — a wake run read the whole tray, or a count
349
+ * found it empty: back to the first rung, drop a pending re-wake (it would
350
+ * only ring for a backlog that is already handled), end the preflight watch.
351
+ */
352
+ private settleLadder;
353
+ private run;
354
+ /**
355
+ * An invite counts as offered once its run has started (recorded at
356
+ * `onStarted`; a runner that never signals it is recorded here, when the
357
+ * run ends): the agent had its chance, and the invite stays reachable
358
+ * through the hosted invite tools in any later run — including a run this
359
+ * integration interrupted. A run that never got going is no offer: the
360
+ * record is taken back and the invite is held for the next wake.
361
+ */
362
+ private settleInvite;
363
+ private scheduleRetry;
364
+ private armPreflightWatch;
365
+ private clearPreflightWatch;
366
+ private probePreflight;
367
+ }
368
+
369
+ interface SpawnRunSpec {
370
+ readonly command: string;
371
+ readonly args: readonly string[];
372
+ readonly cwd: string;
373
+ readonly env: NodeJS.ProcessEnv;
374
+ /** Written to the child's stdin and closed; `null` closes stdin at once. */
375
+ readonly stdin: string | null;
376
+ /** Kill past this. */
377
+ readonly budgetMs: number;
378
+ /** SIGTERM first; SIGKILL this long after. */
379
+ readonly graceMs?: number;
380
+ /**
381
+ * Aborting it SIGTERMs the run's process group (SIGKILL after `graceMs`);
382
+ * the outcome is `failed` with an "interrupted" detail.
383
+ */
384
+ readonly signal?: AbortSignal;
385
+ /** Called once when the child process has been spawned (`RunRequest.onStarted`). */
386
+ readonly onStarted?: () => void;
239
387
  }
388
+ /** Strip anything key-shaped or terminal-styled from a diagnostic, and bound it. */
389
+ declare function redactDiagnostic(value: string, max?: number): string;
390
+ /** Start the command, wait for it, classify. Never throws. */
391
+ declare function spawnRun(spec: SpawnRunSpec): Promise<RunOutcome>;
240
392
 
241
- export { AgentWsClient, type CoordConfig, Daemon, type DaemonConfig, ReplyCoord, type ResolveDaemonOpts, type RunDaemonOpts, RuntimeAdapter, TurnContext, TurnDisposition, type WsClientEvents, buildAgentChatTurnPrompt, describeConversation, describeSender, parseAgentChatTurnOutcome, parseInbound, resolveDaemonConfig, resolveTurnDisposition, runDaemon, senderOf, wsUrlFor };
393
+ export { type DaemonConfig, Integration, IntegrationConnection, type IntegrationConnectionEvents, type IntegrationConnectionOptions, IntegrationInvoker, type IntegrationInvokerOptions, type IntegrationOptions, type InviteWake, type InvokerCounters, type MessageWake, OFFERED_INVITES_FILE, type OfferedInviteStore, OfferedInvites, PREFLIGHT_WATCH_MS, RETRY_LADDER_MS, type ReminderWake, type ResolveDaemonOpts, type RunIntegrationOpts, RunOutcome, RunRunner, type SpawnRunSpec, type Wake, offeredInvitesPath, redactDiagnostic, resolveDaemonConfig, runIntegration, socketStateOf, spawnRun, wsBaseFor, wsUrlFor };