@agentchatme/agent-core 0.3.1 → 0.4.1
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/README.md +44 -28
- package/dist/{chunk-4YF2K5ND.js → chunk-7LAAAXUO.js} +393 -888
- package/dist/chunk-7LAAAXUO.js.map +1 -0
- package/dist/chunk-AE4XHKHQ.js +283 -0
- package/dist/chunk-AE4XHKHQ.js.map +1 -0
- package/dist/chunk-QDM4EFI7.js +139 -0
- package/dist/chunk-QDM4EFI7.js.map +1 -0
- package/dist/chunk-XDWBTX5J.js +30 -0
- package/dist/chunk-XDWBTX5J.js.map +1 -0
- package/dist/daemon-entry.d.ts +127 -282
- package/dist/daemon-entry.js +314 -951
- package/dist/daemon-entry.js.map +1 -1
- package/dist/index.d.ts +115 -32
- package/dist/index.js +302 -241
- package/dist/index.js.map +1 -1
- package/dist/presets.d.ts +289 -0
- package/dist/presets.js +545 -0
- package/dist/presets.js.map +1 -0
- package/dist/runner-B-ZZDAAm.d.ts +130 -0
- package/dist/served-manual-99vEOjJS.d.ts +380 -0
- package/package.json +8 -3
- package/dist/chunk-4YF2K5ND.js.map +0 -1
- package/dist/prompts-BUfpwUT7.d.ts +0 -630
package/dist/daemon-entry.js
CHANGED
|
@@ -1,29 +1,35 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
INTEGRATION_ENV,
|
|
3
|
+
INTEGRATION_ENV_LEGACY,
|
|
4
|
+
INTEGRATION_ENV_LEGACY_REMOVAL,
|
|
5
|
+
MANUAL,
|
|
4
6
|
acquireLeaderLock,
|
|
5
|
-
atomicWriteFile,
|
|
6
7
|
beat,
|
|
7
|
-
buildRunPrompts,
|
|
8
|
-
clientIdentityOf,
|
|
9
8
|
credentialsPath,
|
|
10
|
-
|
|
9
|
+
describeManualSync,
|
|
11
10
|
idle,
|
|
12
11
|
integrationDisabledBy,
|
|
13
|
-
|
|
14
|
-
normalizeHandle,
|
|
15
|
-
readJsonFile,
|
|
12
|
+
isRunnerFactory,
|
|
16
13
|
resolveIdentity,
|
|
17
14
|
resolveRunBudgetMs,
|
|
18
15
|
resolveRunProfile,
|
|
19
|
-
|
|
20
|
-
spawnCommandSync,
|
|
21
|
-
trayHasWaiting,
|
|
16
|
+
textsCachePath,
|
|
22
17
|
writeIntegrationStatus
|
|
23
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-7LAAAXUO.js";
|
|
19
|
+
import {
|
|
20
|
+
WINDOWS_SWEEP_TIMEOUT_MS,
|
|
21
|
+
describeWindowsSweep,
|
|
22
|
+
redactDiagnostic,
|
|
23
|
+
spawnRun,
|
|
24
|
+
sweepWindowsDescendants
|
|
25
|
+
} from "./chunk-AE4XHKHQ.js";
|
|
26
|
+
import {
|
|
27
|
+
clientIdentityOf,
|
|
28
|
+
log
|
|
29
|
+
} from "./chunk-QDM4EFI7.js";
|
|
24
30
|
|
|
25
31
|
// src/integration/run.ts
|
|
26
|
-
import * as
|
|
32
|
+
import * as path2 from "path";
|
|
27
33
|
import * as fs from "fs";
|
|
28
34
|
|
|
29
35
|
// src/daemon/config.ts
|
|
@@ -37,7 +43,7 @@ function wsUrlFor(apiBase) {
|
|
|
37
43
|
}
|
|
38
44
|
async function resolveDaemonConfig(opts) {
|
|
39
45
|
const home = path.resolve(opts.home);
|
|
40
|
-
const id = resolveIdentity(home);
|
|
46
|
+
const id = resolveIdentity(home, { envKey: opts.envKey !== false });
|
|
41
47
|
if (id === null) {
|
|
42
48
|
throw new Error(`no AgentChat identity in ${home} \u2014 register this agent first`);
|
|
43
49
|
}
|
|
@@ -68,11 +74,10 @@ async function resolveDaemonConfig(opts) {
|
|
|
68
74
|
}
|
|
69
75
|
|
|
70
76
|
// src/integration/integration.ts
|
|
71
|
-
import
|
|
77
|
+
import * as crypto from "crypto";
|
|
78
|
+
import { AgentChatClient as AgentChatClient2, RealtimeClient, integration as kit } from "agentchatme";
|
|
72
79
|
|
|
73
|
-
// src/integration/
|
|
74
|
-
import { EventEmitter } from "events";
|
|
75
|
-
import { RealtimeClient } from "agentchatme";
|
|
80
|
+
// src/integration/socket-state.ts
|
|
76
81
|
function socketStateOf(next, previous) {
|
|
77
82
|
switch (next) {
|
|
78
83
|
case "idle":
|
|
@@ -93,755 +98,168 @@ function socketStateOf(next, previous) {
|
|
|
93
98
|
function blockedDetail(info) {
|
|
94
99
|
return `auth rejected (close ${info.code}${info.reason ? ` ${info.reason}` : ""}) \u2014 check the agent's API key; a fresh hello is tried every 10\u201315 min until one is accepted`;
|
|
95
100
|
}
|
|
96
|
-
function stringField(record, keys) {
|
|
97
|
-
for (const key of keys) {
|
|
98
|
-
const value = record[key];
|
|
99
|
-
if (typeof value === "string" && value.length > 0) return value;
|
|
100
|
-
}
|
|
101
|
-
return null;
|
|
102
|
-
}
|
|
103
|
-
function asRecord(value) {
|
|
104
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
105
|
-
}
|
|
106
|
-
var IntegrationConnection = class extends EventEmitter {
|
|
107
|
-
constructor(options) {
|
|
108
|
-
super();
|
|
109
|
-
this.options = options;
|
|
110
|
-
this.selfHandle = normalizeHandle(options.selfHandle);
|
|
111
|
-
}
|
|
112
|
-
options;
|
|
113
|
-
rt = null;
|
|
114
|
-
_state = "idle";
|
|
115
|
-
stopped = false;
|
|
116
|
-
/** Rejected hellos since the last accepted one: the first is an error line, the rest are info. */
|
|
117
|
-
refusals = 0;
|
|
118
|
-
selfHandle;
|
|
119
|
-
get state() {
|
|
120
|
-
return this._state;
|
|
121
|
-
}
|
|
122
|
-
/** True only while the socket is live — `hello.ok` received, not merely open. */
|
|
123
|
-
get connected() {
|
|
124
|
-
return this._state === "ready";
|
|
125
|
-
}
|
|
126
|
-
on(event, listener) {
|
|
127
|
-
return super.on(event, listener);
|
|
128
|
-
}
|
|
129
|
-
/** Open the SDK's client. Once: it lives until `stop()`, reconnecting on its own. */
|
|
130
|
-
start() {
|
|
131
|
-
if (this.rt !== null || this.stopped) return;
|
|
132
|
-
const rt = new RealtimeClient({
|
|
133
|
-
apiKey: this.options.apiKey,
|
|
134
|
-
baseUrl: this.options.wsBase,
|
|
135
|
-
clientIdentity: clientIdentityOf(this.options.client),
|
|
136
|
-
// Delivered = this machine received it. Acked at parse time, before
|
|
137
|
-
// anything here runs; read state is the agent's verdict, separately.
|
|
138
|
-
ackOnReceipt: true,
|
|
139
|
-
reconnect: true,
|
|
140
|
-
...this.options.reconnectIntervalMs !== void 0 ? { reconnectInterval: this.options.reconnectIntervalMs } : {},
|
|
141
|
-
...this.options.maxReconnectIntervalMs !== void 0 ? { maxReconnectInterval: this.options.maxReconnectIntervalMs } : {}
|
|
142
|
-
});
|
|
143
|
-
this.rt = rt;
|
|
144
|
-
this.setState("connecting");
|
|
145
|
-
rt.on("state", (next) => this.setState(socketStateOf(next, this._state)));
|
|
146
|
-
rt.on("blocked", (info) => this.onBlocked(info));
|
|
147
|
-
rt.onConnect(() => {
|
|
148
|
-
this.refusals = 0;
|
|
149
|
-
log.info(`socket ready (hello.ok) \u2014 acks ${rt.ackNegotiated ? "on receipt" : "not negotiated by this server"}`);
|
|
150
|
-
this.emit("ready");
|
|
151
|
-
});
|
|
152
|
-
rt.onDisconnect(({ code, reason, initiator }) => {
|
|
153
|
-
if (this.stopped) return;
|
|
154
|
-
log.warn(`socket closed (${code}${reason ? ` ${reason}` : ""}${initiator === "client" ? ", by this client" : ""})`);
|
|
155
|
-
});
|
|
156
|
-
rt.onError((err) => {
|
|
157
|
-
if (this.stopped) return;
|
|
158
|
-
log.warn(`socket: ${err.message}`);
|
|
159
|
-
});
|
|
160
|
-
rt.on("message.new", (message) => {
|
|
161
|
-
if (!this.stopped) this.onMessageFrame(message);
|
|
162
|
-
});
|
|
163
|
-
rt.on("wake", (frame) => {
|
|
164
|
-
if (!this.stopped) this.onWakeFrame(frame);
|
|
165
|
-
});
|
|
166
|
-
rt.on("group.invite.received", (message) => {
|
|
167
|
-
if (!this.stopped) this.onInviteFrame(message);
|
|
168
|
-
});
|
|
169
|
-
rt.connect().catch((err) => {
|
|
170
|
-
if (this.stopped || rt.state !== "idle") return;
|
|
171
|
-
log.error(`socket cannot be opened (${err instanceof Error ? err.message : String(err)}) \u2014 no WebSocket implementation; holding no socket`);
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
/** End the SDK's client. Final: a stopped connection is not restarted. */
|
|
175
|
-
stop() {
|
|
176
|
-
if (this.stopped) return;
|
|
177
|
-
this.stopped = true;
|
|
178
|
-
const rt = this.rt;
|
|
179
|
-
this.rt = null;
|
|
180
|
-
try {
|
|
181
|
-
rt?.disconnect();
|
|
182
|
-
} catch {
|
|
183
|
-
}
|
|
184
|
-
this.setState("closed");
|
|
185
|
-
}
|
|
186
|
-
setState(next) {
|
|
187
|
-
const prev = this._state;
|
|
188
|
-
if (prev === next) return;
|
|
189
|
-
this._state = next;
|
|
190
|
-
if (next === "connecting") log.info("socket connecting");
|
|
191
|
-
else if (next === "reconnecting") log.info("socket reconnecting \u2014 the SDK backs off and retries; it never gives up");
|
|
192
|
-
else if (next === "closed") log.info("socket closed");
|
|
193
|
-
this.emit("state", next, prev);
|
|
194
|
-
}
|
|
195
|
-
/** The SDK is `blocked`: the server refused the credential on the hello. Fires per rejected attempt. */
|
|
196
|
-
onBlocked(info) {
|
|
197
|
-
if (this.stopped) return;
|
|
198
|
-
const detail = blockedDetail(info);
|
|
199
|
-
this.refusals += 1;
|
|
200
|
-
if (this.refusals === 1) {
|
|
201
|
-
log.error(`socket blocked (auth): ${detail}`);
|
|
202
|
-
} else {
|
|
203
|
-
const next = info.retryInMs === null ? "no retry" : `next hello in about ${Math.max(1, Math.round(info.retryInMs / 6e4))} min`;
|
|
204
|
-
log.info(`socket still blocked (auth): close ${info.code}${info.reason ? ` ${info.reason}` : ""} \u2014 ${next}`);
|
|
205
|
-
}
|
|
206
|
-
this.emit("blocked", detail, info);
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* A `message.new` frame. Only the sender (echo filter) and the ids (log
|
|
210
|
-
* line) are read. `content`, `metadata`, previews — never touched. The SDK
|
|
211
|
-
* acked it before this ran.
|
|
212
|
-
*/
|
|
213
|
-
onMessageFrame(message) {
|
|
214
|
-
const payload = asRecord(message.payload);
|
|
215
|
-
if (payload === null) {
|
|
216
|
-
log.warn("socket: message.new without an object payload \u2014 dropped");
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
const senderRaw = stringField(payload, ["sender", "sender_handle", "from"]);
|
|
220
|
-
const sender = senderRaw === null ? null : normalizeHandle(senderRaw);
|
|
221
|
-
const messageId = stringField(payload, ["id"]);
|
|
222
|
-
const conversationId = stringField(payload, ["conversation_id"]);
|
|
223
|
-
if (sender !== null && sender === this.selfHandle) {
|
|
224
|
-
log.debug(`socket: own echo in ${conversationId ?? "?"} \u2014 not a wake`);
|
|
225
|
-
this.emit("echo");
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
log.info(`wake \u2014 message.new conv=${conversationId ?? "?"} msg=${messageId ?? "?"} from=@${sender ?? "?"}`);
|
|
229
|
-
this.emit("wake", { source: "message", sender, conversationId, messageId });
|
|
230
|
-
}
|
|
231
|
-
/** A `wake` frame, validated by the SDK. No message, nothing to ack. */
|
|
232
|
-
onWakeFrame(frame) {
|
|
233
|
-
const { conversation_id, anchor_message_id, step, reason } = frame.payload;
|
|
234
|
-
log.info(`wake \u2014 ${reason} conv=${conversation_id} anchor=${anchor_message_id} step=${step}`);
|
|
235
|
-
this.emit("wake", {
|
|
236
|
-
source: "reminder",
|
|
237
|
-
conversationId: conversation_id,
|
|
238
|
-
anchorMessageId: anchor_message_id,
|
|
239
|
-
step
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
onInviteFrame(message) {
|
|
243
|
-
const payload = asRecord(message.payload);
|
|
244
|
-
if (payload === null) {
|
|
245
|
-
log.warn("socket: group.invite.received without an object payload \u2014 dropped");
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const inviteId = stringField(payload, ["invite_id", "id"]);
|
|
249
|
-
if (inviteId === null) {
|
|
250
|
-
log.warn("socket: group invite without an invite id \u2014 dropped");
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
const invite = {
|
|
254
|
-
inviteId,
|
|
255
|
-
groupId: stringField(payload, ["group_id", "conversation_id"]),
|
|
256
|
-
groupName: stringField(payload, ["group_name", "name"]),
|
|
257
|
-
inviterHandle: stringField(payload, ["inviter_handle", "inviter", "from"])
|
|
258
|
-
};
|
|
259
|
-
log.info(`wake \u2014 group invite ${invite.inviteId} to ${invite.groupId ?? "?"} from=@${invite.inviterHandle ?? "?"}`);
|
|
260
|
-
this.emit("invite", invite);
|
|
261
|
-
}
|
|
262
|
-
};
|
|
263
|
-
|
|
264
|
-
// src/integration/invoker.ts
|
|
265
|
-
import * as crypto from "crypto";
|
|
266
|
-
|
|
267
|
-
// src/integration/wake.ts
|
|
268
|
-
var DEFAULT_WAKE_DEBOUNCE_MS = 2e3;
|
|
269
|
-
var WakeCoalescer = class {
|
|
270
|
-
onFire;
|
|
271
|
-
debounceMs;
|
|
272
|
-
now;
|
|
273
|
-
_setTimeout;
|
|
274
|
-
_clearTimeout;
|
|
275
|
-
timer = null;
|
|
276
|
-
delayed = null;
|
|
277
|
-
delayedDeadline = null;
|
|
278
|
-
stopped = false;
|
|
279
|
-
wakes = 0;
|
|
280
|
-
absorbed = 0;
|
|
281
|
-
fires = 0;
|
|
282
|
-
constructor(options) {
|
|
283
|
-
const debounce = options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS;
|
|
284
|
-
if (!(debounce >= 0)) throw new RangeError("debounceMs must be >= 0");
|
|
285
|
-
this.onFire = options.onFire;
|
|
286
|
-
this.debounceMs = debounce;
|
|
287
|
-
this.now = options.now ?? Date.now;
|
|
288
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
289
|
-
this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
|
|
290
|
-
}
|
|
291
|
-
/** True while a debounce timer is armed. */
|
|
292
|
-
get armed() {
|
|
293
|
-
return this.timer !== null;
|
|
294
|
-
}
|
|
295
|
-
/** True while a retry wake is scheduled and has not fired. */
|
|
296
|
-
get delayedPending() {
|
|
297
|
-
return this.delayed !== null;
|
|
298
|
-
}
|
|
299
|
-
/** Epoch ms of the pending retry wake, or null. */
|
|
300
|
-
get delayedDue() {
|
|
301
|
-
return this.delayedDeadline;
|
|
302
|
-
}
|
|
303
|
-
/** A wake: arm the timer if none is armed; otherwise absorb. */
|
|
304
|
-
wake() {
|
|
305
|
-
if (this.stopped) return;
|
|
306
|
-
this.wakes += 1;
|
|
307
|
-
if (this.timer !== null) {
|
|
308
|
-
this.absorbed += 1;
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
this.timer = this._setTimeout(() => this.fire(), this.debounceMs);
|
|
312
|
-
}
|
|
313
|
-
/** A delayed wake (retry ladder). The sooner pending deadline is kept. */
|
|
314
|
-
wakeAfter(delayMs) {
|
|
315
|
-
if (this.stopped) return;
|
|
316
|
-
const delay = Math.max(0, delayMs);
|
|
317
|
-
const deadline = this.now() + delay;
|
|
318
|
-
if (this.delayed !== null) {
|
|
319
|
-
if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
this._clearTimeout(this.delayed);
|
|
323
|
-
}
|
|
324
|
-
this.delayedDeadline = deadline;
|
|
325
|
-
this.delayed = this._setTimeout(() => {
|
|
326
|
-
this.delayed = null;
|
|
327
|
-
this.delayedDeadline = null;
|
|
328
|
-
this.wake();
|
|
329
|
-
}, delay);
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* Drop a pending retry wake, if there is one; returns whether there was.
|
|
333
|
-
* The debounce timer and later wakes are unaffected. For when nothing is
|
|
334
|
-
* owed any more — a run read the whole tray, or the tray was found empty —
|
|
335
|
-
* so the retry would only ring for a backlog that is already handled.
|
|
336
|
-
*/
|
|
337
|
-
cancelDelayed() {
|
|
338
|
-
if (this.delayed === null) return false;
|
|
339
|
-
this._clearTimeout(this.delayed);
|
|
340
|
-
this.delayed = null;
|
|
341
|
-
this.delayedDeadline = null;
|
|
342
|
-
return true;
|
|
343
|
-
}
|
|
344
|
-
/** Cancel everything; later wakes are ignored. */
|
|
345
|
-
stop() {
|
|
346
|
-
this.stopped = true;
|
|
347
|
-
if (this.timer !== null) {
|
|
348
|
-
this._clearTimeout(this.timer);
|
|
349
|
-
this.timer = null;
|
|
350
|
-
}
|
|
351
|
-
this.cancelDelayed();
|
|
352
|
-
}
|
|
353
|
-
fire() {
|
|
354
|
-
this.timer = null;
|
|
355
|
-
if (this.stopped) return;
|
|
356
|
-
this.fires += 1;
|
|
357
|
-
try {
|
|
358
|
-
this.onFire();
|
|
359
|
-
} catch {
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
};
|
|
363
|
-
|
|
364
|
-
// src/integration/invites.ts
|
|
365
|
-
import * as path2 from "path";
|
|
366
|
-
var OFFERED_INVITES_FILE = "invites.offered.json";
|
|
367
|
-
var MAX_REMEMBERED = 1e3;
|
|
368
|
-
var Schema = external_exports.object({
|
|
369
|
-
version: external_exports.literal(1),
|
|
370
|
-
offered: external_exports.array(external_exports.object({ id: external_exports.string(), at: external_exports.string() }))
|
|
371
|
-
});
|
|
372
|
-
function offeredInvitesPath(home) {
|
|
373
|
-
return path2.join(home, OFFERED_INVITES_FILE);
|
|
374
|
-
}
|
|
375
|
-
var OfferedInvites = class _OfferedInvites {
|
|
376
|
-
/** `home === null` keeps the set in memory only (tests). */
|
|
377
|
-
constructor(home, entries = [], now = () => /* @__PURE__ */ new Date()) {
|
|
378
|
-
this.home = home;
|
|
379
|
-
this.now = now;
|
|
380
|
-
this.entries = entries.slice(-MAX_REMEMBERED);
|
|
381
|
-
}
|
|
382
|
-
home;
|
|
383
|
-
now;
|
|
384
|
-
entries;
|
|
385
|
-
/** Read the set from the identity home; a missing or malformed file is an empty set. */
|
|
386
|
-
static load(home, now) {
|
|
387
|
-
const parsed = Schema.safeParse(readJsonFile(offeredInvitesPath(home)));
|
|
388
|
-
return new _OfferedInvites(home, parsed.success ? parsed.data.offered : [], now);
|
|
389
|
-
}
|
|
390
|
-
get size() {
|
|
391
|
-
return this.entries.length;
|
|
392
|
-
}
|
|
393
|
-
has(inviteId) {
|
|
394
|
-
return this.entries.some((entry) => entry.id === inviteId);
|
|
395
|
-
}
|
|
396
|
-
add(inviteId) {
|
|
397
|
-
if (this.has(inviteId)) return;
|
|
398
|
-
this.entries.push({ id: inviteId, at: this.now().toISOString() });
|
|
399
|
-
while (this.entries.length > MAX_REMEMBERED) this.entries.shift();
|
|
400
|
-
this.persist();
|
|
401
|
-
}
|
|
402
|
-
remove(inviteId) {
|
|
403
|
-
const index = this.entries.findIndex((entry) => entry.id === inviteId);
|
|
404
|
-
if (index === -1) return;
|
|
405
|
-
this.entries.splice(index, 1);
|
|
406
|
-
this.persist();
|
|
407
|
-
}
|
|
408
|
-
persist() {
|
|
409
|
-
if (this.home === null) return;
|
|
410
|
-
try {
|
|
411
|
-
atomicWriteFile(
|
|
412
|
-
offeredInvitesPath(this.home),
|
|
413
|
-
`${JSON.stringify({ version: 1, offered: this.entries }, null, 2)}
|
|
414
|
-
`,
|
|
415
|
-
384
|
|
416
|
-
);
|
|
417
|
-
} catch (err) {
|
|
418
|
-
log.debug(`offered-invites write failed: ${String(err)}`);
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
};
|
|
422
|
-
|
|
423
|
-
// src/integration/invoker.ts
|
|
424
|
-
var RETRY_LADDER_MS = [6e4, 3e5, 18e5];
|
|
425
|
-
var PREFLIGHT_WATCH_MS = 5 * 6e4;
|
|
426
|
-
var MAX_TAKEN = 1e3;
|
|
427
|
-
var IntegrationInvoker = class {
|
|
428
|
-
runner;
|
|
429
|
-
prompts;
|
|
430
|
-
budgetMs;
|
|
431
|
-
ladder;
|
|
432
|
-
preflightWatchMs;
|
|
433
|
-
now;
|
|
434
|
-
_setTimeout;
|
|
435
|
-
_clearTimeout;
|
|
436
|
-
onChange;
|
|
437
|
-
newRunId;
|
|
438
|
-
trayHasWaiting;
|
|
439
|
-
offered;
|
|
440
|
-
coalescer;
|
|
441
|
-
cycleDue = false;
|
|
442
|
-
running = null;
|
|
443
|
-
inFlight = null;
|
|
444
|
-
stopped = false;
|
|
445
|
-
/** Invites queued for a run, in arrival order. */
|
|
446
|
-
invites = [];
|
|
447
|
-
/** Invites whose run did not start; offered again on the next wake. */
|
|
448
|
-
invitesAwaitingRetry = [];
|
|
449
|
-
/**
|
|
450
|
-
* Invite ids this process has taken, offered or not. The on-disk store says
|
|
451
|
-
* what was OFFERED; this says what is already in hand here — queued, in
|
|
452
|
-
* flight, or awaiting its retry — so the connect-time listing and a live
|
|
453
|
-
* frame for the same invite cannot queue it twice.
|
|
454
|
-
*/
|
|
455
|
-
taken = /* @__PURE__ */ new Set();
|
|
456
|
-
retryRung = 0;
|
|
457
|
-
preflightWatch = null;
|
|
458
|
-
preflightWasDown = false;
|
|
459
|
-
invitesSeen = 0;
|
|
460
|
-
runsStarted = 0;
|
|
461
|
-
runsOk = 0;
|
|
462
|
-
runsFailed = 0;
|
|
463
|
-
runsTimedOut = 0;
|
|
464
|
-
runsNotStarted = 0;
|
|
465
|
-
runsSkippedEmpty = 0;
|
|
466
|
-
lastRun = null;
|
|
467
|
-
constructor(options) {
|
|
468
|
-
this.runner = options.runner;
|
|
469
|
-
this.prompts = options.prompts;
|
|
470
|
-
this.budgetMs = options.budgetMs;
|
|
471
|
-
this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
|
|
472
|
-
this.preflightWatchMs = options.preflightWatchMs ?? PREFLIGHT_WATCH_MS;
|
|
473
|
-
this.now = options.now ?? Date.now;
|
|
474
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
475
|
-
this._clearTimeout = options.clearTimeout ?? ((handle) => clearTimeout(handle));
|
|
476
|
-
this.onChange = options.onChange ?? (() => void 0);
|
|
477
|
-
this.newRunId = options.runId ?? (() => crypto.randomUUID());
|
|
478
|
-
this.trayHasWaiting = options.trayHasWaiting ?? null;
|
|
479
|
-
this.offered = options.offeredInvites ?? new OfferedInvites(null);
|
|
480
|
-
this.coalescer = new WakeCoalescer({
|
|
481
|
-
onFire: () => this.onWakeFired(),
|
|
482
|
-
debounceMs: options.debounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS,
|
|
483
|
-
now: this.now,
|
|
484
|
-
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
485
|
-
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
|
|
486
|
-
});
|
|
487
|
-
}
|
|
488
|
-
// ─── wakes ──────────────────────────────────────────────────────────────
|
|
489
|
-
/** A wake from the socket (a frame), the connect-time catch-up, or any other source. Coalesced, then run. */
|
|
490
|
-
wake(source) {
|
|
491
|
-
if (this.stopped) return;
|
|
492
|
-
log.debug(`wake (${source})`);
|
|
493
|
-
this.coalescer.wake();
|
|
494
|
-
this.onChange();
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* The second wake kind. Offered once per machine: an invite already offered
|
|
498
|
-
* to a run, already queued, or awaiting its retry is not queued again.
|
|
499
|
-
* Returns true when newly queued.
|
|
500
|
-
*/
|
|
501
|
-
invite(invite) {
|
|
502
|
-
if (this.stopped) return false;
|
|
503
|
-
if (this.offered.has(invite.inviteId) || this.taken.has(invite.inviteId)) return false;
|
|
504
|
-
this.taken.add(invite.inviteId);
|
|
505
|
-
if (this.taken.size > MAX_TAKEN) {
|
|
506
|
-
const oldest = this.taken.values().next().value;
|
|
507
|
-
if (oldest !== void 0) this.taken.delete(oldest);
|
|
508
|
-
}
|
|
509
|
-
this.invitesSeen += 1;
|
|
510
|
-
this.invites.push(invite);
|
|
511
|
-
this.onChange();
|
|
512
|
-
this.schedule();
|
|
513
|
-
return true;
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Cancel timers and interrupt a run in flight (its signal aborts; the
|
|
517
|
-
* runner SIGTERMs the run's process group). `settled()` resolves when the
|
|
518
|
-
* interrupted run has ended.
|
|
519
|
-
*/
|
|
520
|
-
stop() {
|
|
521
|
-
this.stopped = true;
|
|
522
|
-
this.coalescer.stop();
|
|
523
|
-
this.clearPreflightWatch();
|
|
524
|
-
this.inFlight?.abort();
|
|
525
|
-
}
|
|
526
|
-
/** The promise of the work currently running, for tests and graceful stops. */
|
|
527
|
-
settled() {
|
|
528
|
-
return this.running ?? Promise.resolve();
|
|
529
|
-
}
|
|
530
|
-
counters() {
|
|
531
|
-
return {
|
|
532
|
-
wakes: this.coalescer.wakes,
|
|
533
|
-
absorbed: this.coalescer.absorbed,
|
|
534
|
-
invites: this.invitesSeen,
|
|
535
|
-
runsStarted: this.runsStarted,
|
|
536
|
-
runsOk: this.runsOk,
|
|
537
|
-
runsFailed: this.runsFailed,
|
|
538
|
-
runsTimedOut: this.runsTimedOut,
|
|
539
|
-
runsNotStarted: this.runsNotStarted,
|
|
540
|
-
runsSkippedEmpty: this.runsSkippedEmpty,
|
|
541
|
-
retryRung: this.retryRung,
|
|
542
|
-
retryDueAt: this.coalescer.delayedDue,
|
|
543
|
-
lastRun: this.lastRun,
|
|
544
|
-
running: this.running !== null
|
|
545
|
-
};
|
|
546
|
-
}
|
|
547
|
-
// ─── worker ─────────────────────────────────────────────────────────────
|
|
548
|
-
onWakeFired() {
|
|
549
|
-
this.cycleDue = true;
|
|
550
|
-
if (this.invitesAwaitingRetry.length > 0) {
|
|
551
|
-
const retry = this.invitesAwaitingRetry.splice(0);
|
|
552
|
-
log.info(`${retry.length} group invite(s) whose run did not start are offered again`);
|
|
553
|
-
this.invites.push(...retry);
|
|
554
|
-
}
|
|
555
|
-
this.schedule();
|
|
556
|
-
}
|
|
557
|
-
/** Run the worker if idle. One run at a time; work that lands mid-run runs afterwards. */
|
|
558
|
-
schedule() {
|
|
559
|
-
if (this.running) return;
|
|
560
|
-
this.running = this.drain().finally(() => {
|
|
561
|
-
this.running = null;
|
|
562
|
-
this.onChange();
|
|
563
|
-
if (!this.stopped && (this.cycleDue || this.invites.length > 0)) this.schedule();
|
|
564
|
-
});
|
|
565
|
-
}
|
|
566
|
-
async drain() {
|
|
567
|
-
while (!this.stopped) {
|
|
568
|
-
const invite = this.invites.shift();
|
|
569
|
-
if (invite) {
|
|
570
|
-
await this.run("invite", invite);
|
|
571
|
-
continue;
|
|
572
|
-
}
|
|
573
|
-
if (this.cycleDue) {
|
|
574
|
-
this.cycleDue = false;
|
|
575
|
-
if (!await this.trayOwesRun()) continue;
|
|
576
|
-
await this.run("wake");
|
|
577
|
-
continue;
|
|
578
|
-
}
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
/**
|
|
583
|
-
* The count before a wake run. True: start the run (something waits, or
|
|
584
|
-
* the count could not be read). False: the tray is empty — no run, nothing
|
|
585
|
-
* owed — or the invoker stopped while counting.
|
|
586
|
-
*/
|
|
587
|
-
async trayOwesRun() {
|
|
588
|
-
if (this.trayHasWaiting === null) return true;
|
|
589
|
-
let waiting;
|
|
590
|
-
try {
|
|
591
|
-
waiting = await this.trayHasWaiting();
|
|
592
|
-
} catch (err) {
|
|
593
|
-
if (this.stopped) return false;
|
|
594
|
-
log.warn(
|
|
595
|
-
`tray count failed (${err instanceof Error ? err.message : String(err)}) \u2014 starting the run anyway: a failed count is not an empty tray`
|
|
596
|
-
);
|
|
597
|
-
return true;
|
|
598
|
-
}
|
|
599
|
-
if (this.stopped) return false;
|
|
600
|
-
if (waiting) return true;
|
|
601
|
-
this.runsSkippedEmpty += 1;
|
|
602
|
-
log.info(`wake: the tray is empty \u2014 no run (nothing is owed; ${this.runsSkippedEmpty} skipped so far)`);
|
|
603
|
-
this.settleLadder();
|
|
604
|
-
this.onChange();
|
|
605
|
-
return false;
|
|
606
|
-
}
|
|
607
|
-
/**
|
|
608
|
-
* Nothing is owed any more — a wake run read the whole tray, or a count
|
|
609
|
-
* found it empty: back to the first rung, drop a pending re-wake (it would
|
|
610
|
-
* only ring for a backlog that is already handled), end the preflight watch.
|
|
611
|
-
*/
|
|
612
|
-
settleLadder() {
|
|
613
|
-
this.retryRung = 0;
|
|
614
|
-
if (this.coalescer.cancelDelayed()) log.info("pending re-wake cancelled \u2014 nothing is owed any more");
|
|
615
|
-
this.clearPreflightWatch();
|
|
616
|
-
}
|
|
617
|
-
async run(kind, invite) {
|
|
618
|
-
const runId = this.newRunId();
|
|
619
|
-
const startedAt = this.now();
|
|
620
|
-
this.runsStarted += 1;
|
|
621
|
-
this.onChange();
|
|
622
|
-
log.info(`run start kind=${kind} id=${runId} budget=${Math.round(this.budgetMs / 1e3)}s`);
|
|
623
|
-
const controller = new AbortController();
|
|
624
|
-
this.inFlight = controller;
|
|
625
|
-
let offerRecorded = false;
|
|
626
|
-
const onStarted = () => {
|
|
627
|
-
if (invite === void 0 || offerRecorded) return;
|
|
628
|
-
offerRecorded = true;
|
|
629
|
-
this.offered.add(invite.inviteId);
|
|
630
|
-
};
|
|
631
|
-
let outcome;
|
|
632
|
-
try {
|
|
633
|
-
const prompts = await this.prompts();
|
|
634
|
-
if (prompts === null) {
|
|
635
|
-
outcome = {
|
|
636
|
-
state: "not_started",
|
|
637
|
-
exitCode: null,
|
|
638
|
-
durationMs: this.now() - startedAt,
|
|
639
|
-
detail: "no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home"
|
|
640
|
-
};
|
|
641
|
-
} else if (this.stopped) {
|
|
642
|
-
outcome = { state: "not_started", exitCode: null, durationMs: this.now() - startedAt, detail: "interrupted before the runtime was started" };
|
|
643
|
-
} else {
|
|
644
|
-
const prompt = kind === "invite" ? prompts.invite : prompts.wake;
|
|
645
|
-
outcome = await this.runner.start({
|
|
646
|
-
kind,
|
|
647
|
-
prompt,
|
|
648
|
-
runId,
|
|
649
|
-
budgetMs: this.budgetMs,
|
|
650
|
-
signal: controller.signal,
|
|
651
|
-
...invite !== void 0 ? { onStarted } : {}
|
|
652
|
-
});
|
|
653
|
-
}
|
|
654
|
-
} catch (err) {
|
|
655
|
-
outcome = {
|
|
656
|
-
state: "not_started",
|
|
657
|
-
exitCode: null,
|
|
658
|
-
durationMs: this.now() - startedAt,
|
|
659
|
-
detail: `runner threw: ${err instanceof Error ? err.message : String(err)}`
|
|
660
|
-
};
|
|
661
|
-
} finally {
|
|
662
|
-
if (this.inFlight === controller) this.inFlight = null;
|
|
663
|
-
}
|
|
664
|
-
this.lastRun = {
|
|
665
|
-
kind,
|
|
666
|
-
started_at: new Date(startedAt).toISOString(),
|
|
667
|
-
ended_at: new Date(this.now()).toISOString(),
|
|
668
|
-
state: outcome.state,
|
|
669
|
-
exit_code: outcome.exitCode,
|
|
670
|
-
duration_ms: outcome.durationMs,
|
|
671
|
-
detail: outcome.detail ?? null
|
|
672
|
-
};
|
|
673
|
-
switch (outcome.state) {
|
|
674
|
-
case "ok":
|
|
675
|
-
this.runsOk += 1;
|
|
676
|
-
if (kind === "wake") this.settleLadder();
|
|
677
|
-
log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1e3)}s (output discarded; any send was the agent's own hosted-tool call)`);
|
|
678
|
-
break;
|
|
679
|
-
case "failed":
|
|
680
|
-
this.runsFailed += 1;
|
|
681
|
-
break;
|
|
682
|
-
case "timed_out":
|
|
683
|
-
this.runsTimedOut += 1;
|
|
684
|
-
break;
|
|
685
|
-
case "not_started":
|
|
686
|
-
this.runsNotStarted += 1;
|
|
687
|
-
break;
|
|
688
|
-
}
|
|
689
|
-
if (invite !== void 0) this.settleInvite(invite, outcome, offerRecorded);
|
|
690
|
-
if (outcome.state !== "ok") {
|
|
691
|
-
log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""}`);
|
|
692
|
-
if (this.stopped) {
|
|
693
|
-
} else if (kind === "wake") {
|
|
694
|
-
this.scheduleRetry(`run ${outcome.state}`);
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
this.onChange();
|
|
698
|
-
}
|
|
699
|
-
/**
|
|
700
|
-
* An invite counts as offered once its run has started (recorded at
|
|
701
|
-
* `onStarted`; a runner that never signals it is recorded here, when the
|
|
702
|
-
* run ends): the agent had its chance, and the invite stays reachable
|
|
703
|
-
* through the hosted invite tools in any later run — including a run this
|
|
704
|
-
* integration interrupted. A run that never got going is no offer: the
|
|
705
|
-
* record is taken back and the invite is held for the next wake.
|
|
706
|
-
*/
|
|
707
|
-
settleInvite(invite, outcome, offerRecorded) {
|
|
708
|
-
if (outcome.state === "not_started") {
|
|
709
|
-
if (offerRecorded) this.offered.remove(invite.inviteId);
|
|
710
|
-
if (!this.invitesAwaitingRetry.some((i) => i.inviteId === invite.inviteId)) this.invitesAwaitingRetry.push(invite);
|
|
711
|
-
log.info(`group-invite run did not start \u2014 invite ${invite.inviteId} is offered again on the next wake`);
|
|
712
|
-
return;
|
|
713
|
-
}
|
|
714
|
-
if (!offerRecorded) this.offered.add(invite.inviteId);
|
|
715
|
-
if (outcome.state !== "ok") log.info(`group-invite run ${outcome.state} \u2014 the invite stays pending server-side, reachable through the hosted tools`);
|
|
716
|
-
}
|
|
717
|
-
scheduleRetry(reason) {
|
|
718
|
-
if (this.coalescer.delayedPending) {
|
|
719
|
-
log.info(`${reason} \u2014 a re-wake is already scheduled; not climbing the ladder`);
|
|
720
|
-
return;
|
|
721
|
-
}
|
|
722
|
-
if (this.retryRung >= this.ladder.length) {
|
|
723
|
-
log.warn(
|
|
724
|
-
`${reason} \u2014 retry ladder exhausted; the backlog stays unread. Watching the runtime's preflight every ${Math.round(this.preflightWatchMs / 1e3)}s: if it comes back, one re-wake; any wake also re-runs`
|
|
725
|
-
);
|
|
726
|
-
this.armPreflightWatch();
|
|
727
|
-
return;
|
|
728
|
-
}
|
|
729
|
-
const delay = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 6e4;
|
|
730
|
-
this.retryRung += 1;
|
|
731
|
-
log.warn(`${reason} \u2014 re-waking in ${Math.round(delay / 1e3)}s (rung ${this.retryRung}/${this.ladder.length})`);
|
|
732
|
-
this.coalescer.wakeAfter(delay);
|
|
733
|
-
}
|
|
734
|
-
// ─── preflight watch, after an exhausted ladder ─────────────────────────
|
|
735
|
-
armPreflightWatch() {
|
|
736
|
-
if (this.stopped || this.preflightWatch !== null) return;
|
|
737
|
-
this.preflightWatch = this._setTimeout(() => {
|
|
738
|
-
this.preflightWatch = null;
|
|
739
|
-
void this.probePreflight();
|
|
740
|
-
}, this.preflightWatchMs);
|
|
741
|
-
this.onChange();
|
|
742
|
-
}
|
|
743
|
-
clearPreflightWatch() {
|
|
744
|
-
if (this.preflightWatch !== null) {
|
|
745
|
-
this._clearTimeout(this.preflightWatch);
|
|
746
|
-
this.preflightWatch = null;
|
|
747
|
-
}
|
|
748
|
-
this.preflightWasDown = false;
|
|
749
|
-
}
|
|
750
|
-
async probePreflight() {
|
|
751
|
-
if (this.stopped) return;
|
|
752
|
-
let ok;
|
|
753
|
-
try {
|
|
754
|
-
ok = (await this.runner.preflight()).ok;
|
|
755
|
-
} catch {
|
|
756
|
-
ok = false;
|
|
757
|
-
}
|
|
758
|
-
if (this.stopped) return;
|
|
759
|
-
if (!ok) {
|
|
760
|
-
if (!this.preflightWasDown) log.info("runtime preflight is not ok \u2014 watching for it to come back");
|
|
761
|
-
this.preflightWasDown = true;
|
|
762
|
-
this.armPreflightWatch();
|
|
763
|
-
return;
|
|
764
|
-
}
|
|
765
|
-
if (this.preflightWasDown) {
|
|
766
|
-
this.preflightWasDown = false;
|
|
767
|
-
log.info("runtime preflight is ok again after an exhausted ladder \u2014 waking once");
|
|
768
|
-
this.wake("preflight");
|
|
769
|
-
return;
|
|
770
|
-
}
|
|
771
|
-
log.info("runtime preflight was already ok \u2014 the failures are not its readiness; the backlog waits for the next wake");
|
|
772
|
-
}
|
|
773
|
-
};
|
|
774
101
|
|
|
775
102
|
// src/integration/integration.ts
|
|
776
103
|
var HEARTBEAT_MS = 3e4;
|
|
777
104
|
var STATUS_MS = 3e4;
|
|
778
105
|
var HTTP_TIMEOUT_MS = 1e4;
|
|
106
|
+
var RUNNER_DEADLINE_SLACK_MS = 6e4;
|
|
107
|
+
var PREFLIGHT_DEADLINE_MS = 6e4;
|
|
108
|
+
var CYCLE_FAILURE_CHARS = 240;
|
|
109
|
+
function reasonOf(source, frameReason) {
|
|
110
|
+
switch (source) {
|
|
111
|
+
case "message":
|
|
112
|
+
return "messages";
|
|
113
|
+
case "invite":
|
|
114
|
+
return "invite";
|
|
115
|
+
case "wake_frame":
|
|
116
|
+
return frameReason ?? "reminder";
|
|
117
|
+
default:
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function withDeadline(work, ms, onTimeout) {
|
|
122
|
+
return new Promise((resolve3, reject) => {
|
|
123
|
+
let done = false;
|
|
124
|
+
const timer = setTimeout(() => {
|
|
125
|
+
if (done) return;
|
|
126
|
+
done = true;
|
|
127
|
+
try {
|
|
128
|
+
resolve3(onTimeout());
|
|
129
|
+
} catch (err) {
|
|
130
|
+
reject(err);
|
|
131
|
+
}
|
|
132
|
+
}, ms);
|
|
133
|
+
timer.unref?.();
|
|
134
|
+
work.then(
|
|
135
|
+
(value) => {
|
|
136
|
+
if (done) return;
|
|
137
|
+
done = true;
|
|
138
|
+
clearTimeout(timer);
|
|
139
|
+
resolve3(value);
|
|
140
|
+
},
|
|
141
|
+
(err) => {
|
|
142
|
+
if (done) return;
|
|
143
|
+
done = true;
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
reject(err);
|
|
146
|
+
}
|
|
147
|
+
);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
779
150
|
var Integration = class {
|
|
780
151
|
constructor(options) {
|
|
781
152
|
this.options = options;
|
|
782
153
|
const { cfg, client } = options;
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
154
|
+
const identity = clientIdentityOf(client);
|
|
155
|
+
this.api = options.api ?? new AgentChatClient2({ apiKey: cfg.apiKey, baseUrl: cfg.apiBase, clientIdentity: identity, timeoutMs: HTTP_TIMEOUT_MS, retry: { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 } });
|
|
156
|
+
this.texts = new kit.TextsCache({
|
|
157
|
+
client: this.api,
|
|
158
|
+
runtime: client.runtime,
|
|
159
|
+
filePath: textsCachePath(cfg.home),
|
|
160
|
+
onError: (err) => log.warn(err.message)
|
|
789
161
|
});
|
|
790
|
-
this.
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
runner: options.runner,
|
|
794
|
-
prompts: () => this.runPrompts(),
|
|
795
|
-
budgetMs: options.budgetMs,
|
|
796
|
-
onChange: () => this.writeStatus(),
|
|
797
|
-
trayHasWaiting: () => trayHasWaiting(this.api),
|
|
798
|
-
offeredInvites: OfferedInvites.load(cfg.home)
|
|
162
|
+
this.texts.onChange((texts, source) => {
|
|
163
|
+
log.info(`texts ${source === "server" ? "fetched" : "read from the cache"} for ${client.runtime} (texts v${texts.version}, manual ${texts.manual.version})`);
|
|
164
|
+
this.writeStatus();
|
|
799
165
|
});
|
|
800
|
-
this.
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
166
|
+
this.manual = options.manualPath === void 0 ? null : new kit.ManualSync({
|
|
167
|
+
texts: this.texts,
|
|
168
|
+
targetPath: options.manualPath,
|
|
169
|
+
fallback: MANUAL,
|
|
170
|
+
...options.manualFetch !== void 0 ? { fetch: options.manualFetch } : {},
|
|
171
|
+
onResult: (result) => {
|
|
172
|
+
const line = `manual: ${describeManualSync({ ...result, source: result.source === "fallback" ? "bundled" : result.source })}`;
|
|
173
|
+
if (result.upToDate === false || result.state === "failed") log.warn(line);
|
|
174
|
+
else if (result.written) log.info(line);
|
|
175
|
+
}
|
|
804
176
|
});
|
|
805
|
-
this.
|
|
806
|
-
|
|
177
|
+
this.realtime = options.realtime ?? new RealtimeClient({
|
|
178
|
+
apiKey: cfg.apiKey,
|
|
179
|
+
baseUrl: cfg.wsBase,
|
|
180
|
+
clientIdentity: identity,
|
|
181
|
+
ackOnReceipt: true,
|
|
182
|
+
reconnect: true,
|
|
183
|
+
capabilities: { heartbeat: true, rewake: true }
|
|
807
184
|
});
|
|
808
|
-
this.
|
|
809
|
-
|
|
185
|
+
this.realtime.on("state", (next) => {
|
|
186
|
+
const word = socketStateOf(next, this.socket);
|
|
187
|
+
if (word === this.socket) return;
|
|
188
|
+
this.socket = word;
|
|
189
|
+
if (word === "ready") {
|
|
810
190
|
beat(cfg.home);
|
|
811
191
|
this.lastError = null;
|
|
192
|
+
log.info(`socket ready (hello.ok) \u2014 acks ${this.realtime.ackNegotiated ? "on receipt" : "not negotiated by this server"}; ${this.realtime.capabilities.has("rewake") ? "the server re-wakes unanswered cards" : "this server does not re-wake unanswered cards"}`);
|
|
812
193
|
} else {
|
|
813
194
|
idle(cfg.home);
|
|
195
|
+
if (word === "reconnecting") log.info("socket reconnecting \u2014 the SDK backs off and retries; it never gives up");
|
|
814
196
|
}
|
|
815
197
|
this.writeStatus();
|
|
816
198
|
});
|
|
817
|
-
this.
|
|
818
|
-
this.lastError =
|
|
199
|
+
this.realtime.on("blocked", (info) => {
|
|
200
|
+
this.lastError = blockedDetail(info);
|
|
201
|
+
log.error(`socket blocked (auth): ${this.lastError}`);
|
|
819
202
|
this.writeStatus();
|
|
820
203
|
});
|
|
204
|
+
this.realtime.on("wake", (frame) => {
|
|
205
|
+
const payload = frame.payload ?? {};
|
|
206
|
+
if (payload.reason === "unanswered" && typeof payload.step === "number") this.lastUnansweredStep = payload.step;
|
|
207
|
+
});
|
|
208
|
+
this.loop = new kit.ReceiveLoop({
|
|
209
|
+
client: this.api,
|
|
210
|
+
// The kit's own switch: off, no invite is dismissed on the agent's behalf.
|
|
211
|
+
...options.dismissIgnoredInvites === false ? { dismissIgnoredInvites: false } : {},
|
|
212
|
+
texts: this.texts,
|
|
213
|
+
mode: "singleRun",
|
|
214
|
+
socket: this.realtime,
|
|
215
|
+
handle: cfg.handle,
|
|
216
|
+
startRun: (request) => this.startRun(request),
|
|
217
|
+
onEvent: (event) => this.onEvent(event),
|
|
218
|
+
...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
|
|
219
|
+
...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
|
|
220
|
+
...options.cycleTimeoutMs !== void 0 ? { cycleTimeoutMs: options.cycleTimeoutMs } : {},
|
|
221
|
+
...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {}
|
|
222
|
+
});
|
|
821
223
|
}
|
|
822
224
|
options;
|
|
823
225
|
api;
|
|
824
|
-
|
|
226
|
+
realtime;
|
|
825
227
|
texts;
|
|
826
228
|
manual;
|
|
827
|
-
|
|
229
|
+
loop;
|
|
828
230
|
heartbeatTimer = null;
|
|
829
231
|
statusTimer = null;
|
|
232
|
+
socket = "idle";
|
|
830
233
|
lastError = null;
|
|
831
234
|
stopping = false;
|
|
235
|
+
stopped = null;
|
|
236
|
+
invites = 0;
|
|
237
|
+
runsStarted = 0;
|
|
238
|
+
runsOk = 0;
|
|
239
|
+
runsFailed = 0;
|
|
240
|
+
runsTimedOut = 0;
|
|
241
|
+
runsNotStarted = 0;
|
|
242
|
+
runsSkippedEmpty = 0;
|
|
243
|
+
lastRun = null;
|
|
244
|
+
/** The newest wake since the last run started (for `RunRequest.wake`). */
|
|
245
|
+
pendingWake = null;
|
|
246
|
+
/** The rung of the newest `unanswered` wake frame (the kit's wake event does not carry it). */
|
|
247
|
+
lastUnansweredStep = null;
|
|
832
248
|
async start() {
|
|
833
|
-
const pre = await this.options.runner.preflight()
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
}
|
|
249
|
+
const pre = await withDeadline(this.options.runner.preflight(), PREFLIGHT_DEADLINE_MS, () => ({
|
|
250
|
+
ok: false,
|
|
251
|
+
detail: `preflight did not answer within ${Math.round(PREFLIGHT_DEADLINE_MS / 1e3)} s`
|
|
252
|
+
}));
|
|
253
|
+
if (!pre.ok) throw new Error(`runtime (${this.options.runner.name}) not ready: ${pre.detail ?? "unknown"}`);
|
|
837
254
|
log.info(
|
|
838
255
|
`integration up as @${this.options.cfg.handle} via ${this.options.runner.name} (${this.options.client.runtime} ${this.options.client.version}), profile ${this.options.profile}; fetching the served texts, then holding the socket`
|
|
839
256
|
);
|
|
840
257
|
await this.texts.start();
|
|
841
258
|
if (this.stopping) return;
|
|
842
|
-
this.
|
|
259
|
+
void this.manual?.start();
|
|
260
|
+
await this.loop.start();
|
|
843
261
|
this.heartbeatTimer = setInterval(() => {
|
|
844
|
-
if (this.
|
|
262
|
+
if (this.socket === "ready") beat(this.options.cfg.home);
|
|
845
263
|
}, HEARTBEAT_MS);
|
|
846
264
|
this.heartbeatTimer.unref();
|
|
847
265
|
this.statusTimer = setInterval(() => this.writeStatus(), STATUS_MS);
|
|
@@ -849,8 +267,8 @@ var Integration = class {
|
|
|
849
267
|
this.writeStatus();
|
|
850
268
|
}
|
|
851
269
|
/**
|
|
852
|
-
* Stop holding the socket and interrupt a run in flight (its
|
|
853
|
-
*
|
|
270
|
+
* Stop holding the socket and interrupt a run in flight (its signal aborts;
|
|
271
|
+
* the runner SIGTERMs its process group). `idle()` / `stopAndWait()`
|
|
854
272
|
* tell when the run has actually ended.
|
|
855
273
|
*/
|
|
856
274
|
stop() {
|
|
@@ -858,25 +276,20 @@ var Integration = class {
|
|
|
858
276
|
this.stopping = true;
|
|
859
277
|
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
860
278
|
if (this.statusTimer) clearInterval(this.statusTimer);
|
|
861
|
-
this.
|
|
279
|
+
this.stopped = this.loop.stop();
|
|
862
280
|
this.texts.stop();
|
|
863
281
|
this.manual?.stop();
|
|
864
|
-
this.
|
|
282
|
+
this.socket = "closed";
|
|
865
283
|
idle(this.options.cfg.home);
|
|
866
284
|
this.writeStatus();
|
|
867
285
|
}
|
|
868
|
-
/**
|
|
869
|
-
* `stop()`, then wait up to `graceMs` for the interrupted run to end. What a
|
|
870
|
-
* shutdown awaits before the process exits, so a launchd/systemd stop
|
|
871
|
-
* reaches the child and the restarted daemon does not find a run still
|
|
872
|
-
* going. Resolves true when nothing is running any more.
|
|
873
|
-
*/
|
|
286
|
+
/** `stop()`, then wait up to `graceMs` for the interrupted run to end. Resolves true when nothing runs any more. */
|
|
874
287
|
async stopAndWait(graceMs) {
|
|
875
288
|
this.stop();
|
|
876
289
|
let timer = null;
|
|
877
290
|
try {
|
|
878
291
|
return await Promise.race([
|
|
879
|
-
this.
|
|
292
|
+
(this.stopped ?? Promise.resolve()).then(() => true),
|
|
880
293
|
new Promise((resolve3) => {
|
|
881
294
|
timer = setTimeout(() => resolve3(false), graceMs);
|
|
882
295
|
})
|
|
@@ -885,13 +298,16 @@ var Integration = class {
|
|
|
885
298
|
if (timer !== null) clearTimeout(timer);
|
|
886
299
|
}
|
|
887
300
|
}
|
|
888
|
-
/**
|
|
889
|
-
|
|
890
|
-
return this.
|
|
301
|
+
/** Resolves when no cycle (and so no run) is running: the kit's `ReceiveLoop.idle()`. */
|
|
302
|
+
idle() {
|
|
303
|
+
return this.loop.idle();
|
|
304
|
+
}
|
|
305
|
+
/** A wake heard outside the socket (a test, a webhook the integration received). */
|
|
306
|
+
wake() {
|
|
307
|
+
this.loop.wake();
|
|
891
308
|
}
|
|
892
309
|
snapshot() {
|
|
893
|
-
const
|
|
894
|
-
const socket = this.stopping ? "closed" : this.connection.state;
|
|
310
|
+
const status = this.loop.status();
|
|
895
311
|
const texts = this.texts.current();
|
|
896
312
|
return {
|
|
897
313
|
version: 2,
|
|
@@ -900,68 +316,147 @@ var Integration = class {
|
|
|
900
316
|
runtime: this.options.runner.name,
|
|
901
317
|
handle: this.options.cfg.handle,
|
|
902
318
|
profile: this.options.profile,
|
|
903
|
-
socket,
|
|
904
|
-
wakes:
|
|
905
|
-
wakes_absorbed:
|
|
906
|
-
invites:
|
|
907
|
-
runs_started:
|
|
908
|
-
runs_ok:
|
|
909
|
-
runs_failed:
|
|
910
|
-
runs_timed_out:
|
|
911
|
-
runs_not_started:
|
|
912
|
-
runs_skipped_empty:
|
|
913
|
-
last_run:
|
|
914
|
-
|
|
915
|
-
|
|
319
|
+
socket: this.stopping ? "closed" : this.socket,
|
|
320
|
+
wakes: status.coalescer.wakes,
|
|
321
|
+
wakes_absorbed: status.coalescer.absorbed,
|
|
322
|
+
invites: this.invites,
|
|
323
|
+
runs_started: this.runsStarted,
|
|
324
|
+
runs_ok: this.runsOk,
|
|
325
|
+
runs_failed: this.runsFailed,
|
|
326
|
+
runs_timed_out: this.runsTimedOut,
|
|
327
|
+
runs_not_started: this.runsNotStarted,
|
|
328
|
+
runs_skipped_empty: this.runsSkippedEmpty,
|
|
329
|
+
last_run: this.lastRun,
|
|
330
|
+
// No local retry ladder (the server re-wakes, D3); kept for older readers.
|
|
331
|
+
retry_rung: 0,
|
|
332
|
+
retry_due_at: null,
|
|
916
333
|
last_error: this.lastError,
|
|
917
334
|
texts: {
|
|
918
335
|
source: this.texts.source,
|
|
919
336
|
fetched_at: this.texts.fetchedAt,
|
|
920
337
|
version: texts?.version ?? null,
|
|
921
338
|
manual_version: texts?.manual.version ?? null
|
|
922
|
-
}
|
|
339
|
+
},
|
|
340
|
+
capabilities: status.socket === null ? null : status.socket.capabilities,
|
|
341
|
+
intake_paused: status.socket === null ? null : status.socket.intakePaused,
|
|
342
|
+
recent_cycles: status.recentCycles.map((cycle) => ({
|
|
343
|
+
at: cycle.at,
|
|
344
|
+
outcome: cycle.outcome,
|
|
345
|
+
cards: cycle.cards,
|
|
346
|
+
invites: cycle.invites,
|
|
347
|
+
failure: cycle.failure === null ? null : cycle.failure.slice(0, CYCLE_FAILURE_CHARS)
|
|
348
|
+
}))
|
|
923
349
|
};
|
|
924
350
|
}
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
351
|
+
// ─── the one run ────────────────────────────────────────────────────────
|
|
352
|
+
async startRun(request) {
|
|
353
|
+
const kind = request.cards === 0 && (request.invites ?? 0) > 0 ? "invite" : "wake";
|
|
354
|
+
const wake = this.pendingWake ?? { reason: kind === "invite" ? "invite" : "messages" };
|
|
355
|
+
this.pendingWake = null;
|
|
356
|
+
const runId = crypto.randomUUID();
|
|
357
|
+
const startedAt = Date.now();
|
|
358
|
+
const budgetMs = this.options.budgetMs;
|
|
359
|
+
const slackMs = this.options.runnerDeadlineSlackMs ?? RUNNER_DEADLINE_SLACK_MS;
|
|
360
|
+
this.runsStarted += 1;
|
|
931
361
|
this.writeStatus();
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
}
|
|
939
|
-
/**
|
|
940
|
-
* The connect-time catch-up: one wake (the invoker counts the tray before
|
|
941
|
-
* any run, so an empty tray costs a count, not a run) and the pending invites.
|
|
942
|
-
*/
|
|
943
|
-
async catchUp() {
|
|
944
|
-
if (this.stopping) return;
|
|
945
|
-
log.info("wake \u2014 connect (a run starts only if the tray has something unread)");
|
|
946
|
-
this.invoker.wake("connect");
|
|
362
|
+
log.info(`run start kind=${kind} id=${runId} budget=${Math.round(budgetMs / 1e3)}s (tray: ${request.cards ?? "?"} card(s), ${request.invites ?? "?"} invite(s))`);
|
|
363
|
+
const controller = new AbortController();
|
|
364
|
+
const onAbort = () => controller.abort();
|
|
365
|
+
if (request.signal.aborted) controller.abort();
|
|
366
|
+
else request.signal.addEventListener("abort", onAbort, { once: true });
|
|
367
|
+
let outcome;
|
|
947
368
|
try {
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
369
|
+
outcome = await withDeadline(
|
|
370
|
+
this.options.runner.start({
|
|
371
|
+
kind,
|
|
372
|
+
wake,
|
|
373
|
+
prompt: `${request.prompt}
|
|
374
|
+
|
|
375
|
+
${this.options.manualPointer}`,
|
|
376
|
+
runId,
|
|
377
|
+
budgetMs,
|
|
378
|
+
signal: controller.signal
|
|
379
|
+
}),
|
|
380
|
+
budgetMs + slackMs,
|
|
381
|
+
() => {
|
|
382
|
+
controller.abort();
|
|
383
|
+
return {
|
|
384
|
+
state: "timed_out",
|
|
385
|
+
exitCode: null,
|
|
386
|
+
durationMs: Date.now() - startedAt,
|
|
387
|
+
detail: `the runner did not return within ${Math.round((budgetMs + slackMs) / 1e3)} s (budget plus ${Math.round(slackMs / 1e3)} s) \u2014 abandoned so the next wake can run`
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
);
|
|
961
391
|
} catch (err) {
|
|
962
|
-
|
|
392
|
+
outcome = { state: "not_started", exitCode: null, durationMs: Date.now() - startedAt, detail: `runner threw: ${err instanceof Error ? err.message : String(err)}` };
|
|
393
|
+
} finally {
|
|
394
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
395
|
+
}
|
|
396
|
+
this.lastRun = {
|
|
397
|
+
kind,
|
|
398
|
+
started_at: new Date(startedAt).toISOString(),
|
|
399
|
+
ended_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
400
|
+
state: outcome.state,
|
|
401
|
+
exit_code: outcome.exitCode,
|
|
402
|
+
duration_ms: outcome.durationMs,
|
|
403
|
+
detail: outcome.detail ?? null
|
|
404
|
+
};
|
|
405
|
+
switch (outcome.state) {
|
|
406
|
+
case "ok":
|
|
407
|
+
this.runsOk += 1;
|
|
408
|
+
log.info(`run ok kind=${kind} id=${runId} ${Math.round(outcome.durationMs / 1e3)}s (output discarded; any send was the agent's own hosted-tool call)`);
|
|
409
|
+
break;
|
|
410
|
+
case "failed":
|
|
411
|
+
this.runsFailed += 1;
|
|
412
|
+
break;
|
|
413
|
+
case "timed_out":
|
|
414
|
+
this.runsTimedOut += 1;
|
|
415
|
+
break;
|
|
416
|
+
case "not_started":
|
|
417
|
+
this.runsNotStarted += 1;
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
if (outcome.state !== "ok") {
|
|
421
|
+
log.warn(`run ${outcome.state} kind=${kind} id=${runId}${outcome.detail ? `: ${outcome.detail}` : ""} \u2014 the cards stay on the tray; the next wake (or the server's re-wake) finds them`);
|
|
963
422
|
}
|
|
964
423
|
this.writeStatus();
|
|
424
|
+
return outcome.state === "ok" ? { status: "completed" } : { status: outcome.state === "not_started" ? "not_started" : "failed", ...outcome.detail !== void 0 ? { detail: outcome.detail } : {} };
|
|
425
|
+
}
|
|
426
|
+
onEvent(event) {
|
|
427
|
+
switch (event.type) {
|
|
428
|
+
case "wake": {
|
|
429
|
+
if (event.source === "invite") this.invites += 1;
|
|
430
|
+
const reason = reasonOf(event.source, event.reason);
|
|
431
|
+
if (reason !== null) {
|
|
432
|
+
this.pendingWake = reason === "unanswered" && this.lastUnansweredStep !== null ? { reason, step: this.lastUnansweredStep } : { reason };
|
|
433
|
+
}
|
|
434
|
+
log.info(`wake \u2014 ${event.source}${event.reason ? ` (${event.reason})` : ""}${event.conversationId ? ` conv=${event.conversationId}` : ""}`);
|
|
435
|
+
break;
|
|
436
|
+
}
|
|
437
|
+
case "echo":
|
|
438
|
+
log.debug(`own echo${event.conversationId ? ` in ${event.conversationId}` : ""} \u2014 not a wake`);
|
|
439
|
+
break;
|
|
440
|
+
case "cycle": {
|
|
441
|
+
const { outcome, cards, invites } = event.summary;
|
|
442
|
+
if (outcome === "empty" || outcome === "nothing_owed") {
|
|
443
|
+
this.runsSkippedEmpty += 1;
|
|
444
|
+
log.info(`wake: ${outcome === "empty" ? "the tray is empty" : "nothing owed (muted cards only)"} \u2014 no run (${cards} card(s), ${invites} invite(s))`);
|
|
445
|
+
} else if (outcome === "abandoned") {
|
|
446
|
+
log.warn(`wake cycle abandoned by the watchdog: ${event.summary.failure ?? "it ran past its deadline"} \u2014 the next wake starts a new one`);
|
|
447
|
+
} else if (outcome === "texts_missing") {
|
|
448
|
+
this.runsNotStarted += 1;
|
|
449
|
+
log.warn("no served texts in hand: GET /v1/texts has not answered yet and nothing is cached in the identity home \u2014 no run this time");
|
|
450
|
+
}
|
|
451
|
+
this.writeStatus();
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
case "error":
|
|
455
|
+
if (!this.stopping) log.warn(`receive loop: ${event.error.message}`);
|
|
456
|
+
break;
|
|
457
|
+
default:
|
|
458
|
+
break;
|
|
459
|
+
}
|
|
965
460
|
}
|
|
966
461
|
writeStatus() {
|
|
967
462
|
writeIntegrationStatus(this.options.cfg.home, this.snapshot());
|
|
@@ -976,12 +471,12 @@ var SHUTDOWN_GRACE_MS = 1e4;
|
|
|
976
471
|
var MAX_LOG_BYTES = 5 * 1024 * 1024;
|
|
977
472
|
var KEEP_LOG_BYTES = 1024 * 1024;
|
|
978
473
|
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
979
|
-
function fingerprint(home) {
|
|
980
|
-
const id = resolveIdentity(home);
|
|
474
|
+
function fingerprint(home, envKey) {
|
|
475
|
+
const id = resolveIdentity(home, { envKey });
|
|
981
476
|
return id === null ? null : `${id.apiKey}:${id.handle ?? ""}`;
|
|
982
477
|
}
|
|
983
478
|
function boundDaemonLog(home) {
|
|
984
|
-
const file =
|
|
479
|
+
const file = path2.join(home, "daemon.log");
|
|
985
480
|
try {
|
|
986
481
|
const size = fs.statSync(file).size;
|
|
987
482
|
if (size <= MAX_LOG_BYTES) return;
|
|
@@ -1001,8 +496,8 @@ ${keep.toString("utf-8")}`
|
|
|
1001
496
|
}
|
|
1002
497
|
}
|
|
1003
498
|
async function runIntegration(opts) {
|
|
1004
|
-
const home =
|
|
1005
|
-
const workdir =
|
|
499
|
+
const home = path2.resolve(opts.home);
|
|
500
|
+
const workdir = path2.resolve(opts.workdir);
|
|
1006
501
|
const env = opts.env ?? process.env;
|
|
1007
502
|
const profile = opts.profile ?? resolveRunProfile(env);
|
|
1008
503
|
const budgetMs = opts.budgetMs ?? resolveRunBudgetMs(env);
|
|
@@ -1010,6 +505,8 @@ async function runIntegration(opts) {
|
|
|
1010
505
|
if (process.env["AGENTCHAT_LOG_LEVEL"] === void 0) process.env["AGENTCHAT_LOG_LEVEL"] = "info";
|
|
1011
506
|
const lock = acquireLeaderLock(home);
|
|
1012
507
|
if (lock === null) return 1;
|
|
508
|
+
const envKey = opts.credentialsFromHomeOnly !== true;
|
|
509
|
+
const identityOf = () => resolveIdentity(home, { envKey });
|
|
1013
510
|
const disabledBy = integrationDisabledBy(env);
|
|
1014
511
|
const disabled = disabledBy !== null;
|
|
1015
512
|
let live = null;
|
|
@@ -1077,33 +574,38 @@ async function runIntegration(opts) {
|
|
|
1077
574
|
log.info(`integration resident for ${home} (${credentialsPath(home)}) \u2014 ${opts.client.runtime} ${opts.client.version}`);
|
|
1078
575
|
if (disabled) {
|
|
1079
576
|
log.info(`${disabledBy}=off \u2014 holding no socket and starting no run; the hosted tools and the manual still work in every session`);
|
|
577
|
+
if (disabledBy === INTEGRATION_ENV_LEGACY) {
|
|
578
|
+
log.warn(`${INTEGRATION_ENV_LEGACY} is the old name of ${INTEGRATION_ENV} (agent contract v1 schedules its removal for ${INTEGRATION_ENV_LEGACY_REMOVAL}); set ${INTEGRATION_ENV}=off instead`);
|
|
579
|
+
}
|
|
1080
580
|
}
|
|
1081
581
|
idle(home);
|
|
1082
582
|
offStatus(null);
|
|
1083
583
|
for (; ; ) {
|
|
1084
584
|
if (shuttingDown || opts.signal?.aborted) break;
|
|
1085
|
-
const fp = fingerprint(home);
|
|
585
|
+
const fp = fingerprint(home, envKey);
|
|
1086
586
|
const identityChanged = fp !== observedFingerprint;
|
|
1087
587
|
if (identityChanged) {
|
|
1088
588
|
disconnect(fp === null ? "signed out" : "identity changed");
|
|
1089
589
|
observedFingerprint = fp;
|
|
1090
590
|
failures = 0;
|
|
1091
591
|
lastFailure = null;
|
|
1092
|
-
if (fp === null || disabled) offStatus(fp === null ? null :
|
|
592
|
+
if (fp === null || disabled) offStatus(fp === null ? null : identityOf()?.handle ?? null);
|
|
1093
593
|
}
|
|
1094
594
|
if (fp === null) {
|
|
1095
595
|
} else if (disabled) {
|
|
1096
596
|
} else if (fp !== liveFingerprint) {
|
|
1097
597
|
try {
|
|
1098
|
-
const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client });
|
|
598
|
+
const cfg = await resolveDaemonConfig({ home, workdir, client: opts.client, envKey });
|
|
599
|
+
const runner = isRunnerFactory(opts.runner) ? opts.runner.create(cfg) : opts.runner;
|
|
1099
600
|
const candidate = new Integration({
|
|
1100
601
|
cfg,
|
|
1101
|
-
runner
|
|
602
|
+
runner,
|
|
1102
603
|
client: opts.client,
|
|
1103
604
|
manualPointer: opts.manualPointer,
|
|
1104
605
|
...opts.manualPath !== void 0 ? { manualPath: opts.manualPath } : {},
|
|
1105
606
|
profile,
|
|
1106
|
-
budgetMs
|
|
607
|
+
budgetMs,
|
|
608
|
+
...opts.dismissIgnoredInvites !== void 0 ? { dismissIgnoredInvites: opts.dismissIgnoredInvites } : {}
|
|
1107
609
|
});
|
|
1108
610
|
await candidate.start();
|
|
1109
611
|
live = candidate;
|
|
@@ -1115,7 +617,7 @@ async function runIntegration(opts) {
|
|
|
1115
617
|
if (msg !== lastFailure) {
|
|
1116
618
|
log.warn(`not connecting yet: ${msg}`);
|
|
1117
619
|
lastFailure = msg;
|
|
1118
|
-
offStatus(
|
|
620
|
+
offStatus(identityOf()?.handle ?? null);
|
|
1119
621
|
}
|
|
1120
622
|
failures += 1;
|
|
1121
623
|
live = null;
|
|
@@ -1145,158 +647,19 @@ async function runIntegration(opts) {
|
|
|
1145
647
|
}
|
|
1146
648
|
return 0;
|
|
1147
649
|
}
|
|
1148
|
-
|
|
1149
|
-
// src/integration/spawn-run.ts
|
|
1150
|
-
var DEFAULT_GRACE_MS = 5e3;
|
|
1151
|
-
var STDERR_TAIL_CHARS = 400;
|
|
1152
|
-
function redactDiagnostic(value, max = STDERR_TAIL_CHARS) {
|
|
1153
|
-
return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, "").replace(/\b(api[_ -]?key\s*[:=]\s*)\S+/gi, "$1[redacted]").replace(/\b(Bearer)\s+[A-Za-z0-9._~-]{8,}\b/gi, "$1 [redacted]").replace(/\bac_[A-Za-z0-9_-]{8,}\b/g, "[redacted AgentChat key]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "[redacted key]").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").replace(/\s+/g, " ").trim().slice(-max);
|
|
1154
|
-
}
|
|
1155
|
-
function killProcessTree(child, signal) {
|
|
1156
|
-
if (child.pid === void 0) return;
|
|
1157
|
-
try {
|
|
1158
|
-
if (process.platform === "win32") {
|
|
1159
|
-
spawnCommandSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
1160
|
-
windowsHide: true,
|
|
1161
|
-
stdio: "ignore"
|
|
1162
|
-
});
|
|
1163
|
-
} else {
|
|
1164
|
-
process.kill(-child.pid, signal);
|
|
1165
|
-
}
|
|
1166
|
-
} catch {
|
|
1167
|
-
try {
|
|
1168
|
-
child.kill(signal);
|
|
1169
|
-
} catch {
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
}
|
|
1173
|
-
function spawnRun(spec) {
|
|
1174
|
-
const started = Date.now();
|
|
1175
|
-
return new Promise((resolve3) => {
|
|
1176
|
-
let settled = false;
|
|
1177
|
-
let stdoutBytes = 0;
|
|
1178
|
-
let stderrTail = "";
|
|
1179
|
-
let timedOut = false;
|
|
1180
|
-
let interrupted = false;
|
|
1181
|
-
let killTimer = null;
|
|
1182
|
-
let graceTimer = null;
|
|
1183
|
-
let onAbort = null;
|
|
1184
|
-
const finish = (outcome) => {
|
|
1185
|
-
if (settled) return;
|
|
1186
|
-
settled = true;
|
|
1187
|
-
if (killTimer) clearTimeout(killTimer);
|
|
1188
|
-
if (graceTimer) clearTimeout(graceTimer);
|
|
1189
|
-
if (onAbort) spec.signal?.removeEventListener("abort", onAbort);
|
|
1190
|
-
resolve3({ ...outcome, durationMs: Date.now() - started });
|
|
1191
|
-
};
|
|
1192
|
-
if (spec.signal?.aborted) {
|
|
1193
|
-
finish({ state: "not_started", exitCode: null, detail: "interrupted before the runtime was started" });
|
|
1194
|
-
return;
|
|
1195
|
-
}
|
|
1196
|
-
let child;
|
|
1197
|
-
try {
|
|
1198
|
-
child = spawnCommand(spec.command, [...spec.args], {
|
|
1199
|
-
cwd: spec.cwd,
|
|
1200
|
-
env: spec.env,
|
|
1201
|
-
stdio: [spec.stdin === null ? "ignore" : "pipe", "pipe", "pipe"],
|
|
1202
|
-
detached: process.platform !== "win32",
|
|
1203
|
-
windowsHide: true
|
|
1204
|
-
});
|
|
1205
|
-
} catch (err) {
|
|
1206
|
-
finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
|
|
1207
|
-
return;
|
|
1208
|
-
}
|
|
1209
|
-
if (spec.onStarted) {
|
|
1210
|
-
const onStarted = spec.onStarted;
|
|
1211
|
-
child.once("spawn", () => {
|
|
1212
|
-
try {
|
|
1213
|
-
onStarted();
|
|
1214
|
-
} catch {
|
|
1215
|
-
}
|
|
1216
|
-
});
|
|
1217
|
-
}
|
|
1218
|
-
child.stdout?.on("data", (chunk) => {
|
|
1219
|
-
stdoutBytes += chunk.length;
|
|
1220
|
-
});
|
|
1221
|
-
child.stderr?.on("data", (chunk) => {
|
|
1222
|
-
stderrTail = (stderrTail + String(chunk)).slice(-4 * STDERR_TAIL_CHARS);
|
|
1223
|
-
});
|
|
1224
|
-
if (spec.stdin !== null && child.stdin) {
|
|
1225
|
-
child.stdin.on("error", () => {
|
|
1226
|
-
});
|
|
1227
|
-
try {
|
|
1228
|
-
child.stdin.write(spec.stdin);
|
|
1229
|
-
child.stdin.end();
|
|
1230
|
-
} catch {
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
const terminate = () => {
|
|
1234
|
-
killProcessTree(child, "SIGTERM");
|
|
1235
|
-
if (graceTimer) clearTimeout(graceTimer);
|
|
1236
|
-
graceTimer = setTimeout(() => killProcessTree(child, "SIGKILL"), spec.graceMs ?? DEFAULT_GRACE_MS);
|
|
1237
|
-
};
|
|
1238
|
-
killTimer = setTimeout(() => {
|
|
1239
|
-
timedOut = true;
|
|
1240
|
-
terminate();
|
|
1241
|
-
}, spec.budgetMs);
|
|
1242
|
-
if (spec.signal) {
|
|
1243
|
-
onAbort = () => {
|
|
1244
|
-
if (settled) return;
|
|
1245
|
-
interrupted = true;
|
|
1246
|
-
terminate();
|
|
1247
|
-
};
|
|
1248
|
-
spec.signal.addEventListener("abort", onAbort, { once: true });
|
|
1249
|
-
}
|
|
1250
|
-
child.on("error", (err) => {
|
|
1251
|
-
finish({ state: "not_started", exitCode: null, detail: redactDiagnostic(String(err)) });
|
|
1252
|
-
});
|
|
1253
|
-
child.on("close", (code, signal) => {
|
|
1254
|
-
const tail = redactDiagnostic(stderrTail);
|
|
1255
|
-
if (timedOut) {
|
|
1256
|
-
finish({
|
|
1257
|
-
state: "timed_out",
|
|
1258
|
-
exitCode: code,
|
|
1259
|
-
detail: `run exceeded its ${Math.round(spec.budgetMs / 1e3)} s budget and was killed${tail ? `: ${tail}` : ""}`
|
|
1260
|
-
});
|
|
1261
|
-
return;
|
|
1262
|
-
}
|
|
1263
|
-
if (interrupted) {
|
|
1264
|
-
finish({
|
|
1265
|
-
state: "failed",
|
|
1266
|
-
exitCode: code,
|
|
1267
|
-
detail: `interrupted \u2014 the integration was stopping; the tray stays unread for the next run${tail ? `: ${tail}` : ""}`
|
|
1268
|
-
});
|
|
1269
|
-
return;
|
|
1270
|
-
}
|
|
1271
|
-
if (code === 0) {
|
|
1272
|
-
finish({ state: "ok", exitCode: 0 });
|
|
1273
|
-
return;
|
|
1274
|
-
}
|
|
1275
|
-
const exit = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
|
|
1276
|
-
if (stdoutBytes === 0) {
|
|
1277
|
-
finish({ state: "not_started", exitCode: code, detail: `${exit} with nothing on stdout${tail ? `: ${tail}` : ""}` });
|
|
1278
|
-
return;
|
|
1279
|
-
}
|
|
1280
|
-
finish({ state: "failed", exitCode: code, detail: `${exit}${tail ? `: ${tail}` : ""}` });
|
|
1281
|
-
});
|
|
1282
|
-
});
|
|
1283
|
-
}
|
|
1284
650
|
export {
|
|
1285
|
-
DEFAULT_WAKE_DEBOUNCE_MS,
|
|
1286
651
|
Integration,
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
RETRY_LADDER_MS,
|
|
1293
|
-
WakeCoalescer,
|
|
1294
|
-
offeredInvitesPath,
|
|
652
|
+
PREFLIGHT_DEADLINE_MS,
|
|
653
|
+
RUNNER_DEADLINE_SLACK_MS,
|
|
654
|
+
WINDOWS_SWEEP_TIMEOUT_MS,
|
|
655
|
+
blockedDetail,
|
|
656
|
+
describeWindowsSweep,
|
|
1295
657
|
redactDiagnostic,
|
|
1296
658
|
resolveDaemonConfig,
|
|
1297
659
|
runIntegration,
|
|
1298
660
|
socketStateOf,
|
|
1299
661
|
spawnRun,
|
|
662
|
+
sweepWindowsDescendants,
|
|
1300
663
|
wsBaseFor,
|
|
1301
664
|
wsUrlFor
|
|
1302
665
|
};
|