@agentchatme/openclaw 0.9.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +35 -26
- package/RUNBOOK.md +49 -17
- package/SECURITY.md +6 -2
- package/dist/binding/agents-anchor.cjs +10 -43
- package/dist/binding/agents-anchor.cjs.map +1 -1
- package/dist/binding/agents-anchor.d.cts +14 -11
- package/dist/binding/agents-anchor.d.ts +14 -11
- package/dist/binding/agents-anchor.js +10 -43
- package/dist/binding/agents-anchor.js.map +1 -1
- package/dist/index.cjs +1569 -1371
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +668 -192
- package/dist/index.d.ts +668 -192
- package/dist/index.js +1568 -1371
- package/dist/index.js.map +1 -1
- package/dist/setup-entry-C9aFZx3n.d.cts +378 -0
- package/dist/setup-entry-C9aFZx3n.d.ts +378 -0
- package/dist/setup-entry.cjs +1557 -1363
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +1 -1
- package/dist/setup-entry.d.ts +1 -1
- package/dist/setup-entry.js +1564 -1370
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +3 -3
- package/dist/setup-entry-sXnwmV8K.d.cts +0 -773
- package/dist/setup-entry-sXnwmV8K.d.ts +0 -773
package/dist/index.cjs
CHANGED
|
@@ -5,15 +5,16 @@ Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
5
5
|
var channelCore = require('openclaw/plugin-sdk/channel-core');
|
|
6
6
|
var channelPluginCommon = require('openclaw/plugin-sdk/channel-plugin-common');
|
|
7
7
|
var setup = require('openclaw/plugin-sdk/setup');
|
|
8
|
+
var agentchatme = require('agentchatme');
|
|
8
9
|
var readEnv_js$1 = require('./credentials/read-env.cjs');
|
|
9
10
|
var fs = require('fs');
|
|
10
11
|
var path2 = require('path');
|
|
11
12
|
var readEnv_js = require('./credentials/read-env.cjs');
|
|
12
13
|
var openclawLayout_js = require('./openclaw-layout.cjs');
|
|
13
14
|
var agentsAnchor_js = require('./binding/agents-anchor.cjs');
|
|
14
|
-
var agentchatme = require('agentchatme');
|
|
15
15
|
var zod = require('zod');
|
|
16
16
|
var pino = require('pino');
|
|
17
|
+
var async_hooks = require('async_hooks');
|
|
17
18
|
|
|
18
19
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
19
20
|
|
|
@@ -52,9 +53,9 @@ function readChannelSection(cfg) {
|
|
|
52
53
|
}
|
|
53
54
|
function readAccountRaw(section, accountId) {
|
|
54
55
|
if (!section) return void 0;
|
|
55
|
-
const { accounts } = section;
|
|
56
|
-
if (
|
|
57
|
-
const entry =
|
|
56
|
+
const { accounts: accounts2 } = section;
|
|
57
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
58
|
+
const entry = accounts2[accountId];
|
|
58
59
|
if (entry && typeof entry === "object") return entry;
|
|
59
60
|
}
|
|
60
61
|
if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {
|
|
@@ -79,8 +80,8 @@ function agentchatEnabledConfigPath(cfg, accountId) {
|
|
|
79
80
|
const section = readChannelSection(cfg);
|
|
80
81
|
const sectionPath = `channels.${AGENTCHAT_CHANNEL_ID}.enabled`;
|
|
81
82
|
if (!section || section.enabled === false) return sectionPath;
|
|
82
|
-
const { accounts } = section;
|
|
83
|
-
const entry =
|
|
83
|
+
const { accounts: accounts2 } = section;
|
|
84
|
+
const entry = accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2) ? accounts2[accountId] : void 0;
|
|
84
85
|
if (entry && typeof entry === "object") return `channels.${AGENTCHAT_CHANNEL_ID}.accounts.${accountId}.enabled`;
|
|
85
86
|
return sectionPath;
|
|
86
87
|
}
|
|
@@ -90,9 +91,9 @@ function agentchatReenableHint(cfg, accountId) {
|
|
|
90
91
|
function listConfiguredAccountIds(cfg) {
|
|
91
92
|
const section = readChannelSection(cfg);
|
|
92
93
|
if (!section) return [];
|
|
93
|
-
const { accounts } = section;
|
|
94
|
-
if (
|
|
95
|
-
const ids = Object.keys(
|
|
94
|
+
const { accounts: accounts2 } = section;
|
|
95
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
96
|
+
const ids = Object.keys(accounts2);
|
|
96
97
|
if (ids.length > 0) return ids;
|
|
97
98
|
}
|
|
98
99
|
return typeof section.apiKey === "string" ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : [];
|
|
@@ -121,12 +122,12 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
|
|
|
121
122
|
if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {
|
|
122
123
|
Object.assign(section, patch);
|
|
123
124
|
} else {
|
|
124
|
-
const
|
|
125
|
+
const accounts2 = {
|
|
125
126
|
...section.accounts ?? {}
|
|
126
127
|
};
|
|
127
|
-
const prevAccount = typeof
|
|
128
|
-
|
|
129
|
-
section.accounts =
|
|
128
|
+
const prevAccount = typeof accounts2[accountId] === "object" && accounts2[accountId] !== null ? accounts2[accountId] : {};
|
|
129
|
+
accounts2[accountId] = { ...prevAccount, ...patch };
|
|
130
|
+
section.accounts = accounts2;
|
|
130
131
|
}
|
|
131
132
|
channels[AGENTCHAT_CHANNEL_ID] = section;
|
|
132
133
|
return { ...cfg ?? {}, channels };
|
|
@@ -147,7 +148,7 @@ var AgentChatChannelError = class extends Error {
|
|
|
147
148
|
};
|
|
148
149
|
|
|
149
150
|
// src/version.ts
|
|
150
|
-
var PACKAGE_VERSION = "0.
|
|
151
|
+
var PACKAGE_VERSION = "0.10.0";
|
|
151
152
|
|
|
152
153
|
// src/client-identity.ts
|
|
153
154
|
var AGENTCHAT_CLIENT_NAME = "openclaw";
|
|
@@ -155,10 +156,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
|
|
|
155
156
|
name: AGENTCHAT_CLIENT_NAME,
|
|
156
157
|
version: PACKAGE_VERSION
|
|
157
158
|
};
|
|
158
|
-
var AGENTCHAT_CLIENT_HEADERS = {
|
|
159
|
-
"X-AgentChat-Client": AGENTCHAT_CLIENT_NAME,
|
|
160
|
-
"X-AgentChat-Client-Version": PACKAGE_VERSION
|
|
161
|
-
};
|
|
162
159
|
|
|
163
160
|
// src/setup-client.ts
|
|
164
161
|
var DEFAULT_API_BASE = "https://api.agentchat.me";
|
|
@@ -167,63 +164,37 @@ async function validateApiKey(apiKey, opts = {}) {
|
|
|
167
164
|
if (!apiKey || typeof apiKey !== "string") {
|
|
168
165
|
return { ok: false, reason: "unauthorized", message: "API key is empty" };
|
|
169
166
|
}
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
167
|
+
const client = new agentchatme.AgentChatClient({
|
|
168
|
+
apiKey,
|
|
169
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
170
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
171
|
+
timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
172
|
+
retry: ONE_ATTEMPT,
|
|
173
|
+
...opts.fetch ? { fetch: opts.fetch } : {}
|
|
174
|
+
});
|
|
175
|
+
let me;
|
|
177
176
|
try {
|
|
178
|
-
|
|
179
|
-
method: "GET",
|
|
180
|
-
headers: {
|
|
181
|
-
Authorization: `Bearer ${apiKey}`,
|
|
182
|
-
Accept: "application/json",
|
|
183
|
-
...AGENTCHAT_CLIENT_HEADERS
|
|
184
|
-
},
|
|
185
|
-
signal: controller.signal
|
|
186
|
-
});
|
|
177
|
+
me = await client.getMe();
|
|
187
178
|
} catch (err) {
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
return { ok: false, reason: "
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
return { ok: false, reason: "forbidden", status: 403, message: "API key lacks permission to read /agents/me" };
|
|
203
|
-
}
|
|
204
|
-
if (res.status === 410) {
|
|
205
|
-
return { ok: false, reason: "deleted", status: 410, message: "Agent account has been deleted" };
|
|
206
|
-
}
|
|
207
|
-
if (res.status >= 500) {
|
|
208
|
-
return { ok: false, reason: "server-error", status: res.status, message: `AgentChat API returned ${res.status}` };
|
|
209
|
-
}
|
|
210
|
-
if (!res.ok) {
|
|
211
|
-
return {
|
|
212
|
-
ok: false,
|
|
213
|
-
reason: "server-error",
|
|
214
|
-
status: res.status,
|
|
215
|
-
message: `AgentChat API returned ${res.status}`
|
|
216
|
-
};
|
|
179
|
+
const failure = describeFailure(err);
|
|
180
|
+
if (failure.kind === "network") {
|
|
181
|
+
const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
|
|
182
|
+
return {
|
|
183
|
+
ok: false,
|
|
184
|
+
reason: unreachable ? "unreachable" : "network-error",
|
|
185
|
+
message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
const status = failure.status;
|
|
189
|
+
if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
|
|
190
|
+
if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
|
|
191
|
+
if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
|
|
192
|
+
return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
|
|
217
193
|
}
|
|
218
|
-
const body =
|
|
194
|
+
const body = asRecord(me);
|
|
219
195
|
const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
|
|
220
196
|
if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
|
|
221
|
-
return {
|
|
222
|
-
ok: false,
|
|
223
|
-
reason: "unexpected-shape",
|
|
224
|
-
status: res.status,
|
|
225
|
-
message: "AgentChat /agents/me returned an unrecognized shape"
|
|
226
|
-
};
|
|
197
|
+
return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
|
|
227
198
|
}
|
|
228
199
|
return {
|
|
229
200
|
ok: true,
|
|
@@ -236,139 +207,122 @@ async function validateApiKey(apiKey, opts = {}) {
|
|
|
236
207
|
};
|
|
237
208
|
}
|
|
238
209
|
async function registerAgentStart(input, opts = {}) {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
}
|
|
267
|
-
if (res.status === 429) {
|
|
268
|
-
return {
|
|
269
|
-
ok: false,
|
|
270
|
-
reason: "rate-limited",
|
|
271
|
-
message,
|
|
272
|
-
status: 429,
|
|
273
|
-
retryAfterSeconds: res.retryAfterSeconds
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
if (res.status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status: res.status };
|
|
277
|
-
return { ok: false, reason: "server-error", status: res.status, message };
|
|
210
|
+
let data;
|
|
211
|
+
try {
|
|
212
|
+
data = await agentchatme.AgentChatClient.register({
|
|
213
|
+
email: input.email,
|
|
214
|
+
handle: input.handle,
|
|
215
|
+
...input.displayName !== void 0 ? { display_name: input.displayName } : {},
|
|
216
|
+
...input.description !== void 0 ? { description: input.description } : {},
|
|
217
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
218
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
219
|
+
});
|
|
220
|
+
} catch (err) {
|
|
221
|
+
const failure = describeFailure(err);
|
|
222
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
223
|
+
const { status, code, message } = failure;
|
|
224
|
+
if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
|
|
225
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
226
|
+
if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
|
|
227
|
+
const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
228
|
+
if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
|
|
229
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
230
|
+
if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
|
|
231
|
+
return { ok: false, reason: "server-error", status, message };
|
|
232
|
+
}
|
|
233
|
+
const pendingId = asRecord(data)?.pending_id;
|
|
234
|
+
if (typeof pendingId !== "string") {
|
|
235
|
+
return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
|
|
236
|
+
}
|
|
237
|
+
return { ok: true, pendingId };
|
|
278
238
|
}
|
|
279
239
|
async function registerAgentVerify(input, opts = {}) {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
}
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
const code = typeof body.code === "string" ? body.code : "";
|
|
306
|
-
const message = typeof body.message === "string" ? body.message : `status ${res.status}`;
|
|
307
|
-
if (res.status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status: 400 };
|
|
308
|
-
if (res.status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status: 400 };
|
|
309
|
-
if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
|
|
310
|
-
if (res.status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status: 409 };
|
|
311
|
-
const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
312
|
-
if (emailPolicy) {
|
|
313
|
-
return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) };
|
|
314
|
-
}
|
|
315
|
-
if (res.status === 429) {
|
|
316
|
-
return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
|
|
240
|
+
let verified;
|
|
241
|
+
try {
|
|
242
|
+
verified = await agentchatme.AgentChatClient.verify(input.pendingId, input.code, {
|
|
243
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
244
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
245
|
+
});
|
|
246
|
+
} catch (err) {
|
|
247
|
+
const failure = describeFailure(err);
|
|
248
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
249
|
+
const { status, code, message } = failure;
|
|
250
|
+
if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
|
|
251
|
+
if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
|
|
252
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
253
|
+
if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
|
|
254
|
+
const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
255
|
+
if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
|
|
256
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
257
|
+
return { ok: false, reason: "server-error", status, message };
|
|
258
|
+
}
|
|
259
|
+
const agent = asRecord(verified.agent);
|
|
260
|
+
if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
|
|
261
|
+
return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
|
|
317
262
|
}
|
|
318
|
-
return {
|
|
263
|
+
return {
|
|
264
|
+
ok: true,
|
|
265
|
+
apiKey: verified.apiKey,
|
|
266
|
+
agent: {
|
|
267
|
+
handle: agent.handle,
|
|
268
|
+
displayName: typeof agent.display_name === "string" ? agent.display_name : null,
|
|
269
|
+
email: agent.email,
|
|
270
|
+
createdAt: agent.created_at
|
|
271
|
+
}
|
|
272
|
+
};
|
|
319
273
|
}
|
|
320
274
|
async function recoverAgentStart(input, opts = {}) {
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
const
|
|
338
|
-
if (
|
|
339
|
-
|
|
340
|
-
|
|
275
|
+
let data;
|
|
276
|
+
try {
|
|
277
|
+
data = await agentchatme.AgentChatClient.recover(input.email, {
|
|
278
|
+
handle: input.handle,
|
|
279
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
280
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
281
|
+
});
|
|
282
|
+
} catch (err) {
|
|
283
|
+
const failure = describeFailure(err);
|
|
284
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
285
|
+
const { status, code, message: message2 } = failure;
|
|
286
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
|
|
287
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
288
|
+
return { ok: false, reason: "server-error", status, message: message2 };
|
|
289
|
+
}
|
|
290
|
+
const body = asRecord(data);
|
|
291
|
+
const message = typeof body?.message === "string" ? body.message : "status 200";
|
|
292
|
+
if (typeof body?.pending_id !== "string") {
|
|
293
|
+
return {
|
|
294
|
+
ok: false,
|
|
295
|
+
reason: "unexpected-shape",
|
|
296
|
+
status: 200,
|
|
297
|
+
message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
|
|
298
|
+
};
|
|
341
299
|
}
|
|
342
|
-
return { ok:
|
|
300
|
+
return { ok: true, pendingId: body.pending_id, message };
|
|
343
301
|
}
|
|
344
302
|
async function recoverAgentVerify(input, opts = {}) {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
303
|
+
let recovered;
|
|
304
|
+
try {
|
|
305
|
+
recovered = await agentchatme.AgentChatClient.recoverVerify(input.pendingId, input.code, {
|
|
306
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
307
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
308
|
+
});
|
|
309
|
+
} catch (err) {
|
|
310
|
+
const failure = describeFailure(err);
|
|
311
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
312
|
+
const { status, code, message } = failure;
|
|
313
|
+
if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
|
|
314
|
+
if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
|
|
315
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
316
|
+
if (status === 409 && code === "HANDLE_REQUIRED") {
|
|
317
|
+
return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
|
|
357
318
|
}
|
|
358
|
-
return { ok:
|
|
319
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
320
|
+
return { ok: false, reason: "server-error", status, message };
|
|
359
321
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
if (res.status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status: 400 };
|
|
363
|
-
if (res.status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status: 400 };
|
|
364
|
-
if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
|
|
365
|
-
if (res.status === 409 && code === "HANDLE_REQUIRED") {
|
|
366
|
-
return { ok: false, reason: "handle-required", message, status: 409, handles: readHandleList(body.details) };
|
|
322
|
+
if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
|
|
323
|
+
return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
|
|
367
324
|
}
|
|
368
|
-
|
|
369
|
-
return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
|
|
370
|
-
}
|
|
371
|
-
return { ok: false, reason: "server-error", status: res.status, message };
|
|
325
|
+
return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
|
|
372
326
|
}
|
|
373
327
|
function classifyEmailPolicyRejection(code) {
|
|
374
328
|
if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
|
|
@@ -386,39 +340,34 @@ function readHandleList(details) {
|
|
|
386
340
|
if (!Array.isArray(handles)) return [];
|
|
387
341
|
return handles.filter((h) => typeof h === "string" && h.length > 0);
|
|
388
342
|
}
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
headers: {
|
|
400
|
-
"content-type": "application/json",
|
|
401
|
-
accept: "application/json",
|
|
402
|
-
...AGENTCHAT_CLIENT_HEADERS
|
|
403
|
-
},
|
|
404
|
-
body: JSON.stringify(body),
|
|
405
|
-
signal: controller.signal
|
|
406
|
-
});
|
|
407
|
-
const parsed = await res.json().catch(() => null);
|
|
408
|
-
const retryAfterHeader = res.headers.get("retry-after");
|
|
409
|
-
const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : void 0;
|
|
343
|
+
var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
|
|
344
|
+
function apiBaseOf(apiBase) {
|
|
345
|
+
return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
|
|
346
|
+
}
|
|
347
|
+
function describeFailure(err) {
|
|
348
|
+
if (err instanceof agentchatme.AgentChatError) {
|
|
349
|
+
const raw = asRecord(asRecord(err.details)?.body);
|
|
350
|
+
const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
|
|
351
|
+
const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
|
|
352
|
+
const retryAfterMs = err instanceof agentchatme.RateLimitedError ? err.retryAfterMs : null;
|
|
410
353
|
return {
|
|
411
354
|
kind: "http",
|
|
412
|
-
status:
|
|
413
|
-
|
|
414
|
-
|
|
355
|
+
status: err.status,
|
|
356
|
+
code,
|
|
357
|
+
message: message2,
|
|
358
|
+
details: raw ? raw.details : err.details,
|
|
359
|
+
...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
|
|
415
360
|
};
|
|
416
|
-
} catch (err) {
|
|
417
|
-
if (err instanceof Error && err.name === "AbortError") return { kind: "timeout" };
|
|
418
|
-
return { kind: "network", message: err instanceof Error ? err.message : String(err) };
|
|
419
|
-
} finally {
|
|
420
|
-
clearTimeout(timer);
|
|
421
361
|
}
|
|
362
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
363
|
+
const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
|
|
364
|
+
return { kind: "network", message, timedOut };
|
|
365
|
+
}
|
|
366
|
+
function networkMessage(failure) {
|
|
367
|
+
return failure.timedOut ? "request timed out" : failure.message;
|
|
368
|
+
}
|
|
369
|
+
function asRecord(value) {
|
|
370
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
422
371
|
}
|
|
423
372
|
async function assertApiKeyValid(apiKey, opts = {}) {
|
|
424
373
|
const result = await validateApiKey(apiKey, opts);
|
|
@@ -436,34 +385,20 @@ var MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
|
436
385
|
function mcpToolName(tool) {
|
|
437
386
|
return `${MCP_TOOL_PREFIX}${tool}`;
|
|
438
387
|
}
|
|
439
|
-
var DECIDE_TOOL = mcpToolName("agentchat_decide");
|
|
440
|
-
var GET_CONVERSATION_TOOL = mcpToolName("agentchat_get_conversation");
|
|
441
388
|
var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
|
|
442
389
|
var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
|
|
443
390
|
function spellToolsForOpenClaw(text) {
|
|
444
391
|
return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token));
|
|
445
392
|
}
|
|
446
|
-
function wakeTurnPrompt(texts, conversationId) {
|
|
447
|
-
const instruction = texts.wake_instruction.trim();
|
|
448
|
-
if (!conversationId) return instruction;
|
|
449
|
-
return `${instruction}
|
|
450
|
-
|
|
451
|
-
${conversationLine(conversationId)}`;
|
|
452
|
-
}
|
|
453
|
-
function conversationLine(conversationId) {
|
|
454
|
-
return `Conversation to answer in this turn: ${conversationId}. The gate decided reply; its card is still on the tray while you work, and the reply verdict for it is recorded for you when this turn completes unless you record one yourself with ${DECIDE_TOOL} (reply after your answer is sent, or dismiss if you read and choose not to answer) \u2014 open it with ${GET_CONVERSATION_TOOL} and reply.`;
|
|
455
|
-
}
|
|
456
|
-
function inviteTurnPrompt(texts) {
|
|
457
|
-
return texts.invite_prompt.trim();
|
|
458
|
-
}
|
|
459
393
|
function wakeSessionKey(agentId, now = Date.now(), nonce = randomNonce()) {
|
|
460
394
|
return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`;
|
|
461
395
|
}
|
|
462
|
-
function inviteSessionKey(agentId, inviteId) {
|
|
463
|
-
return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`;
|
|
396
|
+
function inviteSessionKey(agentId, inviteId, now = Date.now(), nonce = randomNonce()) {
|
|
397
|
+
return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}-${utcStamp(now)}-${nonce}`;
|
|
464
398
|
}
|
|
465
|
-
function integrationLane(accountId) {
|
|
466
|
-
|
|
399
|
+
function integrationLane(accountId, generation2 = 0) {
|
|
400
|
+
const base = `agentchat-integration:${sanitizeKeyPart(accountId)}`;
|
|
401
|
+
return generation2 > 0 ? `${base}:${generation2}` : base;
|
|
467
402
|
}
|
|
468
403
|
function utcStamp(ms) {
|
|
469
404
|
return new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
@@ -480,7 +415,6 @@ function sanitizeKeyPart(value) {
|
|
|
480
415
|
var MCP_PATH = "/mcp";
|
|
481
416
|
var AUTH_HEADER_TEMPLATE = `Bearer \${${readEnv_js.API_KEY_ENV}}`;
|
|
482
417
|
var DEFAULT_API_BASE2 = "https://api.agentchat.me";
|
|
483
|
-
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
484
418
|
function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
|
|
485
419
|
return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
|
|
486
420
|
}
|
|
@@ -549,67 +483,24 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
|
549
483
|
return { cfg: { ...cfg, mcp }, removed: true };
|
|
550
484
|
}
|
|
551
485
|
async function probeHostedMcp(params) {
|
|
552
|
-
const
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
capabilities: {},
|
|
571
|
-
clientInfo: { name: "@agentchatme/openclaw doctor", version: "0" }
|
|
572
|
-
}
|
|
573
|
-
}),
|
|
574
|
-
signal: controller.signal
|
|
575
|
-
});
|
|
576
|
-
if (!res.ok) {
|
|
577
|
-
return { ok: false, status: res.status, error: res.status === 401 ? "the key does not authenticate against the hosted MCP server" : `HTTP ${res.status}` };
|
|
578
|
-
}
|
|
579
|
-
const text = await res.text();
|
|
580
|
-
const result = readInitializeResult(text);
|
|
581
|
-
if (!result) return { ok: false, status: res.status, error: "no initialize result in the answer" };
|
|
582
|
-
const serverInfo = result.serverInfo ?? {};
|
|
583
|
-
return {
|
|
584
|
-
ok: true,
|
|
585
|
-
status: res.status,
|
|
586
|
-
serverName: typeof serverInfo.name === "string" ? serverInfo.name : void 0,
|
|
587
|
-
serverVersion: typeof serverInfo.version === "string" ? serverInfo.version : void 0,
|
|
588
|
-
protocolVersion: typeof result.protocolVersion === "string" ? result.protocolVersion : void 0,
|
|
589
|
-
hasInstructions: typeof result.instructions === "string" && result.instructions.trim().length > 0
|
|
590
|
-
};
|
|
591
|
-
} catch (err) {
|
|
592
|
-
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
593
|
-
} finally {
|
|
594
|
-
clearTimeout(timer);
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
function readInitializeResult(text) {
|
|
598
|
-
const candidates = [];
|
|
599
|
-
const trimmed = text.trim();
|
|
600
|
-
if (trimmed.startsWith("{")) candidates.push(trimmed);
|
|
601
|
-
for (const line of text.split(/\r?\n/)) {
|
|
602
|
-
if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
|
|
603
|
-
}
|
|
604
|
-
for (const candidate of candidates) {
|
|
605
|
-
try {
|
|
606
|
-
const parsed = JSON.parse(candidate);
|
|
607
|
-
const result = parsed.result;
|
|
608
|
-
if (result && typeof result === "object" && !Array.isArray(result)) return result;
|
|
609
|
-
} catch {
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
return null;
|
|
486
|
+
const result = await agentchatme.integration.probeHostedTools({
|
|
487
|
+
apiBase: params.apiBase ?? DEFAULT_API_BASE2,
|
|
488
|
+
apiKey: params.apiKey,
|
|
489
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
490
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
491
|
+
...params.fetch ? { fetch: params.fetch } : {}
|
|
492
|
+
});
|
|
493
|
+
const missing = result.missing ?? [];
|
|
494
|
+
return {
|
|
495
|
+
ok: result.ok,
|
|
496
|
+
...result.status !== void 0 ? { status: result.status } : {},
|
|
497
|
+
...result.serverName ? { serverName: result.serverName } : {},
|
|
498
|
+
...result.serverVersion ? { serverVersion: result.serverVersion } : {},
|
|
499
|
+
...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {},
|
|
500
|
+
...result.tools ? { tools: result.tools } : {},
|
|
501
|
+
...missing.length > 0 ? { missing } : {},
|
|
502
|
+
...result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(", ")} for this key` } : {}
|
|
503
|
+
};
|
|
613
504
|
}
|
|
614
505
|
|
|
615
506
|
// src/integration/runtime-holder.ts
|
|
@@ -629,11 +520,137 @@ function setPluginRuntime(runtime) {
|
|
|
629
520
|
function getPluginRuntime() {
|
|
630
521
|
return current;
|
|
631
522
|
}
|
|
523
|
+
|
|
524
|
+
// src/integration/run.ts
|
|
525
|
+
var DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 6e4;
|
|
526
|
+
var RUN_WAIT_RETRY_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
|
|
527
|
+
var MIN_WAIT_SPACING_MS = 1e3;
|
|
528
|
+
var TRANSCRIPT_READ_LIMIT = 200;
|
|
529
|
+
var METADATA_KEYS = ["endedAt", "stopReason", "livenessState", "pendingError", "timeoutPhase", "startedAt", "providerStarted"];
|
|
530
|
+
function runEndOf(wait, timing) {
|
|
531
|
+
const status = wait?.status;
|
|
532
|
+
const error = nonEmpty(wait?.error);
|
|
533
|
+
if (status === "ok") return { ended: true, status: "ok" };
|
|
534
|
+
if (status === "error") {
|
|
535
|
+
if (error && error.trim().toLowerCase() === "completed") return { ended: true, status: "ok" };
|
|
536
|
+
return { ended: true, status: "error", ...error ? { error } : {} };
|
|
537
|
+
}
|
|
538
|
+
if (status !== "timeout") {
|
|
539
|
+
return { ended: false };
|
|
540
|
+
}
|
|
541
|
+
const ended = { ended: true, status: "timeout", ...error ? { error } : {} };
|
|
542
|
+
const hasMetadata = wait !== null && wait !== void 0 && METADATA_KEYS.some((key) => key in wait);
|
|
543
|
+
if (!hasMetadata) {
|
|
544
|
+
return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false };
|
|
545
|
+
}
|
|
546
|
+
if (wait.pendingError === true) return { ended: false };
|
|
547
|
+
if (typeof wait.endedAt === "number" || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended;
|
|
548
|
+
if (isHardTimeout(wait)) return ended;
|
|
549
|
+
return error ? ended : { ended: false };
|
|
550
|
+
}
|
|
551
|
+
var HARD_TIMEOUT_PHASES = /* @__PURE__ */ new Set(["preflight", "provider", "tool_execution", "post_turn"]);
|
|
552
|
+
function isHardTimeout(wait) {
|
|
553
|
+
const phase = typeof wait.timeoutPhase === "string" ? wait.timeoutPhase.trim() : "";
|
|
554
|
+
if (HARD_TIMEOUT_PHASES.has(phase)) return true;
|
|
555
|
+
return wait.status === "timeout" && wait.providerStarted === true && nonEmpty(wait.stopReason) !== "restart";
|
|
556
|
+
}
|
|
557
|
+
async function watchRunUntilEnded(options) {
|
|
558
|
+
const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS;
|
|
559
|
+
const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS;
|
|
560
|
+
const now = options.now ?? Date.now;
|
|
561
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
562
|
+
const started = now();
|
|
563
|
+
let failures = 0;
|
|
564
|
+
for (; ; ) {
|
|
565
|
+
const runtime = options.runtime();
|
|
566
|
+
if (!runtime) return { ended: false, reason: "gone", elapsedMs: now() - started };
|
|
567
|
+
const waitStarted = now();
|
|
568
|
+
let observation;
|
|
569
|
+
try {
|
|
570
|
+
observation = await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs });
|
|
571
|
+
} catch (err) {
|
|
572
|
+
const message = describe(err);
|
|
573
|
+
const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 6e4;
|
|
574
|
+
failures += 1;
|
|
575
|
+
options.onWaitError?.(message, failures, delay);
|
|
576
|
+
await sleep(delay);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
failures = 0;
|
|
580
|
+
const elapsedMs = now() - waitStarted;
|
|
581
|
+
const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs });
|
|
582
|
+
if (end.ended) return { ...end, elapsedMs: now() - started };
|
|
583
|
+
options.onStillRunning?.(now() - started);
|
|
584
|
+
if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
function countAgentChatCalls(messages, runId) {
|
|
588
|
+
if (messages.length === 0) return null;
|
|
589
|
+
let recognised = false;
|
|
590
|
+
let made = 0;
|
|
591
|
+
let failed = 0;
|
|
592
|
+
for (const row of messages) {
|
|
593
|
+
const message = unwrapMessage(row);
|
|
594
|
+
if (!message) continue;
|
|
595
|
+
const role = message.role;
|
|
596
|
+
if (role === "assistant" || role === "user") recognised = true;
|
|
597
|
+
if (role !== "toolResult" && role !== "tool") continue;
|
|
598
|
+
recognised = true;
|
|
599
|
+
const meta = asRecord2(message.__openclaw);
|
|
600
|
+
if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
|
|
601
|
+
if (!isAgentChatToolResult(message)) continue;
|
|
602
|
+
made += 1;
|
|
603
|
+
if (message.isError === true) failed += 1;
|
|
604
|
+
}
|
|
605
|
+
return recognised ? { made, failed } : null;
|
|
606
|
+
}
|
|
607
|
+
async function readAgentChatCalls(runtime, sessionKey, runId) {
|
|
608
|
+
if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
|
|
609
|
+
try {
|
|
610
|
+
const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
|
|
611
|
+
const messages = result?.messages;
|
|
612
|
+
return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
|
|
613
|
+
} catch {
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
618
|
+
function isAgentChatToolResult(message) {
|
|
619
|
+
const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
|
|
620
|
+
if (toolName.startsWith(TOOL_PREFIX)) return true;
|
|
621
|
+
const tool = asRecord2(asRecord2(message.details)?.tool);
|
|
622
|
+
if (!tool) return false;
|
|
623
|
+
if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
|
|
624
|
+
if (tool.sourceName === MCP_SERVER_NAME) return true;
|
|
625
|
+
const mcp = asRecord2(tool.mcp);
|
|
626
|
+
return mcp?.serverName === MCP_SERVER_NAME;
|
|
627
|
+
}
|
|
628
|
+
function unwrapMessage(row) {
|
|
629
|
+
const record = asRecord2(row);
|
|
630
|
+
if (!record) return null;
|
|
631
|
+
if (typeof record.role === "string") return record;
|
|
632
|
+
const inner = asRecord2(record.message);
|
|
633
|
+
return inner && typeof inner.role === "string" ? inner : null;
|
|
634
|
+
}
|
|
635
|
+
function asRecord2(value) {
|
|
636
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
637
|
+
}
|
|
638
|
+
function nonEmpty(value) {
|
|
639
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
640
|
+
}
|
|
641
|
+
function describe(err) {
|
|
642
|
+
return err instanceof Error ? err.message : String(err);
|
|
643
|
+
}
|
|
644
|
+
function defaultSleep(ms) {
|
|
645
|
+
return new Promise((resolve) => {
|
|
646
|
+
const timer = setTimeout(resolve, ms);
|
|
647
|
+
timer.unref?.();
|
|
648
|
+
});
|
|
649
|
+
}
|
|
632
650
|
var DEFAULT_AGENT_ID = "main";
|
|
633
651
|
var GATE_TEMPERATURE = 0;
|
|
634
652
|
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
635
653
|
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
636
|
-
var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
|
|
637
654
|
var RuntimeUnavailableError = class extends Error {
|
|
638
655
|
constructor(what) {
|
|
639
656
|
super(`OpenClaw plugin runtime unavailable \u2014 ${what} needs setRuntime(...) from defineChannelPluginEntry`);
|
|
@@ -658,16 +675,21 @@ function createRuntimeModelCall(params) {
|
|
|
658
675
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
659
676
|
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
660
677
|
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
661
|
-
return async (prompt) => {
|
|
678
|
+
return async (prompt, options) => {
|
|
662
679
|
const runtime = getRuntime();
|
|
663
680
|
if (!runtime) throw new RuntimeUnavailableError("the gate call");
|
|
681
|
+
const signals = [
|
|
682
|
+
...Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : [],
|
|
683
|
+
...options?.signal ? [options.signal] : []
|
|
684
|
+
];
|
|
685
|
+
const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
664
686
|
const result = await runtime.llm.complete({
|
|
665
687
|
messages: [{ role: "user", content: prompt }],
|
|
666
688
|
maxTokens,
|
|
667
689
|
temperature: GATE_TEMPERATURE,
|
|
668
690
|
...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
|
|
669
691
|
purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
|
|
670
|
-
...
|
|
692
|
+
...signal ? { signal } : {}
|
|
671
693
|
});
|
|
672
694
|
return typeof result?.text === "string" ? result.text : "";
|
|
673
695
|
};
|
|
@@ -697,10 +719,14 @@ function resolveGateAgent(params) {
|
|
|
697
719
|
return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
|
|
698
720
|
}
|
|
699
721
|
function readLiveConfig(fallback, runtime = getPluginRuntime) {
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
if (
|
|
703
|
-
|
|
722
|
+
const config = runtime()?.config;
|
|
723
|
+
for (const read of [config?.current, config?.loadConfig]) {
|
|
724
|
+
if (typeof read !== "function") continue;
|
|
725
|
+
try {
|
|
726
|
+
const loaded = read.call(config);
|
|
727
|
+
if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
|
|
728
|
+
} catch {
|
|
729
|
+
}
|
|
704
730
|
}
|
|
705
731
|
return { cfg: fallback, live: false };
|
|
706
732
|
}
|
|
@@ -728,11 +754,11 @@ function turnReadiness(params) {
|
|
|
728
754
|
}
|
|
729
755
|
function createRuntimeTurnStarter(params = {}) {
|
|
730
756
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
731
|
-
const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
|
|
732
757
|
return async (request) => {
|
|
733
758
|
const runtime = getRuntime();
|
|
734
759
|
if (!runtime) return { ran: false, error: new RuntimeUnavailableError("the agent turn").message };
|
|
735
760
|
let runId;
|
|
761
|
+
let sessionKey = request.sessionKey;
|
|
736
762
|
try {
|
|
737
763
|
const admitted = await runtime.subagent.run({
|
|
738
764
|
sessionKey: request.sessionKey,
|
|
@@ -741,15 +767,46 @@ function createRuntimeTurnStarter(params = {}) {
|
|
|
741
767
|
deliver: false
|
|
742
768
|
});
|
|
743
769
|
runId = admitted.runId;
|
|
770
|
+
const accepted = admitted.sessionKey;
|
|
771
|
+
if (typeof accepted === "string" && accepted.trim().length > 0) sessionKey = accepted.trim();
|
|
744
772
|
} catch (err) {
|
|
745
773
|
return { ran: false, error: err instanceof Error ? err.message : String(err) };
|
|
746
774
|
}
|
|
747
|
-
const done =
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
775
|
+
const done = watchRunUntilEnded({
|
|
776
|
+
runtime: getRuntime,
|
|
777
|
+
runId,
|
|
778
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
779
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {},
|
|
780
|
+
...params.onWaitError ? { onWaitError: (error, attempt, retryInMs) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) } : {},
|
|
781
|
+
...params.now ? { now: params.now } : {},
|
|
782
|
+
...params.sleep ? { sleep: params.sleep } : {}
|
|
783
|
+
}).then(async (watched) => {
|
|
784
|
+
if (!watched.ended) return { ran: true, runId, status: "gone", elapsedMs: watched.elapsedMs };
|
|
785
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
786
|
+
return {
|
|
787
|
+
ran: true,
|
|
788
|
+
runId,
|
|
789
|
+
status: watched.status,
|
|
790
|
+
...watched.error ? { error: watched.error } : {},
|
|
791
|
+
agentchatCalls,
|
|
792
|
+
elapsedMs: watched.elapsedMs
|
|
793
|
+
};
|
|
794
|
+
});
|
|
795
|
+
return { ran: true, runId, sessionKey, done };
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
function createRunWatcher(params = {}) {
|
|
799
|
+
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
800
|
+
return async ({ runId, sessionKey }) => {
|
|
801
|
+
const watched = await watchRunUntilEnded({
|
|
802
|
+
runtime: getRuntime,
|
|
803
|
+
runId,
|
|
804
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
805
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}
|
|
806
|
+
});
|
|
807
|
+
if (!watched.ended) return null;
|
|
808
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
809
|
+
return { ran: true, runId, status: watched.status, ...watched.error ? { error: watched.error } : {}, agentchatCalls, elapsedMs: watched.elapsedMs };
|
|
753
810
|
};
|
|
754
811
|
}
|
|
755
812
|
var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
@@ -888,7 +945,7 @@ function restoreIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
888
945
|
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
|
|
889
946
|
return { outcome: "placed", path: written.path };
|
|
890
947
|
} catch (err) {
|
|
891
|
-
return { outcome: "failed", path: filePath, detail:
|
|
948
|
+
return { outcome: "failed", path: filePath, detail: describe2(err) };
|
|
892
949
|
}
|
|
893
950
|
}
|
|
894
951
|
function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
@@ -900,7 +957,7 @@ function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
900
957
|
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
|
|
901
958
|
return { outcome: "updated", path: written.path };
|
|
902
959
|
} catch (err) {
|
|
903
|
-
return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail:
|
|
960
|
+
return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail: describe2(err) };
|
|
904
961
|
}
|
|
905
962
|
}
|
|
906
963
|
function placeIntegration(params) {
|
|
@@ -914,7 +971,7 @@ function placeIntegration(params) {
|
|
|
914
971
|
detail: `${readEnv_js.API_KEY_ENV} in ${key.path}${key.changed ? ` (a gateway started before this needs a restart, or a config reload, to resolve \${${readEnv_js.API_KEY_ENV}})` : ""}`
|
|
915
972
|
});
|
|
916
973
|
} catch (err) {
|
|
917
|
-
steps.push({ name: "key", status: "failed", detail: `could not write ${readEnv_js.API_KEY_ENV} to the OpenClaw .env: ${
|
|
974
|
+
steps.push({ name: "key", status: "failed", detail: `could not write ${readEnv_js.API_KEY_ENV} to the OpenClaw .env: ${describe2(err)}` });
|
|
918
975
|
}
|
|
919
976
|
}
|
|
920
977
|
const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
|
|
@@ -930,7 +987,7 @@ function placeIntegration(params) {
|
|
|
930
987
|
const anchor = agentsAnchor_js.writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
|
|
931
988
|
steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
|
|
932
989
|
} catch (err) {
|
|
933
|
-
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${
|
|
990
|
+
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe2(err)}` });
|
|
934
991
|
}
|
|
935
992
|
}
|
|
936
993
|
steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
|
|
@@ -991,7 +1048,7 @@ function checkPlacement(params) {
|
|
|
991
1048
|
});
|
|
992
1049
|
return checks;
|
|
993
1050
|
}
|
|
994
|
-
function
|
|
1051
|
+
function describe2(err) {
|
|
995
1052
|
return err instanceof Error ? err.message : String(err);
|
|
996
1053
|
}
|
|
997
1054
|
var PLUGIN_STATE_DIRNAME = "agentchat";
|
|
@@ -1002,236 +1059,115 @@ function safeSegment(value) {
|
|
|
1002
1059
|
function integrationStateDir(accountId, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
1003
1060
|
return path2__namespace.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
|
|
1004
1061
|
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1062
|
+
var OLD_INVITE_LEDGER_FILE = "invites.json";
|
|
1063
|
+
function removeOldStateFiles(accountId, stateDir) {
|
|
1064
|
+
const dir = integrationStateDir(accountId, stateDir);
|
|
1065
|
+
const removed = [];
|
|
1066
|
+
const ledger = path2__namespace.join(dir, OLD_INVITE_LEDGER_FILE);
|
|
1067
|
+
if (tryUnlink(ledger)) removed.push(ledger);
|
|
1068
|
+
const texts = path2__namespace.join(dir, "texts.json");
|
|
1012
1069
|
try {
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1070
|
+
const entry = JSON.parse(fs__namespace.readFileSync(texts, "utf8"));
|
|
1071
|
+
if (entry.version !== 1 || typeof entry.runtime !== "string") {
|
|
1072
|
+
if (tryUnlink(texts)) removed.push(texts);
|
|
1073
|
+
}
|
|
1074
|
+
} catch (err) {
|
|
1075
|
+
if (err?.code !== "ENOENT" && tryUnlink(texts)) removed.push(texts);
|
|
1016
1076
|
}
|
|
1077
|
+
return removed;
|
|
1017
1078
|
}
|
|
1018
|
-
function
|
|
1019
|
-
fs__namespace.mkdirSync(path2__namespace.dirname(file), { recursive: true });
|
|
1020
|
-
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
1021
|
-
fs__namespace.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
|
|
1022
|
-
`, "utf8");
|
|
1079
|
+
function tryUnlink(file) {
|
|
1023
1080
|
try {
|
|
1024
|
-
fs__namespace.
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
} catch {
|
|
1029
|
-
}
|
|
1030
|
-
throw err;
|
|
1081
|
+
fs__namespace.unlinkSync(file);
|
|
1082
|
+
return true;
|
|
1083
|
+
} catch {
|
|
1084
|
+
return false;
|
|
1031
1085
|
}
|
|
1032
1086
|
}
|
|
1033
1087
|
|
|
1034
1088
|
// src/integration/texts.ts
|
|
1035
1089
|
var TEXTS_RUNTIME = "openclaw";
|
|
1036
|
-
var TEXTS_REFRESH_MS = 24 * 60 * 6e4;
|
|
1037
|
-
var TEXTS_RETRY_MS = 5 * 6e4;
|
|
1038
|
-
var TEXTS_FETCH_TIMEOUT_MS = 1e4;
|
|
1039
1090
|
var TEXTS_CACHE_FILE = "texts.json";
|
|
1040
|
-
function isTexts(value) {
|
|
1041
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1042
|
-
const t = value;
|
|
1043
|
-
const manual = t.manual;
|
|
1044
|
-
return typeof t.version === "string" && typeof t.wake_instruction === "string" && t.wake_instruction.length > 0 && typeof t.invite_prompt === "string" && t.invite_prompt.length > 0 && typeof t.identity_line === "string" && t.identity_line.length > 0 && typeof t.identity_line_template === "string" && !!manual && typeof manual === "object" && typeof manual.url === "string" && typeof manual.version === "string";
|
|
1045
|
-
}
|
|
1046
1091
|
function textsCachePath(accountId, stateDir) {
|
|
1047
1092
|
return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1048
1093
|
}
|
|
1049
|
-
function readCachedTexts(accountId, stateDir) {
|
|
1050
|
-
const raw = readJsonFile(textsCachePath(accountId, stateDir));
|
|
1051
|
-
if (!raw || typeof raw !== "object") return null;
|
|
1052
|
-
const entry = raw;
|
|
1053
|
-
if (typeof entry.fetched_at !== "string" || !isTexts(entry.texts)) return null;
|
|
1054
|
-
return { fetched_at: entry.fetched_at, texts: entry.texts };
|
|
1055
|
-
}
|
|
1056
|
-
function writeCachedTexts(accountId, texts, fetchedAt, stateDir) {
|
|
1057
|
-
const file = textsCachePath(accountId, stateDir);
|
|
1058
|
-
const entry = { fetched_at: fetchedAt.toISOString(), texts };
|
|
1059
|
-
writeJsonFile(file, entry);
|
|
1060
|
-
return file;
|
|
1061
|
-
}
|
|
1062
1094
|
function spellTextsForOpenClaw(texts) {
|
|
1063
1095
|
return {
|
|
1064
1096
|
...texts,
|
|
1065
1097
|
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1066
1098
|
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1067
1099
|
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
1068
|
-
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
|
|
1100
|
+
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),
|
|
1101
|
+
...typeof texts.gate_call_preamble === "string" ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {},
|
|
1102
|
+
...typeof texts.gate_call_answer_format === "string" ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}
|
|
1069
1103
|
};
|
|
1070
1104
|
}
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1105
|
+
function createTextsCache(params) {
|
|
1106
|
+
return new agentchatme.integration.TextsCache({
|
|
1107
|
+
client: params.client,
|
|
1108
|
+
runtime: TEXTS_RUNTIME,
|
|
1109
|
+
filePath: textsCachePath(params.accountId, params.stateDir),
|
|
1110
|
+
...params.logger ? { onError: (err) => params.logger?.warn({ err: err.message }, "served texts") } : {}
|
|
1111
|
+
});
|
|
1075
1112
|
}
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
const texts = await fetchTexts(params.client, params.timeoutMs);
|
|
1080
|
-
const fetchedAt = new Date(now());
|
|
1081
|
-
try {
|
|
1082
|
-
writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir);
|
|
1083
|
-
} catch (err) {
|
|
1084
|
-
params.log?.warn({ err: describe2(err) }, "texts fetched but the cache could not be written");
|
|
1085
|
-
}
|
|
1086
|
-
return { texts: spellTextsForOpenClaw(texts), source: "server", fetchedAt: fetchedAt.toISOString() };
|
|
1087
|
-
} catch (err) {
|
|
1088
|
-
const cached = readCachedTexts(params.accountId, params.stateDir);
|
|
1089
|
-
if (cached) {
|
|
1090
|
-
params.log?.info({ err: describe2(err), fetchedAt: cached.fetched_at }, "texts: server unreachable \u2014 using the cached copy");
|
|
1091
|
-
return { texts: spellTextsForOpenClaw(cached.texts), source: "cache", fetchedAt: cached.fetched_at };
|
|
1092
|
-
}
|
|
1093
|
-
params.log?.debug({ err: describe2(err) }, "texts: server unreachable and nothing cached");
|
|
1094
|
-
return null;
|
|
1113
|
+
var OpenClawTexts = class {
|
|
1114
|
+
constructor(cache2) {
|
|
1115
|
+
this.cache = cache2;
|
|
1095
1116
|
}
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
function cachedIdentityLine(accountId, stateDir) {
|
|
1102
|
-
const cached = readCachedTexts(accountId, stateDir);
|
|
1103
|
-
return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null;
|
|
1104
|
-
}
|
|
1105
|
-
var TextsStore = class {
|
|
1106
|
-
client;
|
|
1107
|
-
accountId;
|
|
1108
|
-
logger;
|
|
1109
|
-
stateDir;
|
|
1110
|
-
refreshMs;
|
|
1111
|
-
retryMs;
|
|
1112
|
-
fetchTimeoutMs;
|
|
1113
|
-
now;
|
|
1114
|
-
_setTimeout;
|
|
1115
|
-
_clearTimeout;
|
|
1116
|
-
loaded = null;
|
|
1117
|
-
timer = null;
|
|
1118
|
-
inFlight = null;
|
|
1119
|
-
stopped = false;
|
|
1120
|
-
missingAnnounced = false;
|
|
1121
|
-
listeners = /* @__PURE__ */ new Set();
|
|
1122
|
-
loads = 0;
|
|
1123
|
-
serverLoads = 0;
|
|
1124
|
-
constructor(options) {
|
|
1125
|
-
this.client = options.client;
|
|
1126
|
-
this.accountId = options.accountId;
|
|
1127
|
-
this.logger = options.logger.child({ component: "texts", accountId: options.accountId });
|
|
1128
|
-
this.stateDir = options.stateDir;
|
|
1129
|
-
this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
|
|
1130
|
-
this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
|
|
1131
|
-
this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS;
|
|
1132
|
-
this.now = options.now ?? Date.now;
|
|
1133
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
1134
|
-
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
1117
|
+
cache;
|
|
1118
|
+
spelledFrom = null;
|
|
1119
|
+
spelled = null;
|
|
1120
|
+
current() {
|
|
1121
|
+
return this.spell(this.cache.current());
|
|
1135
1122
|
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
return this.loaded?.texts ?? null;
|
|
1123
|
+
async ensure() {
|
|
1124
|
+
return this.spell(await this.cache.ensure());
|
|
1139
1125
|
}
|
|
1140
1126
|
get source() {
|
|
1141
|
-
return this.
|
|
1127
|
+
return this.cache.source;
|
|
1142
1128
|
}
|
|
1143
1129
|
get fetchedAt() {
|
|
1144
|
-
return this.
|
|
1130
|
+
return this.cache.fetchedAt;
|
|
1145
1131
|
}
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
this.listeners.add(listener);
|
|
1149
|
-
return () => {
|
|
1150
|
-
this.listeners.delete(listener);
|
|
1151
|
-
};
|
|
1132
|
+
get lastError() {
|
|
1133
|
+
return this.cache.lastError;
|
|
1152
1134
|
}
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
this.
|
|
1158
|
-
this.logger.warn(
|
|
1159
|
-
{ retryMs: this.retryMs },
|
|
1160
|
-
"AgentChat texts unreachable and nothing cached \u2014 starting anyway; turns wait for the first copy, retried until it arrives"
|
|
1161
|
-
);
|
|
1135
|
+
spell(texts) {
|
|
1136
|
+
if (texts === null) return null;
|
|
1137
|
+
if (texts !== this.spelledFrom) {
|
|
1138
|
+
this.spelledFrom = texts;
|
|
1139
|
+
this.spelled = spellTextsForOpenClaw(texts);
|
|
1162
1140
|
}
|
|
1163
|
-
this.
|
|
1164
|
-
return texts;
|
|
1141
|
+
return this.spelled;
|
|
1165
1142
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1143
|
+
};
|
|
1144
|
+
async function loadIdentityLine(params) {
|
|
1145
|
+
const cache2 = createTextsCache(params);
|
|
1146
|
+
try {
|
|
1147
|
+
const texts = await cache2.start();
|
|
1148
|
+
return texts ? spellToolsForOpenClaw(texts.identity_line) : null;
|
|
1149
|
+
} catch {
|
|
1150
|
+
return null;
|
|
1151
|
+
} finally {
|
|
1152
|
+
cache2.stop();
|
|
1175
1153
|
}
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1154
|
+
}
|
|
1155
|
+
function cachedIdentityLine(accountId, stateDir) {
|
|
1156
|
+
let raw;
|
|
1157
|
+
try {
|
|
1158
|
+
raw = fs__namespace.readFileSync(textsCachePath(accountId, stateDir), "utf8");
|
|
1159
|
+
} catch {
|
|
1160
|
+
return null;
|
|
1183
1161
|
}
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
accountId: this.accountId,
|
|
1191
|
-
stateDir: this.stateDir,
|
|
1192
|
-
now: this.now,
|
|
1193
|
-
log: this.logger,
|
|
1194
|
-
timeoutMs: this.fetchTimeoutMs
|
|
1195
|
-
});
|
|
1196
|
-
if (this.stopped) return next?.texts ?? null;
|
|
1197
|
-
if (next) {
|
|
1198
|
-
const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction;
|
|
1199
|
-
this.loaded = next;
|
|
1200
|
-
if (next.source === "server") {
|
|
1201
|
-
this.serverLoads += 1;
|
|
1202
|
-
this.logger[changed ? "info" : "debug"](
|
|
1203
|
-
{ version: next.texts.version, manual: next.texts.manual.version },
|
|
1204
|
-
"texts fetched from the server"
|
|
1205
|
-
);
|
|
1206
|
-
for (const listener of this.listeners) {
|
|
1207
|
-
try {
|
|
1208
|
-
listener(next.texts, next.source);
|
|
1209
|
-
} catch (err) {
|
|
1210
|
-
this.logger.warn({ err: describe2(err) }, "texts listener threw \u2014 continuing");
|
|
1211
|
-
}
|
|
1212
|
-
}
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
return next?.texts ?? null;
|
|
1216
|
-
})().finally(() => {
|
|
1217
|
-
this.inFlight = null;
|
|
1218
|
-
});
|
|
1219
|
-
return this.inFlight;
|
|
1220
|
-
}
|
|
1221
|
-
arm() {
|
|
1222
|
-
if (this.stopped) return;
|
|
1223
|
-
if (this.timer !== null) this._clearTimeout(this.timer);
|
|
1224
|
-
const delay = this.loaded === null ? this.retryMs : this.loaded.source === "cache" ? this.retryMs : this.refreshMs;
|
|
1225
|
-
this.timer = this._setTimeout(() => {
|
|
1226
|
-
this.timer = null;
|
|
1227
|
-
void this.load().finally(() => this.arm());
|
|
1228
|
-
}, delay);
|
|
1229
|
-
this.timer.unref?.();
|
|
1162
|
+
try {
|
|
1163
|
+
const entry = JSON.parse(raw);
|
|
1164
|
+
if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null;
|
|
1165
|
+
return spellToolsForOpenClaw(entry.texts.identity_line);
|
|
1166
|
+
} catch {
|
|
1167
|
+
return null;
|
|
1230
1168
|
}
|
|
1231
|
-
};
|
|
1232
|
-
function describe2(err) {
|
|
1233
|
-
return err instanceof Error ? err.message : String(err);
|
|
1234
1169
|
}
|
|
1170
|
+
var isTexts = agentchatme.integration.isTexts;
|
|
1235
1171
|
var cache = /* @__PURE__ */ new Map();
|
|
1236
1172
|
function createSdkClient(params) {
|
|
1237
1173
|
return new agentchatme.AgentChatClient({
|
|
@@ -2037,35 +1973,672 @@ var agentchatChannelConfigSchema = zod.z.object({
|
|
|
2037
1973
|
function parseChannelConfig(input) {
|
|
2038
1974
|
return agentchatChannelConfigSchema.parse(input);
|
|
2039
1975
|
}
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
timestamp: pino__default.default.stdTimeFunctions.isoTime
|
|
2052
|
-
});
|
|
2053
|
-
return wrapPino(pinoLogger);
|
|
2054
|
-
}
|
|
2055
|
-
function buildRedactPaths(keys) {
|
|
2056
|
-
const prefixes = ["", "config.", "headers.", "context.", "req.headers.", "res.headers."];
|
|
2057
|
-
const paths = [];
|
|
2058
|
-
for (const key of keys) {
|
|
2059
|
-
for (const prefix of prefixes) {
|
|
2060
|
-
paths.push(`${prefix}${key}`);
|
|
1976
|
+
var TRAY_LIMIT = 50;
|
|
1977
|
+
function createAfterTurnRecorder(options) {
|
|
1978
|
+
const { client, logger } = options;
|
|
1979
|
+
return async (record, end) => {
|
|
1980
|
+
if (end.status === "still_running" || record.kind === "run") return;
|
|
1981
|
+
let fresh;
|
|
1982
|
+
try {
|
|
1983
|
+
fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true });
|
|
1984
|
+
} catch (err) {
|
|
1985
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn tray read failed \u2014 nothing recorded; the server re-wakes the card");
|
|
1986
|
+
fresh = null;
|
|
2061
1987
|
}
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
1988
|
+
try {
|
|
1989
|
+
if (record.kind === "reply") {
|
|
1990
|
+
if (!record.card) return;
|
|
1991
|
+
const outcome2 = agentchatme.integration.turnOutcome({
|
|
1992
|
+
turn: end,
|
|
1993
|
+
turnStartedAt: record.startedAt,
|
|
1994
|
+
gateCard: record.card,
|
|
1995
|
+
category: record.category ?? null,
|
|
1996
|
+
freshTray: fresh,
|
|
1997
|
+
silentBefore: 0
|
|
1998
|
+
});
|
|
1999
|
+
const recorded2 = await agentchatme.integration.applyOutcome(client, outcome2);
|
|
2000
|
+
logger.info({ runId: record.runId, conversationId: record.id, action: outcome2.action, reason: outcome2.reason, recorded: recorded2 }, "after-turn rule applied (turn ended outside the loop\u2019s watch)");
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
2003
|
+
if (!record.invite) return;
|
|
2004
|
+
const outcome = agentchatme.integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 });
|
|
2005
|
+
const recorded = await agentchatme.integration.applyInviteOutcome(client, outcome);
|
|
2006
|
+
logger.info({ runId: record.runId, inviteId: record.id, action: outcome.action, reason: outcome.reason, recorded }, "after-turn rule applied to the invite (turn ended outside the loop\u2019s watch)");
|
|
2007
|
+
} catch (err) {
|
|
2008
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn recording failed \u2014 the card stays on the tray; the server re-wakes it");
|
|
2009
|
+
}
|
|
2010
|
+
};
|
|
2065
2011
|
}
|
|
2066
|
-
function
|
|
2012
|
+
function cardFromStored(stored) {
|
|
2013
|
+
return { preview: null, ...stored };
|
|
2014
|
+
}
|
|
2015
|
+
function describe3(err) {
|
|
2016
|
+
return err instanceof Error ? err.message : String(err);
|
|
2017
|
+
}
|
|
2018
|
+
var TURN_STORE_FILE = "turns.json";
|
|
2019
|
+
var KEEP_ENDED_MS = 6e4;
|
|
2020
|
+
function storedCard(card, anchor) {
|
|
2067
2021
|
return {
|
|
2068
|
-
|
|
2022
|
+
conversation_id: card.conversation_id,
|
|
2023
|
+
...anchor ? { last_message_id: anchor } : {},
|
|
2024
|
+
...card.your_last_message_at !== void 0 ? { your_last_message_at: card.your_last_message_at } : {},
|
|
2025
|
+
...card.you_owe_reply !== void 0 ? { you_owe_reply: card.you_owe_reply } : {},
|
|
2026
|
+
...card.your_last_decision !== void 0 ? { your_last_decision: card.your_last_decision } : {}
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
var TurnStore = class {
|
|
2030
|
+
file;
|
|
2031
|
+
constructor(accountId, stateDir) {
|
|
2032
|
+
this.file = path2__namespace.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE);
|
|
2033
|
+
}
|
|
2034
|
+
/** What the last process left. Empty when there is no file or it cannot be read. */
|
|
2035
|
+
load() {
|
|
2036
|
+
let parsed;
|
|
2037
|
+
try {
|
|
2038
|
+
parsed = JSON.parse(fs__namespace.readFileSync(this.file, "utf8"));
|
|
2039
|
+
} catch {
|
|
2040
|
+
return [];
|
|
2041
|
+
}
|
|
2042
|
+
const turns = parsed?.turns;
|
|
2043
|
+
if (parsed?.version !== 1 || !Array.isArray(turns)) return [];
|
|
2044
|
+
return turns.filter(isStoredTurn);
|
|
2045
|
+
}
|
|
2046
|
+
/** Replace the file with `turns` (removed when empty). Returns false when the write failed. */
|
|
2047
|
+
write(turns) {
|
|
2048
|
+
try {
|
|
2049
|
+
if (turns.length === 0) {
|
|
2050
|
+
fs__namespace.rmSync(this.file, { force: true });
|
|
2051
|
+
return true;
|
|
2052
|
+
}
|
|
2053
|
+
fs__namespace.mkdirSync(path2__namespace.dirname(this.file), { recursive: true });
|
|
2054
|
+
const body = { version: 1, turns };
|
|
2055
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
2056
|
+
fs__namespace.writeFileSync(tmp, `${JSON.stringify(body)}
|
|
2057
|
+
`, { mode: 384 });
|
|
2058
|
+
fs__namespace.renameSync(tmp, this.file);
|
|
2059
|
+
return true;
|
|
2060
|
+
} catch {
|
|
2061
|
+
return false;
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
};
|
|
2065
|
+
function isStoredTurn(value) {
|
|
2066
|
+
const turn = value;
|
|
2067
|
+
return typeof turn === "object" && turn !== null && typeof turn.runId === "string" && (turn.kind === "reply" || turn.kind === "invite") && typeof turn.id === "string" && turn.id.length > 0 && typeof turn.sessionKey === "string" && turn.sessionKey.length > 0 && typeof turn.startedAt === "number" && (turn.anchor === null || typeof turn.anchor === "string");
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// src/integration/running.ts
|
|
2071
|
+
var TURN_OVERDUE_MS = 30 * 6e4;
|
|
2072
|
+
var OVERDUE_SLACK_MS = 5e3;
|
|
2073
|
+
function isOverdue(elapsedMs) {
|
|
2074
|
+
return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS;
|
|
2075
|
+
}
|
|
2076
|
+
var MAX_HUNG_TURNS = 2;
|
|
2077
|
+
var OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60;
|
|
2078
|
+
var RESTART_HOLD_MS = 3 * 6e4;
|
|
2079
|
+
var STORED_TURN_MAX_AGE_MS = 24 * 60 * 6e4;
|
|
2080
|
+
var RESTART_END_DETAIL = "the gateway restarted during the turn";
|
|
2081
|
+
function trackerKey(kind, id) {
|
|
2082
|
+
return kind === "reply" ? `conversation:${id}` : kind === "invite" ? `invite:${id}` : `run:${id}`;
|
|
2083
|
+
}
|
|
2084
|
+
function trackedTurn(record) {
|
|
2085
|
+
if (record.kind === "reply") return { kind: "reply", conversationId: record.id, anchor: record.anchor };
|
|
2086
|
+
if (record.kind === "invite") return { kind: "invite", inviteId: record.id };
|
|
2087
|
+
return null;
|
|
2088
|
+
}
|
|
2089
|
+
function storedOf(record) {
|
|
2090
|
+
if (record.kind === "run") return null;
|
|
2091
|
+
return {
|
|
2092
|
+
runId: record.runId,
|
|
2093
|
+
kind: record.kind,
|
|
2094
|
+
id: record.id,
|
|
2095
|
+
anchor: record.anchor,
|
|
2096
|
+
sessionKey: record.sessionKey,
|
|
2097
|
+
startedAt: record.startedAt,
|
|
2098
|
+
...record.firstStartedAt !== void 0 ? { firstStartedAt: record.firstStartedAt } : {},
|
|
2099
|
+
...record.category !== void 0 ? { category: record.category } : {},
|
|
2100
|
+
...record.kind === "reply" && record.card ? { card: storedCard(record.card, record.anchor) } : {}
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
2103
|
+
function recordOf(stored) {
|
|
2104
|
+
return {
|
|
2105
|
+
runId: stored.runId,
|
|
2106
|
+
kind: stored.kind,
|
|
2107
|
+
id: stored.id,
|
|
2108
|
+
anchor: stored.anchor,
|
|
2109
|
+
sessionKey: stored.sessionKey,
|
|
2110
|
+
startedAt: stored.startedAt,
|
|
2111
|
+
firstStartedAt: stored.firstStartedAt ?? stored.startedAt,
|
|
2112
|
+
owner: "previous-process",
|
|
2113
|
+
...stored.category !== void 0 ? { category: stored.category } : {},
|
|
2114
|
+
...stored.kind === "reply" && stored.card ? { card: cardFromStored(stored.card) } : {},
|
|
2115
|
+
...stored.kind === "invite" ? { invite: { invite_id: stored.id } } : {}
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
var AccountTurns = class {
|
|
2119
|
+
/** The kit's tracker for the account, shared by every loop for it. */
|
|
2120
|
+
tracker;
|
|
2121
|
+
entries = /* @__PURE__ */ new Map();
|
|
2122
|
+
/** Turns the last process left in flight, by session key. */
|
|
2123
|
+
adopted = /* @__PURE__ */ new Map();
|
|
2124
|
+
/** Turns OpenClaw is admitting right now. */
|
|
2125
|
+
admitting = /* @__PURE__ */ new Set();
|
|
2126
|
+
/** Ended runs still written to the store (`KEEP_ENDED_MS`). */
|
|
2127
|
+
kept = /* @__PURE__ */ new Map();
|
|
2128
|
+
keptTimer = null;
|
|
2129
|
+
live = null;
|
|
2130
|
+
wiring = {};
|
|
2131
|
+
/** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */
|
|
2132
|
+
lane = 0;
|
|
2133
|
+
now;
|
|
2134
|
+
constructor(options = {}) {
|
|
2135
|
+
this.now = options.now ?? Date.now;
|
|
2136
|
+
this.tracker = new agentchatme.integration.TurnTracker({ now: this.now });
|
|
2137
|
+
this.tracker.onRelease((handle) => {
|
|
2138
|
+
for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true;
|
|
2139
|
+
});
|
|
2140
|
+
}
|
|
2141
|
+
/** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */
|
|
2142
|
+
configure(wiring) {
|
|
2143
|
+
this.wiring = { ...this.wiring, ...wiring };
|
|
2144
|
+
}
|
|
2145
|
+
/** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */
|
|
2146
|
+
setLive(owner, wake, run = (fn) => fn()) {
|
|
2147
|
+
this.live = { owner, wake, run };
|
|
2148
|
+
}
|
|
2149
|
+
clearLive(owner) {
|
|
2150
|
+
if (this.live?.owner === owner) this.live = null;
|
|
2151
|
+
}
|
|
2152
|
+
/** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */
|
|
2153
|
+
admission(kind, id) {
|
|
2154
|
+
const admission = { key: trackerKey(kind, id), released: false };
|
|
2155
|
+
this.admitting.add(admission);
|
|
2156
|
+
return admission;
|
|
2157
|
+
}
|
|
2158
|
+
/** OpenClaw refused the turn: nothing to watch. */
|
|
2159
|
+
admitted(admission) {
|
|
2160
|
+
this.admitting.delete(admission);
|
|
2161
|
+
}
|
|
2162
|
+
/**
|
|
2163
|
+
* A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting
|
|
2164
|
+
* on it when it is handed off or released. `admission`: a turn whose kit
|
|
2165
|
+
* hold was released during admission starts out let go of.
|
|
2166
|
+
*/
|
|
2167
|
+
started(record, options = {}) {
|
|
2168
|
+
const releasedMeanwhile = options.admission?.released === true;
|
|
2169
|
+
if (options.admission) this.admitting.delete(options.admission);
|
|
2170
|
+
this.entries.set(record.runId, {
|
|
2171
|
+
record,
|
|
2172
|
+
state: releasedMeanwhile ? "released" : "kit",
|
|
2173
|
+
handle: null,
|
|
2174
|
+
since: 0,
|
|
2175
|
+
...options.letGo ? { letGo: options.letGo } : {}
|
|
2176
|
+
});
|
|
2177
|
+
this.persist();
|
|
2178
|
+
}
|
|
2179
|
+
run(runId) {
|
|
2180
|
+
return this.entries.get(runId)?.record;
|
|
2181
|
+
}
|
|
2182
|
+
/** Where the run stands (`null`: not a run of this account, or ended). */
|
|
2183
|
+
stateOf(runId) {
|
|
2184
|
+
return this.entries.get(runId)?.state ?? null;
|
|
2185
|
+
}
|
|
2186
|
+
/** Every run OpenClaw has not reported ended that still holds something, oldest first. */
|
|
2187
|
+
runningRuns() {
|
|
2188
|
+
return [...this.entries.values()].filter((entry) => entry.state !== "released").map((entry) => entry.record).sort((a, b) => a.startedAt - b.startedAt);
|
|
2189
|
+
}
|
|
2190
|
+
hungRuns() {
|
|
2191
|
+
return [...this.entries.values()].filter((entry) => entry.state === "hung").map((entry) => entry.record);
|
|
2192
|
+
}
|
|
2193
|
+
get hungCount() {
|
|
2194
|
+
let count = 0;
|
|
2195
|
+
for (const entry of this.entries.values()) if (entry.state === "hung") count += 1;
|
|
2196
|
+
return count;
|
|
2197
|
+
}
|
|
2198
|
+
/** The handed-off gate-off run still going, if any: no new run starts while it lives. */
|
|
2199
|
+
hungSingleRun() {
|
|
2200
|
+
for (const entry of this.entries.values()) if (entry.state === "hung" && entry.record.kind === "run") return entry.record;
|
|
2201
|
+
return null;
|
|
2202
|
+
}
|
|
2203
|
+
/** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */
|
|
2204
|
+
restartHolds() {
|
|
2205
|
+
const holds = [...this.adopted.values()].map((a) => ({
|
|
2206
|
+
record: a.record,
|
|
2207
|
+
until: a.until,
|
|
2208
|
+
watching: null
|
|
2209
|
+
}));
|
|
2210
|
+
for (const entry of this.entries.values()) if (entry.state === "watch") holds.push({ record: entry.record, until: null, watching: entry.record.runId });
|
|
2211
|
+
return holds;
|
|
2212
|
+
}
|
|
2213
|
+
/** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */
|
|
2214
|
+
get laneGeneration() {
|
|
2215
|
+
return this.lane;
|
|
2216
|
+
}
|
|
2217
|
+
/**
|
|
2218
|
+
* OpenClaw reported the run ended (`end`: what it did, when known). A turn
|
|
2219
|
+
* held here (handed off, or continued after a restart) gets the after-turn
|
|
2220
|
+
* rule, then its hold drops and the live loop is woken. A turn the kit
|
|
2221
|
+
* still holds is the kit's to record; the live loop is woken once the card
|
|
2222
|
+
* is free, only when an earlier loop started it. A run let go of records
|
|
2223
|
+
* nothing.
|
|
2224
|
+
*/
|
|
2225
|
+
async ended(runId, end) {
|
|
2226
|
+
const entry = this.entries.get(runId);
|
|
2227
|
+
if (!entry) return;
|
|
2228
|
+
this.entries.delete(runId);
|
|
2229
|
+
if (entry.state !== "released") this.keep(entry.record);
|
|
2230
|
+
else this.persist();
|
|
2231
|
+
if (entry.state === "hung" || entry.state === "watch") {
|
|
2232
|
+
try {
|
|
2233
|
+
if (end && this.wiring.recorder && entry.record.kind !== "run") await this.wiring.recorder(entry.record, end);
|
|
2234
|
+
} finally {
|
|
2235
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2236
|
+
this.live?.wake();
|
|
2237
|
+
}
|
|
2238
|
+
return;
|
|
2239
|
+
}
|
|
2240
|
+
if (entry.state === "released" || entry.record.kind === "run") return;
|
|
2241
|
+
if (!this.live || this.live.owner === entry.record.owner) return;
|
|
2242
|
+
this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id));
|
|
2243
|
+
}
|
|
2244
|
+
/**
|
|
2245
|
+
* Hand a long run off, once, by run id: release the kit's slot for it (its
|
|
2246
|
+
* loop records nothing for it and may start other turns) and hold the
|
|
2247
|
+
* conversation here until the run ends. A gate-off run: the cycle waiting
|
|
2248
|
+
* on it is let go of. A continued run is already held here: it becomes
|
|
2249
|
+
* hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was
|
|
2250
|
+
* handed off now; null when it was already handed off or let go of.
|
|
2251
|
+
*/
|
|
2252
|
+
handOff(runId) {
|
|
2253
|
+
const entry = this.entries.get(runId);
|
|
2254
|
+
if (!entry || entry.state !== "kit" && entry.state !== "watch") return null;
|
|
2255
|
+
const record = entry.record;
|
|
2256
|
+
entry.since = this.now();
|
|
2257
|
+
if (entry.state === "watch") {
|
|
2258
|
+
entry.state = "hung";
|
|
2259
|
+
this.live?.wake();
|
|
2260
|
+
return record;
|
|
2261
|
+
}
|
|
2262
|
+
this.lane += 1;
|
|
2263
|
+
entry.state = "hung";
|
|
2264
|
+
const turn = trackedTurn(record);
|
|
2265
|
+
if (turn === null) {
|
|
2266
|
+
entry.letGo?.();
|
|
2267
|
+
} else {
|
|
2268
|
+
this.tracker.release(trackerKey(record.kind, record.id));
|
|
2269
|
+
entry.handle = this.tracker.begin(turn);
|
|
2270
|
+
if (!entry.handle) entry.state = "released";
|
|
2271
|
+
}
|
|
2272
|
+
this.live?.wake();
|
|
2273
|
+
return entry.state === "hung" ? record : null;
|
|
2274
|
+
}
|
|
2275
|
+
/**
|
|
2276
|
+
* An operator lets go of a conversation's (or invite's) turn: a hung hold,
|
|
2277
|
+
* a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn
|
|
2278
|
+
* still running. Its run may still be live and answer: a second reply is
|
|
2279
|
+
* then possible, which is why a turn under 30 minutes (most likely still
|
|
2280
|
+
* working) is refused without `force`. A gate-off run always needs
|
|
2281
|
+
* `force`: it reads the whole tray, so a new run would answer the same
|
|
2282
|
+
* cards while it may still be going.
|
|
2283
|
+
*/
|
|
2284
|
+
release(id, options = {}) {
|
|
2285
|
+
const live = this.live;
|
|
2286
|
+
return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true);
|
|
2287
|
+
}
|
|
2288
|
+
releaseNow(id, force) {
|
|
2289
|
+
const matches = (record) => record.id === id || record.runId === id;
|
|
2290
|
+
for (const entry of this.entries.values()) {
|
|
2291
|
+
if (entry.state !== "hung" || !matches(entry.record)) continue;
|
|
2292
|
+
if (entry.record.kind === "run" && !force) return this.refuseSingleRun(entry.record);
|
|
2293
|
+
entry.state = "released";
|
|
2294
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2295
|
+
entry.handle = null;
|
|
2296
|
+
this.persist();
|
|
2297
|
+
this.live?.wake();
|
|
2298
|
+
return { released: true, what: "hung", key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId };
|
|
2299
|
+
}
|
|
2300
|
+
for (const [sessionKey, adopted] of this.adopted) {
|
|
2301
|
+
if (adopted.record.id !== id) continue;
|
|
2302
|
+
this.finishAdopted(sessionKey);
|
|
2303
|
+
return { released: true, what: "restart", key: trackerKey(adopted.record.kind, adopted.record.id), runId: null };
|
|
2304
|
+
}
|
|
2305
|
+
for (const entry of this.entries.values()) {
|
|
2306
|
+
if (entry.state !== "kit" && entry.state !== "watch" || !matches(entry.record)) continue;
|
|
2307
|
+
const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force);
|
|
2308
|
+
if (refused) return refused;
|
|
2309
|
+
const key = trackerKey(entry.record.kind, entry.record.id);
|
|
2310
|
+
if (entry.state === "watch") {
|
|
2311
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2312
|
+
entry.handle = null;
|
|
2313
|
+
} else {
|
|
2314
|
+
this.lane += 1;
|
|
2315
|
+
if (entry.record.kind === "run") entry.letGo?.();
|
|
2316
|
+
else this.tracker.release(key);
|
|
2317
|
+
}
|
|
2318
|
+
entry.state = "released";
|
|
2319
|
+
this.persist();
|
|
2320
|
+
this.live?.wake();
|
|
2321
|
+
return { released: true, what: "running", key, runId: entry.record.runId };
|
|
2322
|
+
}
|
|
2323
|
+
for (const held of this.tracker.running()) {
|
|
2324
|
+
const heldId = held.kind === "reply" ? held.conversationId : held.inviteId;
|
|
2325
|
+
if (heldId !== id) continue;
|
|
2326
|
+
const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force);
|
|
2327
|
+
if (refused) return refused;
|
|
2328
|
+
this.lane += 1;
|
|
2329
|
+
const key = trackerKey(held.kind, heldId);
|
|
2330
|
+
if (this.tracker.release(key)) {
|
|
2331
|
+
this.live?.wake();
|
|
2332
|
+
return { released: true, what: "running", key, runId: null };
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
return { released: false, reason: `no turn holds ${id}` };
|
|
2336
|
+
}
|
|
2337
|
+
refuseYoung(kind, id, startedAt, force) {
|
|
2338
|
+
const age = this.now() - startedAt;
|
|
2339
|
+
if (force || age >= TURN_OVERDUE_MS) return null;
|
|
2340
|
+
return {
|
|
2341
|
+
released: false,
|
|
2342
|
+
reason: `the turn for ${whatOf(kind, id)} has run ${Math.floor(age / 6e4)} min \u2014 under ${TURN_OVERDUE_MS / 6e4} min it is most likely still working, and releasing it lets the conversation be gated again while that run can still send its answer (the peer would get two replies); wait, or repeat with --force`
|
|
2343
|
+
};
|
|
2344
|
+
}
|
|
2345
|
+
refuseSingleRun(record) {
|
|
2346
|
+
return {
|
|
2347
|
+
released: false,
|
|
2348
|
+
reason: `${whatOf("run", record.runId)} has run ${Math.floor((this.now() - record.startedAt) / 6e4)} min and reads the whole tray \u2014 releasing it lets a new run answer the same cards while this one may still be going (the peers would get two replies); repeat with --force`
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Adopt the turns the last process left in flight (the store). Each one's
|
|
2353
|
+
* conversation (or invite) is held at once — before the loop's first gate —
|
|
2354
|
+
* for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended
|
|
2355
|
+
* run did now and again when the hold expires. A run OpenClaw starts in the
|
|
2356
|
+
* turn's session meanwhile (`observeRun`) takes the hold over. A turn first
|
|
2357
|
+
* started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what
|
|
2358
|
+
* was adopted.
|
|
2359
|
+
*/
|
|
2360
|
+
adopt(stored = this.wiring.store?.load() ?? []) {
|
|
2361
|
+
const adopted = [];
|
|
2362
|
+
const now = this.now();
|
|
2363
|
+
for (const turn of stored) {
|
|
2364
|
+
if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue;
|
|
2365
|
+
const first = turn.firstStartedAt ?? turn.startedAt;
|
|
2366
|
+
if (now - first > STORED_TURN_MAX_AGE_MS) {
|
|
2367
|
+
this.wiring.logger?.info({ runId: turn.runId, [turn.kind === "reply" ? "conversationId" : "inviteId"]: turn.id }, "a stored turn older than a day was dropped, not adopted again");
|
|
2368
|
+
continue;
|
|
2369
|
+
}
|
|
2370
|
+
const record = recordOf(turn);
|
|
2371
|
+
const tracked = trackedTurn(record);
|
|
2372
|
+
const handle = tracked ? this.tracker.begin(tracked) : null;
|
|
2373
|
+
if (!handle) continue;
|
|
2374
|
+
const entry = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null };
|
|
2375
|
+
this.adopted.set(turn.sessionKey, entry);
|
|
2376
|
+
entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS);
|
|
2377
|
+
entry.timer.unref?.();
|
|
2378
|
+
adopted.push(record);
|
|
2379
|
+
void this.recordRestartEnded(entry);
|
|
2380
|
+
}
|
|
2381
|
+
this.persist();
|
|
2382
|
+
return adopted;
|
|
2383
|
+
}
|
|
2384
|
+
/**
|
|
2385
|
+
* A run started in some session (the `model_call_started` hook). One in
|
|
2386
|
+
* the session of a turn adopted after a restart is OpenClaw continuing
|
|
2387
|
+
* that turn: it takes the hold over as a turn of its own (`watch`), handed
|
|
2388
|
+
* off past `TURN_OVERDUE_MS` like any other.
|
|
2389
|
+
*/
|
|
2390
|
+
observeRun(runId, sessionKey) {
|
|
2391
|
+
if (!sessionKey || this.entries.has(runId)) return;
|
|
2392
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2393
|
+
if (!adopted) return;
|
|
2394
|
+
this.adopted.delete(sessionKey);
|
|
2395
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2396
|
+
const record = { ...adopted.record, runId, startedAt: this.now(), owner: "restart" };
|
|
2397
|
+
this.entries.set(runId, { record, state: "watch", handle: adopted.handle, since: 0 });
|
|
2398
|
+
this.persist();
|
|
2399
|
+
this.wiring.logger?.info(
|
|
2400
|
+
{ runId, sessionKey, [record.kind === "reply" ? "conversationId" : "inviteId"]: record.id },
|
|
2401
|
+
"OpenClaw continued a turn session after the restart \u2014 its conversation stays held until that run ends"
|
|
2402
|
+
);
|
|
2403
|
+
void this.watchContinued(record);
|
|
2404
|
+
}
|
|
2405
|
+
async watchContinued(record) {
|
|
2406
|
+
let end = null;
|
|
2407
|
+
try {
|
|
2408
|
+
end = this.wiring.watch ? await this.wiring.watch(record) : null;
|
|
2409
|
+
} catch {
|
|
2410
|
+
end = null;
|
|
2411
|
+
}
|
|
2412
|
+
if (end === null) return;
|
|
2413
|
+
await this.ended(record.runId, end);
|
|
2414
|
+
}
|
|
2415
|
+
async recordRestartEnded(adopted) {
|
|
2416
|
+
const { record } = adopted;
|
|
2417
|
+
let calls = null;
|
|
2418
|
+
try {
|
|
2419
|
+
calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null;
|
|
2420
|
+
} catch {
|
|
2421
|
+
calls = null;
|
|
2422
|
+
}
|
|
2423
|
+
adopted.end = { status: "failed", agentchatCalls: calls, detail: RESTART_END_DETAIL };
|
|
2424
|
+
if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return;
|
|
2425
|
+
await this.wiring.recorder(record, adopted.end);
|
|
2426
|
+
}
|
|
2427
|
+
/**
|
|
2428
|
+
* The hold expired with nothing continuing the turn: the after-turn rule
|
|
2429
|
+
* once more — the resumed main session may have answered the card
|
|
2430
|
+
* meanwhile — then the conversation is free.
|
|
2431
|
+
*/
|
|
2432
|
+
expireAdopted(sessionKey, adopted) {
|
|
2433
|
+
if (this.adopted.get(sessionKey) !== adopted) return;
|
|
2434
|
+
void (async () => {
|
|
2435
|
+
try {
|
|
2436
|
+
if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: "failed", agentchatCalls: null, detail: RESTART_END_DETAIL });
|
|
2437
|
+
} catch {
|
|
2438
|
+
}
|
|
2439
|
+
if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey);
|
|
2440
|
+
})();
|
|
2441
|
+
}
|
|
2442
|
+
finishAdopted(sessionKey) {
|
|
2443
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2444
|
+
if (!adopted) return;
|
|
2445
|
+
this.adopted.delete(sessionKey);
|
|
2446
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2447
|
+
this.tracker.end(adopted.handle);
|
|
2448
|
+
this.persist();
|
|
2449
|
+
this.live?.wake();
|
|
2450
|
+
}
|
|
2451
|
+
/** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */
|
|
2452
|
+
keep(record) {
|
|
2453
|
+
const turn = storedOf(record);
|
|
2454
|
+
if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() });
|
|
2455
|
+
this.persist();
|
|
2456
|
+
if (!this.keptTimer) this.schedulePrune();
|
|
2457
|
+
}
|
|
2458
|
+
/** The next prune at the oldest kept entry's expiry. */
|
|
2459
|
+
schedulePrune() {
|
|
2460
|
+
let oldest = Infinity;
|
|
2461
|
+
for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt);
|
|
2462
|
+
if (oldest === Infinity) return;
|
|
2463
|
+
this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()));
|
|
2464
|
+
this.keptTimer.unref?.();
|
|
2465
|
+
}
|
|
2466
|
+
pruneKept() {
|
|
2467
|
+
this.keptTimer = null;
|
|
2468
|
+
const cutoff = this.now() - KEEP_ENDED_MS;
|
|
2469
|
+
for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId);
|
|
2470
|
+
this.persist();
|
|
2471
|
+
this.schedulePrune();
|
|
2472
|
+
}
|
|
2473
|
+
persist() {
|
|
2474
|
+
const store = this.wiring.store;
|
|
2475
|
+
if (!store) return;
|
|
2476
|
+
const turns = /* @__PURE__ */ new Map();
|
|
2477
|
+
for (const entry of this.entries.values()) {
|
|
2478
|
+
if (entry.state === "released") continue;
|
|
2479
|
+
const turn = storedOf(entry.record);
|
|
2480
|
+
if (turn) turns.set(turn.runId, turn);
|
|
2481
|
+
}
|
|
2482
|
+
for (const [runId, kept] of this.kept) turns.set(runId, kept.turn);
|
|
2483
|
+
for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored);
|
|
2484
|
+
if (!store.write([...turns.values()])) this.wiring.logger?.debug({ file: store.file }, "turns in flight could not be written (the restart defense is off until the next write)");
|
|
2485
|
+
}
|
|
2486
|
+
wakeWhenFree(key, attempts = 300) {
|
|
2487
|
+
const held = key.startsWith("conversation:") ? this.tracker.conversationRunning(key.slice("conversation:".length)) : this.tracker.inviteRunning(key.slice("invite:".length));
|
|
2488
|
+
if (!held || attempts <= 0) {
|
|
2489
|
+
this.live?.wake();
|
|
2490
|
+
return;
|
|
2491
|
+
}
|
|
2492
|
+
const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100);
|
|
2493
|
+
timer.unref?.();
|
|
2494
|
+
}
|
|
2495
|
+
};
|
|
2496
|
+
var accounts = /* @__PURE__ */ new Map();
|
|
2497
|
+
function accountTurns(accountId) {
|
|
2498
|
+
let turns = accounts.get(accountId);
|
|
2499
|
+
if (!turns) {
|
|
2500
|
+
turns = new AccountTurns();
|
|
2501
|
+
accounts.set(accountId, turns);
|
|
2502
|
+
}
|
|
2503
|
+
return turns;
|
|
2504
|
+
}
|
|
2505
|
+
function findAccountTurns(accountId) {
|
|
2506
|
+
return accounts.get(accountId);
|
|
2507
|
+
}
|
|
2508
|
+
function trackerFor(accountId) {
|
|
2509
|
+
return accountTurns(accountId).tracker;
|
|
2510
|
+
}
|
|
2511
|
+
function observeRunStarted(runId, sessionKey) {
|
|
2512
|
+
if (typeof runId !== "string" || runId.length === 0 || typeof sessionKey !== "string" || sessionKey.length === 0) return;
|
|
2513
|
+
for (const turns of accounts.values()) turns.observeRun(runId, sessionKey);
|
|
2514
|
+
}
|
|
2515
|
+
function runDeadline(cfg) {
|
|
2516
|
+
const value = cfg?.agents?.defaults?.timeoutSeconds;
|
|
2517
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true };
|
|
2518
|
+
return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false };
|
|
2519
|
+
}
|
|
2520
|
+
function whatOf(kind, id) {
|
|
2521
|
+
return kind === "reply" ? `conversation ${id}` : kind === "invite" ? `invite ${id}` : `the gate-off run ${id}`;
|
|
2522
|
+
}
|
|
2523
|
+
function deadlineText(cfg) {
|
|
2524
|
+
const deadline = runDeadline(cfg);
|
|
2525
|
+
return deadline.seconds === 0 ? "agents.defaults.timeoutSeconds is 0 (no deadline), so it may never end" : `OpenClaw ends it at its run deadline, agents.defaults.timeoutSeconds = ${deadline.seconds}${deadline.configured ? "" : " (OpenClaw's default, 48 h)"}`;
|
|
2526
|
+
}
|
|
2527
|
+
function overdueTurnLine(turn, cfg) {
|
|
2528
|
+
const minutes = Math.round(turn.elapsedMs / 6e4);
|
|
2529
|
+
if (turn.kind === "run") {
|
|
2530
|
+
return `${whatOf(turn.kind, turn.id)} has run ${minutes} min \u2014 no new run starts until it ends (one run reads the whole tray); ${deadlineText(cfg)}`;
|
|
2531
|
+
}
|
|
2532
|
+
return `a turn for ${whatOf(turn.kind, turn.id)} has run ${minutes} min \u2014 that conversation stays held (no second reply) until the run ends; ${deadlineText(cfg)}; other conversations are not held up by it`;
|
|
2533
|
+
}
|
|
2534
|
+
function overdueTurnLines(runs, cfg, now = Date.now()) {
|
|
2535
|
+
return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg));
|
|
2536
|
+
}
|
|
2537
|
+
function restartHoldLines(turns, now = Date.now()) {
|
|
2538
|
+
return turns.restartHolds().map(
|
|
2539
|
+
({ record, until, watching }) => watching || until === null ? `${whatOf(record.kind, record.id)} is held: OpenClaw continued its turn's session after the gateway restart (run ${watching ?? "unknown"}) \u2014 gated again once that run ends (handed off like any turn past 30 min)` : `${whatOf(record.kind, record.id)} is held for ${Math.max(0, Math.ceil((until - now) / 6e4))} more min: its turn was running when the gateway restarted, and OpenClaw may continue that turn's session`
|
|
2540
|
+
);
|
|
2541
|
+
}
|
|
2542
|
+
function hungTurnsReason(turns, cfg, now = Date.now()) {
|
|
2543
|
+
const single = turns.hungSingleRun();
|
|
2544
|
+
if (single) {
|
|
2545
|
+
return `${whatOf("run", single.runId)} has run ${Math.floor((now - single.startedAt) / 6e4)} min and is still going in OpenClaw \u2014 no new run starts while it lives (one run reads the whole tray; a second would answer the same cards), so the cards wait on the tray; ${deadlineText(cfg)}. \`openclaw agentchat release ${single.runId} --force\` lets a new run start (the old one may still answer)`;
|
|
2546
|
+
}
|
|
2547
|
+
if (turns.hungCount < MAX_HUNG_TURNS) return null;
|
|
2548
|
+
const held = turns.hungRuns().map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 6e4)} min`).join(", ");
|
|
2549
|
+
return `${turns.hungCount} turns are hung in OpenClaw (${held}) \u2014 no gate calls until one ends, so other cards are waiting on the tray; ${deadlineText(cfg)}. \`openclaw agentchat release <conversation_id>\` lets go of one (its run may still answer, so a second reply is possible), or restart the gateway`;
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
// src/binding/release.ts
|
|
2553
|
+
var RELEASE_METHOD = "agentchat.release";
|
|
2554
|
+
function releaseTurnFor(params) {
|
|
2555
|
+
const id = typeof params.id === "string" ? params.id.trim() : "";
|
|
2556
|
+
if (!id) return { ok: false, error: "a conversation (or invite) id is required" };
|
|
2557
|
+
const accountId = typeof params.accountId === "string" && params.accountId.trim() ? params.accountId.trim() : "default";
|
|
2558
|
+
const turns = findAccountTurns(accountId);
|
|
2559
|
+
if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account "${accountId}" has no turns in this gateway` } };
|
|
2560
|
+
return { ok: true, result: turns.release(id, { force: params.force === true }) };
|
|
2561
|
+
}
|
|
2562
|
+
function registerReleaseGatewayMethod(api) {
|
|
2563
|
+
api.registerGatewayMethod(
|
|
2564
|
+
RELEASE_METHOD,
|
|
2565
|
+
({ params, respond }) => {
|
|
2566
|
+
const outcome = releaseTurnFor(params);
|
|
2567
|
+
if (!outcome.ok) {
|
|
2568
|
+
respond(false, void 0, { code: "INVALID_REQUEST", message: outcome.error });
|
|
2569
|
+
return;
|
|
2570
|
+
}
|
|
2571
|
+
respond(true, outcome.result);
|
|
2572
|
+
},
|
|
2573
|
+
{ scope: "operator.admin" }
|
|
2574
|
+
);
|
|
2575
|
+
}
|
|
2576
|
+
function registerReleaseCli(api) {
|
|
2577
|
+
api.registerCli(
|
|
2578
|
+
({ program }) => {
|
|
2579
|
+
const root = program.command(AGENTCHAT_CHANNEL_ID).description("The AgentChat integration");
|
|
2580
|
+
root.command("release <id>").description(
|
|
2581
|
+
`Let go of the turn holding a conversation (or invite) whose OpenClaw run never ended. The run is not stopped: if it answers later, the peer can get a second reply. A turn under ${TURN_OVERDUE_MS / 6e4} minutes is refused without --force.`
|
|
2582
|
+
).option("--account <accountId>", "the AgentChat account", "default").option("--force", `release a turn that has run under ${TURN_OVERDUE_MS / 6e4} minutes (it is most likely still working: two replies are possible)`).option("--url <url>", "gateway URL (default: the configured gateway)").option("--token <token>", "gateway token (default: the configured one)").option("--json", "print the raw result").action(async (id, opts) => {
|
|
2583
|
+
const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime');
|
|
2584
|
+
const result = await callGatewayFromCli(
|
|
2585
|
+
RELEASE_METHOD,
|
|
2586
|
+
{ ...opts.url ? { url: opts.url } : {}, ...opts.token ? { token: opts.token } : {}, ...opts.json ? { json: true } : {} },
|
|
2587
|
+
{ id, accountId: opts.account ?? "default", ...opts.force ? { force: true } : {} }
|
|
2588
|
+
);
|
|
2589
|
+
process.stdout.write(opts.json ? `${JSON.stringify(result)}
|
|
2590
|
+
` : `${releaseLine(id, result)}
|
|
2591
|
+
`);
|
|
2592
|
+
});
|
|
2593
|
+
},
|
|
2594
|
+
{
|
|
2595
|
+
commands: [AGENTCHAT_CHANNEL_ID],
|
|
2596
|
+
descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: "The AgentChat integration (release a hung turn)", hasSubcommands: true }]
|
|
2597
|
+
}
|
|
2598
|
+
);
|
|
2599
|
+
}
|
|
2600
|
+
function releaseLine(id, result) {
|
|
2601
|
+
if (!result?.released) return `nothing released: ${result?.reason ?? "unknown"}`;
|
|
2602
|
+
if (result.what === "restart") return `released ${id} (held after a gateway restart) \u2014 it may be gated again now`;
|
|
2603
|
+
const what = result.what === "hung" ? "a hung turn" : "a running turn";
|
|
2604
|
+
return `released ${id} (${what}) \u2014 it may be gated again now; its OpenClaw run was not stopped, and if it still sends an answer the peer gets two replies`;
|
|
2605
|
+
}
|
|
2606
|
+
|
|
2607
|
+
// src/binding/run-observer.ts
|
|
2608
|
+
function registerRunObserver(api) {
|
|
2609
|
+
api.on("model_call_started", (event, ctx) => {
|
|
2610
|
+
observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey);
|
|
2611
|
+
});
|
|
2612
|
+
}
|
|
2613
|
+
function createLogger(options) {
|
|
2614
|
+
if (options.delegate) {
|
|
2615
|
+
return options.delegate;
|
|
2616
|
+
}
|
|
2617
|
+
const pinoLogger = pino__default.default({
|
|
2618
|
+
level: options.level,
|
|
2619
|
+
base: { plugin: "@agentchatme/openclaw" },
|
|
2620
|
+
redact: {
|
|
2621
|
+
paths: buildRedactPaths(options.redactKeys),
|
|
2622
|
+
censor: "[REDACTED]"
|
|
2623
|
+
},
|
|
2624
|
+
timestamp: pino__default.default.stdTimeFunctions.isoTime
|
|
2625
|
+
});
|
|
2626
|
+
return wrapPino(pinoLogger);
|
|
2627
|
+
}
|
|
2628
|
+
function buildRedactPaths(keys) {
|
|
2629
|
+
const prefixes = ["", "config.", "headers.", "context.", "req.headers.", "res.headers."];
|
|
2630
|
+
const paths = [];
|
|
2631
|
+
for (const key of keys) {
|
|
2632
|
+
for (const prefix of prefixes) {
|
|
2633
|
+
paths.push(`${prefix}${key}`);
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
paths.push(...keys.map((k) => `*.${k}`));
|
|
2637
|
+
return paths;
|
|
2638
|
+
}
|
|
2639
|
+
function wrapPino(p) {
|
|
2640
|
+
return {
|
|
2641
|
+
trace: (obj, msg) => p.trace(obj, msg),
|
|
2069
2642
|
debug: (obj, msg) => p.debug(obj, msg),
|
|
2070
2643
|
info: (obj, msg) => p.info(obj, msg),
|
|
2071
2644
|
warn: (obj, msg) => p.warn(obj, msg),
|
|
@@ -2135,85 +2708,12 @@ function createNoopMetrics() {
|
|
|
2135
2708
|
incWake: () => void 0
|
|
2136
2709
|
};
|
|
2137
2710
|
}
|
|
2138
|
-
function groupInviteFromRecord(record) {
|
|
2139
|
-
if (!record || typeof record !== "object" || Array.isArray(record)) return null;
|
|
2140
|
-
const row = record;
|
|
2141
|
-
const inviteId = str(row.id);
|
|
2142
|
-
const groupId = str(row.group_id);
|
|
2143
|
-
if (!inviteId || !groupId) return null;
|
|
2144
|
-
return {
|
|
2145
|
-
inviteId,
|
|
2146
|
-
groupId,
|
|
2147
|
-
groupName: str(row.group_name) ?? "",
|
|
2148
|
-
inviterHandle: (str(row.inviter_handle) ?? "").replace(/^@/, "")
|
|
2149
|
-
};
|
|
2150
|
-
}
|
|
2151
|
-
function str(value) {
|
|
2152
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2153
|
-
}
|
|
2154
|
-
var INVITE_LEDGER_FILE = "invites.json";
|
|
2155
|
-
var INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 6e4;
|
|
2156
|
-
function inviteLedgerPath(accountId, stateDir) {
|
|
2157
|
-
return path2__namespace.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE);
|
|
2158
|
-
}
|
|
2159
|
-
var InviteLedger = class {
|
|
2160
|
-
file;
|
|
2161
|
-
now;
|
|
2162
|
-
maxAgeMs;
|
|
2163
|
-
onWriteError;
|
|
2164
|
-
offered;
|
|
2165
|
-
constructor(options) {
|
|
2166
|
-
this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir);
|
|
2167
|
-
this.now = options.now ?? Date.now;
|
|
2168
|
-
this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS;
|
|
2169
|
-
this.onWriteError = options.onWriteError;
|
|
2170
|
-
this.offered = this.read();
|
|
2171
|
-
}
|
|
2172
|
-
get path() {
|
|
2173
|
-
return this.file;
|
|
2174
|
-
}
|
|
2175
|
-
get size() {
|
|
2176
|
-
return this.offered.size;
|
|
2177
|
-
}
|
|
2178
|
-
/** True when a turn for this invite was started before (in this process or an earlier one). */
|
|
2179
|
-
isOffered(inviteId) {
|
|
2180
|
-
return this.offered.has(inviteId);
|
|
2181
|
-
}
|
|
2182
|
-
/** Record that a turn for this invite was admitted. Persists at once. */
|
|
2183
|
-
markOffered(inviteId) {
|
|
2184
|
-
this.offered.set(inviteId, new Date(this.now()).toISOString());
|
|
2185
|
-
this.prune();
|
|
2186
|
-
try {
|
|
2187
|
-
writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) });
|
|
2188
|
-
} catch (err) {
|
|
2189
|
-
this.onWriteError?.(err);
|
|
2190
|
-
}
|
|
2191
|
-
}
|
|
2192
|
-
read() {
|
|
2193
|
-
const raw = readJsonFile(this.file);
|
|
2194
|
-
const out = /* @__PURE__ */ new Map();
|
|
2195
|
-
if (!raw || typeof raw !== "object") return out;
|
|
2196
|
-
const offered = raw.offered;
|
|
2197
|
-
if (!offered || typeof offered !== "object" || Array.isArray(offered)) return out;
|
|
2198
|
-
for (const [id, at] of Object.entries(offered)) {
|
|
2199
|
-
if (typeof at === "string" && id.length > 0) out.set(id, at);
|
|
2200
|
-
}
|
|
2201
|
-
this.offered = out;
|
|
2202
|
-
this.prune();
|
|
2203
|
-
return this.offered;
|
|
2204
|
-
}
|
|
2205
|
-
prune() {
|
|
2206
|
-
const cutoff = this.now() - this.maxAgeMs;
|
|
2207
|
-
for (const [id, at] of this.offered) {
|
|
2208
|
-
const t = Date.parse(at);
|
|
2209
|
-
if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id);
|
|
2210
|
-
}
|
|
2211
|
-
}
|
|
2212
|
-
};
|
|
2213
2711
|
|
|
2214
2712
|
// src/integration/socket.ts
|
|
2215
2713
|
function wakeSourceOf(reason) {
|
|
2216
|
-
|
|
2714
|
+
if (reason === "reminder") return "reminder";
|
|
2715
|
+
if (reason === "unanswered") return "unanswered";
|
|
2716
|
+
return "other";
|
|
2217
2717
|
}
|
|
2218
2718
|
function realtimeOptionsFor(config, extra = {}) {
|
|
2219
2719
|
return {
|
|
@@ -2221,6 +2721,10 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2221
2721
|
baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
|
|
2222
2722
|
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
2223
2723
|
ackOnReceipt: true,
|
|
2724
|
+
// `rewake`: the server re-wakes this socket while cards stay unanswered
|
|
2725
|
+
// (contract v1, D3) — the integration keeps no retry ladder of its own.
|
|
2726
|
+
// `heartbeat` is offered by default (the idle watchdog's proof of life).
|
|
2727
|
+
capabilities: { rewake: true },
|
|
2224
2728
|
reconnect: true,
|
|
2225
2729
|
reconnectInterval: config.reconnect.initialBackoffMs,
|
|
2226
2730
|
maxReconnectInterval: config.reconnect.maxBackoffMs,
|
|
@@ -2229,169 +2733,118 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2229
2733
|
};
|
|
2230
2734
|
}
|
|
2231
2735
|
var IntegrationSocket = class {
|
|
2232
|
-
|
|
2736
|
+
/** The SDK client: handed to the receive loop, which connects and disconnects it. */
|
|
2737
|
+
realtime;
|
|
2233
2738
|
logger;
|
|
2234
2739
|
handlers;
|
|
2235
2740
|
metrics;
|
|
2236
|
-
client;
|
|
2237
|
-
createRealtime;
|
|
2238
|
-
webSocket;
|
|
2239
2741
|
now;
|
|
2240
|
-
|
|
2241
|
-
realtime = null;
|
|
2242
|
-
/** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
|
|
2742
|
+
/** The SDK's state as last reported through its `state` event. */
|
|
2243
2743
|
state = "idle";
|
|
2244
2744
|
connectedAt = null;
|
|
2745
|
+
bound = false;
|
|
2245
2746
|
stopping = false;
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
wakes = 0;
|
|
2249
|
-
invites = 0;
|
|
2747
|
+
unbind = [];
|
|
2748
|
+
wakeFrames = 0;
|
|
2250
2749
|
disconnects = 0;
|
|
2251
2750
|
constructor(options) {
|
|
2252
|
-
this.config = options.config;
|
|
2253
2751
|
this.logger = options.logger.child({ component: "socket" });
|
|
2254
2752
|
this.handlers = options.handlers ?? {};
|
|
2255
2753
|
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2256
|
-
this.client = options.client;
|
|
2257
|
-
this.createRealtime = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
|
|
2258
|
-
this.webSocket = options.webSocket;
|
|
2259
2754
|
this.now = options.now ?? Date.now;
|
|
2260
|
-
|
|
2755
|
+
const create = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
|
|
2756
|
+
this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }));
|
|
2261
2757
|
this.metrics.setConnectionState(this.state);
|
|
2262
2758
|
}
|
|
2263
|
-
/**
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2759
|
+
/** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */
|
|
2760
|
+
bind() {
|
|
2761
|
+
if (this.bound || this.stopping) return;
|
|
2762
|
+
this.bound = true;
|
|
2763
|
+
const realtime = this.realtime;
|
|
2764
|
+
this.unbind.push(
|
|
2765
|
+
realtime.on("state", (next, prev) => this.onState(next, prev)),
|
|
2766
|
+
realtime.onConnect(() => {
|
|
2767
|
+
const at = this.now();
|
|
2768
|
+
this.connectedAt = at;
|
|
2769
|
+
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2770
|
+
this.metrics.incWake({ source: "connect" });
|
|
2771
|
+
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2772
|
+
}),
|
|
2773
|
+
realtime.onDisconnect((info) => {
|
|
2774
|
+
if (this.stopping) return;
|
|
2775
|
+
this.disconnects += 1;
|
|
2776
|
+
this.connectedAt = null;
|
|
2777
|
+
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2778
|
+
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2779
|
+
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2780
|
+
}),
|
|
2781
|
+
realtime.on("blocked", (info) => {
|
|
2782
|
+
if (this.stopping) return;
|
|
2783
|
+
this.metrics.incError({ errorClass: "auth" });
|
|
2784
|
+
this.logger.warn(
|
|
2785
|
+
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2786
|
+
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2787
|
+
);
|
|
2788
|
+
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2789
|
+
}),
|
|
2790
|
+
realtime.onError((error) => {
|
|
2791
|
+
if (this.stopping) return;
|
|
2792
|
+
if (realtime.state === "blocked") {
|
|
2793
|
+
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2794
|
+
return;
|
|
2795
|
+
}
|
|
2796
|
+
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2797
|
+
this.logger.debug({ err: error.message }, "socket error");
|
|
2798
|
+
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2799
|
+
}),
|
|
2800
|
+
// The loop turns a wake frame into a cycle; here it is only labelled
|
|
2801
|
+
// by its reason for the log line and the metric.
|
|
2802
|
+
realtime.on("wake", (frame) => {
|
|
2803
|
+
this.wakeFrames += 1;
|
|
2804
|
+
const payload = frame.payload ?? {};
|
|
2805
|
+
const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : void 0;
|
|
2806
|
+
this.metrics.incWake({ source: wakeSourceOf(payload.reason) });
|
|
2807
|
+
this.logger.info(
|
|
2808
|
+
{
|
|
2809
|
+
reason: payload.reason,
|
|
2810
|
+
step: payload.step,
|
|
2811
|
+
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2812
|
+
...conversations !== void 0 ? { conversations } : {}
|
|
2813
|
+
},
|
|
2814
|
+
"wake \u2014 server wake frame"
|
|
2815
|
+
);
|
|
2816
|
+
})
|
|
2817
|
+
);
|
|
2278
2818
|
}
|
|
2279
|
-
/**
|
|
2280
|
-
|
|
2819
|
+
/** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */
|
|
2820
|
+
stopped() {
|
|
2281
2821
|
this.stopping = true;
|
|
2282
|
-
const realtime = this.realtime;
|
|
2283
|
-
this.realtime = null;
|
|
2284
2822
|
this.connectedAt = null;
|
|
2285
|
-
|
|
2823
|
+
for (const off of this.unbind.splice(0)) {
|
|
2286
2824
|
try {
|
|
2287
|
-
|
|
2288
|
-
} catch
|
|
2289
|
-
this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
|
|
2825
|
+
off();
|
|
2826
|
+
} catch {
|
|
2290
2827
|
}
|
|
2291
2828
|
}
|
|
2292
2829
|
if (this.state !== "stopped") this.onState("stopped", this.state);
|
|
2293
2830
|
}
|
|
2294
2831
|
getHealth() {
|
|
2295
|
-
return {
|
|
2296
|
-
state: this.state,
|
|
2297
|
-
connectedAt: this.connectedAt,
|
|
2298
|
-
counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects }
|
|
2299
|
-
};
|
|
2300
|
-
}
|
|
2301
|
-
// ─── Internals ─────────────────────────────────────────────────────
|
|
2302
|
-
bind(realtime) {
|
|
2303
|
-
realtime.on("state", (next, prev) => this.onState(next, prev));
|
|
2304
|
-
realtime.onConnect(() => {
|
|
2305
|
-
const at = this.now();
|
|
2306
|
-
this.connectedAt = at;
|
|
2307
|
-
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2308
|
-
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2309
|
-
this.wake("connect", {});
|
|
2310
|
-
});
|
|
2311
|
-
realtime.onDisconnect((info) => {
|
|
2312
|
-
if (this.stopping) return;
|
|
2313
|
-
this.disconnects += 1;
|
|
2314
|
-
this.connectedAt = null;
|
|
2315
|
-
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2316
|
-
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2317
|
-
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2318
|
-
});
|
|
2319
|
-
realtime.on("blocked", (info) => {
|
|
2320
|
-
if (this.stopping) return;
|
|
2321
|
-
this.metrics.incError({ errorClass: "auth" });
|
|
2322
|
-
this.logger.warn(
|
|
2323
|
-
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2324
|
-
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2325
|
-
);
|
|
2326
|
-
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2327
|
-
});
|
|
2328
|
-
realtime.onError((error) => {
|
|
2329
|
-
if (this.stopping) return;
|
|
2330
|
-
if (realtime.state === "blocked") {
|
|
2331
|
-
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2332
|
-
return;
|
|
2333
|
-
}
|
|
2334
|
-
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2335
|
-
this.logger.debug({ err: error.message }, "socket error");
|
|
2336
|
-
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2337
|
-
});
|
|
2338
|
-
realtime.on("message.new", (message) => this.onMessageNew(message));
|
|
2339
|
-
realtime.on("wake", (frame) => this.onWakeFrame(frame));
|
|
2340
|
-
realtime.on("group.invite.received", (message) => this.onInvite(message));
|
|
2341
|
-
}
|
|
2342
|
-
onMessageNew(message) {
|
|
2343
|
-
this.frames += 1;
|
|
2344
|
-
const payload = message.payload ?? {};
|
|
2345
|
-
const senderRaw = payload.sender ?? payload.from ?? "";
|
|
2346
|
-
const sender = typeof senderRaw === "string" ? senderRaw.replace(/^@/, "").toLowerCase() : "";
|
|
2347
|
-
const detail = {
|
|
2348
|
-
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2349
|
-
...typeof payload.id === "string" ? { messageId: payload.id } : {},
|
|
2350
|
-
...sender ? { from: sender } : {}
|
|
2351
|
-
};
|
|
2352
|
-
if (this.selfHandle && sender === this.selfHandle) {
|
|
2353
|
-
this.selfFiltered += 1;
|
|
2354
|
-
this.logger.debug(detail, "own echo \u2014 not a wake");
|
|
2355
|
-
return;
|
|
2356
|
-
}
|
|
2357
|
-
this.logger.debug(detail, "wake \u2014 message.new");
|
|
2358
|
-
this.wake("message", detail);
|
|
2359
|
-
}
|
|
2360
|
-
onWakeFrame(frame) {
|
|
2361
|
-
this.frames += 1;
|
|
2362
|
-
const reason = frame.payload?.reason;
|
|
2363
|
-
const detail = { conversationId: frame.payload.conversation_id };
|
|
2364
|
-
this.logger.info({ ...detail, reason, step: frame.payload.step }, "wake \u2014 server wake frame");
|
|
2365
|
-
this.wake(wakeSourceOf(reason), detail);
|
|
2366
|
-
}
|
|
2367
|
-
onInvite(message) {
|
|
2368
|
-
this.frames += 1;
|
|
2369
|
-
const invite = groupInviteFromRecord(message.payload);
|
|
2370
|
-
if (!invite) {
|
|
2371
|
-
this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, "group.invite.received without ids \u2014 dropped");
|
|
2372
|
-
return;
|
|
2373
|
-
}
|
|
2374
|
-
this.invites += 1;
|
|
2375
|
-
this.guard("onGroupInvite", () => this.handlers.onGroupInvite?.(invite));
|
|
2376
|
-
}
|
|
2377
|
-
wake(source, detail) {
|
|
2378
|
-
this.wakes += 1;
|
|
2379
|
-
this.metrics.incWake({ source });
|
|
2380
|
-
this.guard("onWake", () => this.handlers.onWake?.(source, detail));
|
|
2832
|
+
return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } };
|
|
2381
2833
|
}
|
|
2382
2834
|
/** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
|
|
2383
2835
|
onState(next, prev) {
|
|
2836
|
+
if (this.state === next) return;
|
|
2384
2837
|
this.state = next;
|
|
2385
2838
|
this.metrics.setConnectionState(next);
|
|
2386
2839
|
this.logger.debug({ from: prev, to: next }, "socket state");
|
|
2387
2840
|
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2388
2841
|
}
|
|
2389
|
-
/** A failing handler never takes the socket down
|
|
2842
|
+
/** A failing handler never takes the socket down. */
|
|
2390
2843
|
guard(name, fn) {
|
|
2391
2844
|
try {
|
|
2392
2845
|
fn();
|
|
2393
2846
|
} catch (err) {
|
|
2394
|
-
this.logger.error({ err:
|
|
2847
|
+
this.logger.error({ err: describe4(err), handler: name }, "handler threw \u2014 continuing");
|
|
2395
2848
|
}
|
|
2396
2849
|
}
|
|
2397
2850
|
};
|
|
@@ -2402,7 +2855,7 @@ function classifyRealtimeError(error) {
|
|
|
2402
2855
|
if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
|
|
2403
2856
|
return "other";
|
|
2404
2857
|
}
|
|
2405
|
-
function
|
|
2858
|
+
function describe4(err) {
|
|
2406
2859
|
return err instanceof Error ? err.message : String(err);
|
|
2407
2860
|
}
|
|
2408
2861
|
|
|
@@ -2432,8 +2885,6 @@ function registerIntegration(params) {
|
|
|
2432
2885
|
}
|
|
2433
2886
|
let built = null;
|
|
2434
2887
|
const handlers = {
|
|
2435
|
-
onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
|
|
2436
|
-
onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
|
|
2437
2888
|
onConnected: (at) => built?.handlers.onConnected?.(at),
|
|
2438
2889
|
onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
|
|
2439
2890
|
onBlocked: (info) => built?.handlers.onBlocked?.(info),
|
|
@@ -2445,19 +2896,20 @@ function registerIntegration(params) {
|
|
|
2445
2896
|
built = params.build(socket);
|
|
2446
2897
|
const entry = {
|
|
2447
2898
|
socket,
|
|
2448
|
-
|
|
2899
|
+
loop: built.loop,
|
|
2449
2900
|
texts: built.texts ?? null,
|
|
2901
|
+
textsCache: built.textsCache ?? null,
|
|
2450
2902
|
metrics: params.socketOptions?.metrics ?? null,
|
|
2451
2903
|
config: params.config,
|
|
2452
2904
|
logger: params.logger
|
|
2453
2905
|
};
|
|
2454
2906
|
registry.set(params.accountId, entry);
|
|
2907
|
+
socket.bind();
|
|
2455
2908
|
try {
|
|
2456
|
-
await
|
|
2909
|
+
await built.loop?.loop.start();
|
|
2457
2910
|
} catch (err) {
|
|
2458
2911
|
registry.delete(params.accountId);
|
|
2459
|
-
|
|
2460
|
-
built.texts?.stop();
|
|
2912
|
+
await stopEntry(entry);
|
|
2461
2913
|
throw err;
|
|
2462
2914
|
}
|
|
2463
2915
|
return entry;
|
|
@@ -2472,591 +2924,272 @@ function unregisterIntegration(accountId) {
|
|
|
2472
2924
|
});
|
|
2473
2925
|
}
|
|
2474
2926
|
async function stopEntry(entry) {
|
|
2475
|
-
entry.invoker?.stop();
|
|
2476
|
-
entry.texts?.stop();
|
|
2477
2927
|
try {
|
|
2478
|
-
await entry.
|
|
2928
|
+
await entry.loop?.stop();
|
|
2479
2929
|
} catch (err) {
|
|
2480
|
-
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "
|
|
2930
|
+
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "receive loop stop threw during unregister");
|
|
2481
2931
|
}
|
|
2482
|
-
|
|
2483
|
-
function getIntegration(accountId) {
|
|
2484
|
-
return registry.get(accountId);
|
|
2485
|
-
}
|
|
2486
|
-
|
|
2487
|
-
// src/integration/wake.ts
|
|
2488
|
-
var DEFAULT_DEBOUNCE_MS = 2e3;
|
|
2489
|
-
var DEFAULT_MAX_WINDOW_MS = 6e3;
|
|
2490
|
-
var WakeCoalescer = class {
|
|
2491
|
-
onFire;
|
|
2492
|
-
onDelayedWake;
|
|
2493
|
-
debounceMs;
|
|
2494
|
-
maxWindowMs;
|
|
2495
|
-
now;
|
|
2496
|
-
_setTimeout;
|
|
2497
|
-
_clearTimeout;
|
|
2498
|
-
timer = null;
|
|
2499
|
-
burstStartedAt = null;
|
|
2500
|
-
delayed = null;
|
|
2501
|
-
delayedDeadline = null;
|
|
2502
|
-
stopped = false;
|
|
2503
|
-
wakes = 0;
|
|
2504
|
-
absorbed = 0;
|
|
2505
|
-
fires = 0;
|
|
2506
|
-
constructor(options) {
|
|
2507
|
-
const debounce = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
|
2508
|
-
if (!(debounce >= 0)) throw new RangeError("debounceMs must be >= 0");
|
|
2509
|
-
const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS;
|
|
2510
|
-
if (!(maxWindow >= debounce)) throw new RangeError("maxWindowMs must be >= debounceMs");
|
|
2511
|
-
this.onFire = options.onFire;
|
|
2512
|
-
this.onDelayedWake = options.onDelayedWake;
|
|
2513
|
-
this.debounceMs = debounce;
|
|
2514
|
-
this.maxWindowMs = maxWindow;
|
|
2515
|
-
this.now = options.now ?? Date.now;
|
|
2516
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
2517
|
-
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
2518
|
-
}
|
|
2519
|
-
/** True while a debounce timer is armed. */
|
|
2520
|
-
get armed() {
|
|
2521
|
-
return this.timer !== null;
|
|
2522
|
-
}
|
|
2523
|
-
/** True while a retry wake is scheduled and has not fired. */
|
|
2524
|
-
get delayedPending() {
|
|
2525
|
-
return this.delayed !== null;
|
|
2526
|
-
}
|
|
2527
|
-
/**
|
|
2528
|
-
* A wake. The first one of a burst arms the window; every later one is
|
|
2529
|
-
* absorbed and restarts it (trailing edge), never past the burst's cap.
|
|
2530
|
-
*/
|
|
2531
|
-
wake() {
|
|
2532
|
-
if (this.stopped) return;
|
|
2533
|
-
this.wakes += 1;
|
|
2534
|
-
const now = this.now();
|
|
2535
|
-
if (this.timer === null) {
|
|
2536
|
-
this.burstStartedAt = now;
|
|
2537
|
-
this.timer = this._setTimeout(() => this.fire(), this.debounceMs);
|
|
2538
|
-
return;
|
|
2539
|
-
}
|
|
2540
|
-
this.absorbed += 1;
|
|
2541
|
-
const capAt = (this.burstStartedAt ?? now) + this.maxWindowMs;
|
|
2542
|
-
const delay = Math.max(0, Math.min(this.debounceMs, capAt - now));
|
|
2543
|
-
this._clearTimeout(this.timer);
|
|
2544
|
-
this.timer = this._setTimeout(() => this.fire(), delay);
|
|
2545
|
-
}
|
|
2546
|
-
/** A delayed wake (retry ladder). The sooner pending deadline is kept. */
|
|
2547
|
-
wakeAfter(delayMs) {
|
|
2548
|
-
if (this.stopped) return;
|
|
2549
|
-
const delay = Math.max(0, delayMs);
|
|
2550
|
-
const deadline = this.now() + delay;
|
|
2551
|
-
if (this.delayed !== null) {
|
|
2552
|
-
if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {
|
|
2553
|
-
return;
|
|
2554
|
-
}
|
|
2555
|
-
this._clearTimeout(this.delayed);
|
|
2556
|
-
}
|
|
2557
|
-
this.delayedDeadline = deadline;
|
|
2558
|
-
this.delayed = this._setTimeout(() => {
|
|
2559
|
-
this.delayed = null;
|
|
2560
|
-
this.delayedDeadline = null;
|
|
2561
|
-
if (this.stopped) return;
|
|
2562
|
-
try {
|
|
2563
|
-
this.onDelayedWake?.();
|
|
2564
|
-
} catch {
|
|
2565
|
-
}
|
|
2566
|
-
this.wake();
|
|
2567
|
-
}, delay);
|
|
2568
|
-
}
|
|
2569
|
-
/** Cancel everything; later wakes are ignored. */
|
|
2570
|
-
stop() {
|
|
2571
|
-
this.stopped = true;
|
|
2572
|
-
if (this.timer !== null) {
|
|
2573
|
-
this._clearTimeout(this.timer);
|
|
2574
|
-
this.timer = null;
|
|
2575
|
-
this.burstStartedAt = null;
|
|
2576
|
-
}
|
|
2577
|
-
if (this.delayed !== null) {
|
|
2578
|
-
this._clearTimeout(this.delayed);
|
|
2579
|
-
this.delayed = null;
|
|
2580
|
-
this.delayedDeadline = null;
|
|
2581
|
-
}
|
|
2582
|
-
}
|
|
2583
|
-
fire() {
|
|
2584
|
-
this.timer = null;
|
|
2585
|
-
this.burstStartedAt = null;
|
|
2586
|
-
if (this.stopped) return;
|
|
2587
|
-
this.fires += 1;
|
|
2932
|
+
if (!entry.loop) {
|
|
2588
2933
|
try {
|
|
2589
|
-
|
|
2934
|
+
entry.socket.realtime.disconnect();
|
|
2590
2935
|
} catch {
|
|
2591
2936
|
}
|
|
2592
2937
|
}
|
|
2593
|
-
|
|
2938
|
+
entry.socket.stopped();
|
|
2939
|
+
entry.textsCache?.stop();
|
|
2940
|
+
}
|
|
2941
|
+
function getIntegration(accountId) {
|
|
2942
|
+
return registry.get(accountId);
|
|
2943
|
+
}
|
|
2944
|
+
function listActiveAccounts() {
|
|
2945
|
+
return [...registry.keys()];
|
|
2946
|
+
}
|
|
2594
2947
|
|
|
2595
|
-
// src/integration/
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
texts;
|
|
2604
|
-
invites;
|
|
2605
|
-
logger;
|
|
2606
|
-
metrics;
|
|
2607
|
-
readiness;
|
|
2608
|
-
gateEnabled;
|
|
2609
|
-
ladder;
|
|
2610
|
-
now;
|
|
2611
|
-
coalescer;
|
|
2612
|
-
cycleDue = false;
|
|
2613
|
-
running = null;
|
|
2614
|
-
stopped = false;
|
|
2615
|
-
pendingInvites = [];
|
|
2616
|
-
invitesDirty = false;
|
|
2617
|
-
retryRung = 0;
|
|
2618
|
-
turnsInFlight = 0;
|
|
2619
|
-
/**
|
|
2620
|
-
* Conversations whose reply turn is running. Their verdict is recorded
|
|
2621
|
-
* only when the turn completes, so the card stays on the tray meanwhile
|
|
2622
|
-
* and every wake in between would re-gate it and queue a second turn.
|
|
2623
|
-
* Such cards are left out of the cycle; once the turn ends the tray is
|
|
2624
|
-
* read again if any were.
|
|
2625
|
-
*/
|
|
2626
|
-
replyTurnsInFlight = /* @__PURE__ */ new Set();
|
|
2627
|
-
skippedWhileInFlight = false;
|
|
2628
|
-
/** The reason the tools were last found unavailable; logged when it changes, not per wake. */
|
|
2629
|
-
unreadyReason = null;
|
|
2630
|
-
cycles = 0;
|
|
2631
|
-
turns = 0;
|
|
2632
|
-
inviteTurns = 0;
|
|
2633
|
-
constructor(options) {
|
|
2634
|
-
this.accountId = options.accountId;
|
|
2635
|
-
this.agentId = options.agentId;
|
|
2636
|
-
this.client = options.client;
|
|
2637
|
-
this.callModel = options.callModel;
|
|
2638
|
-
this.startTurn = options.startTurn;
|
|
2639
|
-
this.texts = options.texts;
|
|
2640
|
-
this.invites = options.invites;
|
|
2641
|
-
this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
2642
|
-
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2643
|
-
this.readiness = options.readiness ?? (() => ({ ready: true }));
|
|
2644
|
-
this.gateEnabled = options.gateEnabled ?? true;
|
|
2645
|
-
this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
|
|
2646
|
-
this.now = options.now ?? Date.now;
|
|
2647
|
-
this.coalescer = new WakeCoalescer({
|
|
2648
|
-
onFire: () => this.onWakeFired(),
|
|
2649
|
-
onDelayedWake: () => {
|
|
2650
|
-
this.logger.debug({ source: "retry" }, "wake");
|
|
2651
|
-
this.metrics.incWake({ source: "retry" });
|
|
2652
|
-
},
|
|
2653
|
-
debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,
|
|
2654
|
-
now: this.now,
|
|
2655
|
-
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
2656
|
-
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
|
|
2657
|
-
});
|
|
2658
|
-
}
|
|
2659
|
-
// ─── wakes ──────────────────────────────────────────────────────────
|
|
2660
|
-
/** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
|
|
2661
|
-
wake(source) {
|
|
2662
|
-
if (this.stopped) return;
|
|
2663
|
-
this.logger.debug({ source }, "wake");
|
|
2664
|
-
this.coalescer.wake();
|
|
2665
|
-
}
|
|
2666
|
-
/**
|
|
2667
|
-
* The second wake kind. An invite already offered (this process or an
|
|
2668
|
-
* earlier one, per the ledger) or already pending is ignored, so an
|
|
2669
|
-
* invite seen live and again on a connect-time catch-up is decided once.
|
|
2670
|
-
* Returns true when newly queued.
|
|
2671
|
-
*/
|
|
2672
|
-
groupInvite(invite, source) {
|
|
2673
|
-
if (this.stopped) return false;
|
|
2674
|
-
if (this.invites.isOffered(invite.inviteId)) return false;
|
|
2675
|
-
if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false;
|
|
2676
|
-
this.logger.info(
|
|
2677
|
-
{ groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },
|
|
2678
|
-
"group invite \u2014 queuing one invite turn"
|
|
2679
|
-
);
|
|
2680
|
-
this.pendingInvites.push(invite);
|
|
2681
|
-
this.invitesDirty = true;
|
|
2682
|
-
this.schedule();
|
|
2683
|
-
return true;
|
|
2684
|
-
}
|
|
2685
|
-
/** Cancel timers; a cycle in flight finishes on its own. */
|
|
2686
|
-
stop() {
|
|
2687
|
-
this.stopped = true;
|
|
2688
|
-
this.coalescer.stop();
|
|
2689
|
-
}
|
|
2690
|
-
/** The promise of the work currently running, for tests and for graceful stops. */
|
|
2691
|
-
settled() {
|
|
2692
|
-
return this.running ?? Promise.resolve();
|
|
2693
|
-
}
|
|
2694
|
-
counters() {
|
|
2695
|
-
return {
|
|
2696
|
-
cycles: this.cycles,
|
|
2697
|
-
turns: this.turns,
|
|
2698
|
-
inviteTurns: this.inviteTurns,
|
|
2699
|
-
turnsInFlight: this.turnsInFlight,
|
|
2700
|
-
wakes: this.coalescer.wakes,
|
|
2701
|
-
absorbed: this.coalescer.absorbed,
|
|
2702
|
-
retryRung: this.retryRung,
|
|
2703
|
-
pendingInvites: this.pendingInvites.length
|
|
2704
|
-
};
|
|
2705
|
-
}
|
|
2706
|
-
// ─── worker ─────────────────────────────────────────────────────────
|
|
2707
|
-
onWakeFired() {
|
|
2708
|
-
this.cycleDue = true;
|
|
2709
|
-
if (this.pendingInvites.length > 0) this.invitesDirty = true;
|
|
2710
|
-
this.schedule();
|
|
2711
|
-
}
|
|
2712
|
-
/** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
|
|
2713
|
-
schedule() {
|
|
2714
|
-
if (this.running) return;
|
|
2715
|
-
this.running = this.drain().finally(() => {
|
|
2716
|
-
this.running = null;
|
|
2717
|
-
if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule();
|
|
2718
|
-
});
|
|
2719
|
-
}
|
|
2720
|
-
async drain() {
|
|
2721
|
-
while (!this.stopped) {
|
|
2722
|
-
if (this.invitesDirty) {
|
|
2723
|
-
this.invitesDirty = false;
|
|
2724
|
-
await this.runInviteTurns();
|
|
2725
|
-
continue;
|
|
2726
|
-
}
|
|
2727
|
-
if (this.cycleDue) {
|
|
2728
|
-
this.cycleDue = false;
|
|
2729
|
-
try {
|
|
2730
|
-
await this.runCycle();
|
|
2731
|
-
} catch (err) {
|
|
2732
|
-
this.logger.error({ err: describe4(err), ...this.retry() }, "cycle failed with an unhandled error \u2014 re-waking later");
|
|
2733
|
-
}
|
|
2734
|
-
continue;
|
|
2735
|
-
}
|
|
2736
|
-
return;
|
|
2737
|
-
}
|
|
2738
|
-
}
|
|
2739
|
-
// ─── one cycle ──────────────────────────────────────────────────────
|
|
2740
|
-
/** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
|
|
2741
|
-
async runCycle() {
|
|
2742
|
-
this.cycles += 1;
|
|
2743
|
-
const started = this.now();
|
|
2744
|
-
let tray;
|
|
2745
|
-
try {
|
|
2746
|
-
tray = await this.client.inbox.tray({ waitMs: 0 });
|
|
2747
|
-
} catch (err) {
|
|
2748
|
-
this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
|
|
2749
|
-
return this.result("tray_failed", 0, false, started, describe4(err));
|
|
2750
|
-
}
|
|
2751
|
-
const allCards = agentchatme.gate.cardsOf(tray);
|
|
2752
|
-
const truncated = tray.truncated === true;
|
|
2753
|
-
if (allCards.length === 0) {
|
|
2754
|
-
this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
|
|
2755
|
-
this.retryRung = 0;
|
|
2756
|
-
return this.result("empty", 0, truncated, started);
|
|
2757
|
-
}
|
|
2758
|
-
const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id));
|
|
2759
|
-
const skippedInFlight = allCards.length - cards.length;
|
|
2760
|
-
if (skippedInFlight > 0) this.skippedWhileInFlight = true;
|
|
2761
|
-
if (cards.length === 0) {
|
|
2762
|
-
this.logger.info({ skippedInFlight }, "every card on the tray has a reply turn running \u2014 nothing new to decide");
|
|
2763
|
-
return { ...this.result("empty", 0, truncated, started), skippedInFlight };
|
|
2764
|
-
}
|
|
2765
|
-
const texts = await this.texts.ensure();
|
|
2766
|
-
if (!texts) {
|
|
2767
|
-
this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
2768
|
-
return { ...this.result("texts_missing", cards.length, truncated, started, "texts missing"), skippedInFlight };
|
|
2769
|
-
}
|
|
2770
|
-
const readiness = this.readiness();
|
|
2771
|
-
if (!readiness.ready) {
|
|
2772
|
-
const changed = this.unreadyReason !== readiness.reason;
|
|
2773
|
-
this.unreadyReason = readiness.reason;
|
|
2774
|
-
this.logger[changed ? "warn" : "debug"]({ cards: cards.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 not gating; the cards wait on the tray");
|
|
2775
|
-
return { ...this.result("tools_unavailable", cards.length, truncated, started, readiness.reason), skippedInFlight };
|
|
2776
|
-
}
|
|
2777
|
-
if (this.unreadyReason !== null) {
|
|
2778
|
-
this.unreadyReason = null;
|
|
2779
|
-
this.logger.info({}, "AgentChat tools available to turns again");
|
|
2780
|
-
}
|
|
2781
|
-
let result;
|
|
2782
|
-
if (!this.gateEnabled) {
|
|
2783
|
-
result = await this.runUngated(cards.length, texts, truncated, started);
|
|
2784
|
-
} else {
|
|
2785
|
-
const trayToGate = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray;
|
|
2786
|
-
result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight);
|
|
2787
|
-
}
|
|
2788
|
-
if (skippedInFlight > 0) result = { ...result, skippedInFlight };
|
|
2789
|
-
if (truncated && result.outcome !== "fail_closed") {
|
|
2790
|
-
this.logger.info({}, "tray truncated \u2014 waking again for the rest");
|
|
2791
|
-
this.coalescer.wake();
|
|
2792
|
-
}
|
|
2793
|
-
return result;
|
|
2794
|
-
}
|
|
2795
|
-
/** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
|
|
2796
|
-
async runUngated(cards, texts, truncated, started) {
|
|
2797
|
-
this.logger.info({ cards }, "gate off \u2014 starting one turn with the served wake instruction");
|
|
2798
|
-
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2799
|
-
this.logger.info({ sessionKey }, "turn start");
|
|
2800
|
-
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2948
|
+
// src/integration/turns.ts
|
|
2949
|
+
function createLoopTurnStarter(options) {
|
|
2950
|
+
const now = options.now ?? Date.now;
|
|
2951
|
+
return async (request) => {
|
|
2952
|
+
const id = request.kind === "reply" ? request.conversationId : request.invite.invite_id;
|
|
2953
|
+
const sessionKey = request.kind === "reply" ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now());
|
|
2954
|
+
const watch = options.turns.admission(request.kind, id);
|
|
2955
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
2801
2956
|
if (!admission.ran) {
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
}
|
|
2826
|
-
let turnsStarted = 0;
|
|
2827
|
-
let turnsRefused = 0;
|
|
2828
|
-
const recordFailures = decided.recordFailures.length;
|
|
2829
|
-
const recorded = decided.recorded;
|
|
2830
|
-
for (const entry of decided.reply) {
|
|
2831
|
-
if (this.replyTurnsInFlight.has(entry.conversationId)) {
|
|
2832
|
-
this.skippedWhileInFlight = true;
|
|
2833
|
-
continue;
|
|
2834
|
-
}
|
|
2835
|
-
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2836
|
-
this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
|
|
2837
|
-
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
|
|
2838
|
-
if (!admission.ran) {
|
|
2839
|
-
turnsRefused += 1;
|
|
2840
|
-
this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, "turn not started \u2014 reply not recorded; the conversation stays unread");
|
|
2841
|
-
continue;
|
|
2957
|
+
options.turns.admitted(watch);
|
|
2958
|
+
return { started: false, error: admission.error };
|
|
2959
|
+
}
|
|
2960
|
+
options.turns.started({
|
|
2961
|
+
runId: admission.runId,
|
|
2962
|
+
kind: request.kind,
|
|
2963
|
+
id,
|
|
2964
|
+
anchor: request.kind === "reply" ? request.anchor : null,
|
|
2965
|
+
sessionKey: admission.sessionKey,
|
|
2966
|
+
startedAt: now(),
|
|
2967
|
+
owner: options.owner,
|
|
2968
|
+
// What the after-turn rule compares when the turn ends outside the
|
|
2969
|
+
// kit's watch (handed off, or after a restart).
|
|
2970
|
+
...request.kind === "reply" ? { card: request.card, category: request.category } : { invite: request.invite }
|
|
2971
|
+
}, { admission: watch });
|
|
2972
|
+
options.logger.info(
|
|
2973
|
+
{ kind: request.kind, sessionKey, runId: admission.runId, ...request.kind === "reply" ? { conversationId: id } : { inviteId: id } },
|
|
2974
|
+
request.kind === "reply" ? "turn start" : "group-invite turn start"
|
|
2975
|
+
);
|
|
2976
|
+
const done = admission.done.then((outcome) => {
|
|
2977
|
+
if (outcome.status === "gone") {
|
|
2978
|
+
options.logger.warn({ sessionKey, runId: outcome.runId }, "turn end not confirmed: the plugin runtime is gone \u2014 its card stays held");
|
|
2979
|
+
return { status: "still_running", detail: "the plugin runtime is gone" };
|
|
2842
2980
|
}
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2981
|
+
const end = turnEndOf(outcome);
|
|
2982
|
+
void options.turns.ended(admission.runId, end);
|
|
2983
|
+
options.logger[outcome.status === "ok" ? "info" : "warn"](
|
|
2984
|
+
{
|
|
2985
|
+
sessionKey,
|
|
2986
|
+
runId: outcome.runId,
|
|
2987
|
+
status: outcome.status,
|
|
2988
|
+
...outcome.error ? { error: outcome.error } : {},
|
|
2989
|
+
...outcome.elapsedMs !== void 0 ? { elapsedMs: outcome.elapsedMs } : {},
|
|
2990
|
+
agentchatCalls: outcome.agentchatCalls ?? null
|
|
2991
|
+
},
|
|
2992
|
+
request.kind === "reply" ? "turn ended (final text discarded; the send is a hosted-tool call)" : "group-invite turn ended"
|
|
2993
|
+
);
|
|
2994
|
+
return end;
|
|
2995
|
+
});
|
|
2996
|
+
return { started: true, done };
|
|
2997
|
+
};
|
|
2998
|
+
}
|
|
2999
|
+
function turnEndOf(outcome) {
|
|
3000
|
+
const agentchatCalls = outcome.agentchatCalls ?? null;
|
|
3001
|
+
if (outcome.status === "ok" && !outcome.error) return { status: "completed", agentchatCalls };
|
|
3002
|
+
return { status: "failed", agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? "unknown"}` };
|
|
3003
|
+
}
|
|
3004
|
+
|
|
3005
|
+
// src/integration/loop.ts
|
|
3006
|
+
var generation = 0;
|
|
3007
|
+
function createIntegrationLoop(options) {
|
|
3008
|
+
const logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
3009
|
+
const metrics = options.metrics ?? createNoopMetrics();
|
|
3010
|
+
const now = options.now ?? Date.now;
|
|
3011
|
+
generation += 1;
|
|
3012
|
+
const owner = `${options.accountId}#${generation}`;
|
|
3013
|
+
const gateEnabled = options.gateEnabled ?? true;
|
|
3014
|
+
let unreadyReason = null;
|
|
3015
|
+
const readiness = options.readiness ? () => {
|
|
3016
|
+
const ready = options.readiness();
|
|
3017
|
+
if (ready.ready) {
|
|
3018
|
+
if (unreadyReason !== null) logger.info({}, "turns can start again \u2014 gating resumes");
|
|
3019
|
+
unreadyReason = null;
|
|
3020
|
+
return ready;
|
|
3021
|
+
}
|
|
3022
|
+
if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, "not gating \u2014 no turn can start now; the cards wait on the tray");
|
|
3023
|
+
unreadyReason = ready.reason;
|
|
3024
|
+
return ready;
|
|
3025
|
+
} : void 0;
|
|
3026
|
+
const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now });
|
|
3027
|
+
const loop = new agentchatme.integration.ReceiveLoop({
|
|
3028
|
+
client: options.client,
|
|
3029
|
+
texts: options.texts,
|
|
3030
|
+
mode: gateEnabled ? "gateCall" : "singleRun",
|
|
3031
|
+
...gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) },
|
|
3032
|
+
socket: options.socket,
|
|
3033
|
+
...options.handle ? { handle: options.handle } : {},
|
|
3034
|
+
toolNamer: OPENCLAW_TOOL_NAMER,
|
|
3035
|
+
// One account's turns run on one OpenClaw lane anyway; one slot keeps
|
|
3036
|
+
// the rest held out of the gate (no second model call decides them).
|
|
3037
|
+
maxConcurrentTurns: 1,
|
|
3038
|
+
tracker: options.turns.tracker,
|
|
3039
|
+
...readiness ? { readiness } : {},
|
|
3040
|
+
...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {},
|
|
3041
|
+
...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
|
|
3042
|
+
...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
|
|
3043
|
+
now,
|
|
3044
|
+
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
3045
|
+
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {},
|
|
3046
|
+
onEvent: (event) => logEvent(event, logger, metrics)
|
|
3047
|
+
});
|
|
3048
|
+
const inLoopContext = async_hooks.AsyncLocalStorage.snapshot();
|
|
3049
|
+
options.turns.setLive(
|
|
3050
|
+
owner,
|
|
3051
|
+
() => inLoopContext(() => loop.wake()),
|
|
3052
|
+
(fn) => inLoopContext(fn)
|
|
3053
|
+
);
|
|
3054
|
+
return {
|
|
3055
|
+
loop,
|
|
3056
|
+
async stop() {
|
|
3057
|
+
options.turns.clearLive(owner);
|
|
3058
|
+
await loop.stop();
|
|
2867
3059
|
}
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
skippedInFlight: 0,
|
|
2883
|
-
truncated,
|
|
2884
|
-
latencyMs: this.now() - started,
|
|
2885
|
-
failure
|
|
3060
|
+
};
|
|
3061
|
+
}
|
|
3062
|
+
function singleRunStarter(options, owner, logger, now) {
|
|
3063
|
+
return async (request) => {
|
|
3064
|
+
const hung = options.turns.hungSingleRun();
|
|
3065
|
+
if (hung) {
|
|
3066
|
+
logger.warn({ runId: hung.runId }, "gate off \u2014 a handed-off run is still going; no second run while it lives (the cards wait on the tray)");
|
|
3067
|
+
return { status: "not_started", detail: `the gate-off run ${hung.runId} is still going` };
|
|
3068
|
+
}
|
|
3069
|
+
const sessionKey = wakeSessionKey(options.agentId, now());
|
|
3070
|
+
logger.info({ sessionKey, cards: request.cards, invites: request.invites }, "gate off \u2014 one run with the served wake instruction");
|
|
3071
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
3072
|
+
if (!admission.ran) return { status: "not_started", detail: admission.error };
|
|
3073
|
+
let letGo = () => {
|
|
2886
3074
|
};
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
3075
|
+
const handedOff = new Promise((resolve) => {
|
|
3076
|
+
letGo = () => resolve("let_go");
|
|
3077
|
+
});
|
|
3078
|
+
const { runId } = admission;
|
|
3079
|
+
options.turns.started({ runId, kind: "run", id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo });
|
|
3080
|
+
const ended = admission.done.then((outcome) => {
|
|
3081
|
+
if (outcome.status !== "gone") void options.turns.ended(runId);
|
|
3082
|
+
logger[outcome.status === "ok" ? "info" : "warn"]({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, "gate off \u2014 run ended");
|
|
3083
|
+
return outcome;
|
|
3084
|
+
});
|
|
3085
|
+
const first = await Promise.race([ended, handedOff]);
|
|
3086
|
+
if (first === "let_go") {
|
|
3087
|
+
logger.warn({ sessionKey, runId }, "gate off \u2014 the run is still going after 30 min; no new run starts until it ends (or `openclaw agentchat release <run id> --force`)");
|
|
3088
|
+
return { status: "failed", detail: "the run was handed off while still going" };
|
|
2895
3089
|
}
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
this.replyTurnEnded(reply.conversationId);
|
|
3090
|
+
return first.status === "ok" && !first.error ? { status: "completed" } : { status: "failed", detail: first.error ?? `run ended: ${first.status ?? "unknown"}` };
|
|
3091
|
+
};
|
|
3092
|
+
}
|
|
3093
|
+
function logEvent(event, logger, metrics) {
|
|
3094
|
+
switch (event.type) {
|
|
3095
|
+
case "wake":
|
|
3096
|
+
if (event.source === "message") metrics.incWake({ source: "message" });
|
|
3097
|
+
else if (event.source === "invite") metrics.incWake({ source: "invite" });
|
|
3098
|
+
logger.debug({ source: event.source, ...event.conversationId ? { conversationId: event.conversationId } : {} }, "wake");
|
|
3099
|
+
return;
|
|
3100
|
+
case "echo":
|
|
3101
|
+
logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
|
|
3102
|
+
return;
|
|
3103
|
+
case "cycle": {
|
|
3104
|
+
const s = event.summary;
|
|
3105
|
+
const fields = {
|
|
3106
|
+
outcome: s.outcome,
|
|
3107
|
+
cards: s.cards,
|
|
3108
|
+
invites: s.invites,
|
|
3109
|
+
reply: s.reply,
|
|
3110
|
+
dismiss: s.dismiss,
|
|
3111
|
+
defer: s.defer,
|
|
3112
|
+
undecided: s.undecided,
|
|
3113
|
+
recordFailures: s.recordFailures,
|
|
3114
|
+
turnsStarted: s.turnsStarted,
|
|
3115
|
+
turnsRefused: s.turnsRefused,
|
|
3116
|
+
heldByTurns: s.heldByTurns,
|
|
3117
|
+
...s.truncated ? { truncated: true } : {},
|
|
3118
|
+
...s.failure ? { failure: s.failure } : {}
|
|
3119
|
+
};
|
|
3120
|
+
switch (s.outcome) {
|
|
3121
|
+
case "empty":
|
|
3122
|
+
logger.info({}, "tray empty \u2014 nothing to decide");
|
|
3123
|
+
return;
|
|
3124
|
+
case "nothing_owed":
|
|
3125
|
+
logger.info(fields, "nothing new to decide (muted cards, or cards a running turn holds)");
|
|
3126
|
+
return;
|
|
3127
|
+
case "fail_closed":
|
|
3128
|
+
logger.warn(fields, "gate failed closed \u2014 nothing recorded, no turn started; the server re-wakes");
|
|
3129
|
+
return;
|
|
3130
|
+
case "tray_failed":
|
|
3131
|
+
logger.warn(fields, "tray read failed \u2014 the cards stay on the tray; the server re-wakes");
|
|
3132
|
+
return;
|
|
3133
|
+
case "texts_missing":
|
|
3134
|
+
logger.warn(fields, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
3135
|
+
return;
|
|
3136
|
+
case "tools_unavailable":
|
|
3137
|
+
logger.debug(fields, "not gating \u2014 no turn can start now");
|
|
3138
|
+
return;
|
|
3139
|
+
case "abandoned":
|
|
3140
|
+
logger.warn(fields, "cycle abandoned \u2014 it ran past its deadline; nothing more is done for it, the next wake starts a new one");
|
|
3141
|
+
return;
|
|
3142
|
+
default: {
|
|
3143
|
+
const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0;
|
|
3144
|
+
logger[incomplete ? "warn" : "info"](fields, incomplete ? "gate \u2014 some cards were left on the tray; the server re-wakes" : "gate");
|
|
3145
|
+
return;
|
|
2953
3146
|
}
|
|
2954
3147
|
}
|
|
2955
|
-
);
|
|
2956
|
-
}
|
|
2957
|
-
/** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
|
|
2958
|
-
replyTurnEnded(conversationId) {
|
|
2959
|
-
this.replyTurnsInFlight.delete(conversationId);
|
|
2960
|
-
if (this.skippedWhileInFlight && !this.stopped) {
|
|
2961
|
-
this.skippedWhileInFlight = false;
|
|
2962
|
-
this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
|
|
2963
|
-
this.coalescer.wake();
|
|
2964
|
-
}
|
|
2965
|
-
}
|
|
2966
|
-
/**
|
|
2967
|
-
* Whether the completed turn recorded a verdict for its conversation
|
|
2968
|
-
* itself, seen on one fresh tray read. A card that left the tray was read
|
|
2969
|
-
* (a verdict or a mark-read) or hidden by a `defer` — by the turn, since
|
|
2970
|
-
* the host had recorded nothing for it. A card still there whose
|
|
2971
|
-
* `your_last_decision` differs from the gate's copy got a verdict in the
|
|
2972
|
-
* turn (a newer message keeps it on the tray). A card still there,
|
|
2973
|
-
* unchanged, got nothing. A failed read, or a missing card past a
|
|
2974
|
-
* truncated tray, claims nothing: `reply` is recorded as before.
|
|
2975
|
-
*/
|
|
2976
|
-
async decidedInTurn(reply) {
|
|
2977
|
-
let tray;
|
|
2978
|
-
try {
|
|
2979
|
-
tray = await this.client.inbox.tray({ waitMs: 0, limit: POST_TURN_TRAY_LIMIT });
|
|
2980
|
-
} catch (err) {
|
|
2981
|
-
this.logger.info({ conversationId: reply.conversationId, err: describe4(err) }, "tray re-read after the turn failed \u2014 recording reply");
|
|
2982
|
-
return false;
|
|
2983
3148
|
}
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
{ sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
|
|
2996
|
-
"reply verdict not recorded after the turn completed \u2014 the conversation stays unread; the next wake gates it again"
|
|
3149
|
+
case "turn_started":
|
|
3150
|
+
return;
|
|
3151
|
+
// the turn starter logs it with the OpenClaw session and run
|
|
3152
|
+
case "turn_refused":
|
|
3153
|
+
logger.warn({ kind: event.kind, id: event.id, error: event.error }, "turn not started \u2014 nothing recorded; the card stays on the tray");
|
|
3154
|
+
return;
|
|
3155
|
+
case "turn_outcome": {
|
|
3156
|
+
const o = event.outcome;
|
|
3157
|
+
logger.info(
|
|
3158
|
+
{ conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...o.action !== "none" ? { through: o.throughMessageId } : {} },
|
|
3159
|
+
event.recorded ? `${o.action === "record_reply" ? "reply" : "dismiss"} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`
|
|
2997
3160
|
);
|
|
3161
|
+
return;
|
|
2998
3162
|
}
|
|
3163
|
+
case "invite_outcome":
|
|
3164
|
+
logger.info(
|
|
3165
|
+
{ inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },
|
|
3166
|
+
event.recorded ? "invite dismissed after a second silent turn (left pending)" : `nothing recorded for the invite (${event.outcome.reason})`
|
|
3167
|
+
);
|
|
3168
|
+
return;
|
|
3169
|
+
case "run":
|
|
3170
|
+
return;
|
|
3171
|
+
// single-run mode logs the run itself
|
|
3172
|
+
case "error":
|
|
3173
|
+
logger.debug({ err: event.error.message }, "receive loop notice");
|
|
3174
|
+
return;
|
|
2999
3175
|
}
|
|
3000
|
-
/**
|
|
3001
|
-
* Every pending invite gets one attempt. An invite leaves the pending list
|
|
3002
|
-
* only once its turn was admitted (and is then remembered in the ledger);
|
|
3003
|
-
* a refused one stays there for the next wake. Invites that arrive while
|
|
3004
|
-
* this runs are appended and get their pass on the next drain.
|
|
3005
|
-
*/
|
|
3006
|
-
async runInviteTurns() {
|
|
3007
|
-
const batch = [...this.pendingInvites];
|
|
3008
|
-
if (batch.length > 0) {
|
|
3009
|
-
const readiness = this.readiness();
|
|
3010
|
-
if (!readiness.ready) {
|
|
3011
|
-
const changed = this.unreadyReason !== readiness.reason;
|
|
3012
|
-
this.unreadyReason = readiness.reason;
|
|
3013
|
-
this.logger[changed ? "warn" : "debug"]({ pending: batch.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 invite turns wait; re-waking later");
|
|
3014
|
-
return;
|
|
3015
|
-
}
|
|
3016
|
-
}
|
|
3017
|
-
let texts = null;
|
|
3018
|
-
let refused = 0;
|
|
3019
|
-
let waitingForTexts = 0;
|
|
3020
|
-
for (const invite of batch) {
|
|
3021
|
-
if (this.stopped) return;
|
|
3022
|
-
texts ??= await this.texts.ensure();
|
|
3023
|
-
if (!texts) {
|
|
3024
|
-
waitingForTexts = batch.length;
|
|
3025
|
-
break;
|
|
3026
|
-
}
|
|
3027
|
-
const sessionKey = inviteSessionKey(this.agentId, invite.inviteId);
|
|
3028
|
-
this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, "group-invite turn start");
|
|
3029
|
-
let admission;
|
|
3030
|
-
try {
|
|
3031
|
-
admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
3032
|
-
} catch (err) {
|
|
3033
|
-
admission = { ran: false, error: describe4(err) };
|
|
3034
|
-
}
|
|
3035
|
-
if (!admission.ran) {
|
|
3036
|
-
refused += 1;
|
|
3037
|
-
this.logger.warn({ sessionKey, inviteId: invite.inviteId, error: admission.error }, "group-invite turn not started \u2014 the invite stays pending; retried on the next wake");
|
|
3038
|
-
continue;
|
|
3039
|
-
}
|
|
3040
|
-
this.inviteTurns += 1;
|
|
3041
|
-
this.invites.markOffered(invite.inviteId);
|
|
3042
|
-
this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId);
|
|
3043
|
-
this.admitted(sessionKey, admission, "group-invite turn complete");
|
|
3044
|
-
}
|
|
3045
|
-
if (this.stopped) return;
|
|
3046
|
-
if (waitingForTexts > 0) {
|
|
3047
|
-
this.logger.warn({ pending: waitingForTexts, ...this.retry() }, "served texts not available \u2014 invite turns wait; re-waking later");
|
|
3048
|
-
} else if (refused > 0) {
|
|
3049
|
-
this.logger.warn({ pending: refused, ...this.retry() }, "invite turns refused \u2014 re-waking later");
|
|
3050
|
-
}
|
|
3051
|
-
}
|
|
3052
|
-
};
|
|
3053
|
-
var POST_TURN_TRAY_LIMIT = 50;
|
|
3054
|
-
function lastDecisionAt(card) {
|
|
3055
|
-
const at = card.your_last_decision?.at;
|
|
3056
|
-
return typeof at === "string" && at.length > 0 ? at : null;
|
|
3057
3176
|
}
|
|
3058
|
-
|
|
3059
|
-
|
|
3177
|
+
var TROUBLE_OUTCOMES = /* @__PURE__ */ new Set(["fail_closed", "tools_unavailable", "texts_missing", "abandoned"]);
|
|
3178
|
+
var CYCLE_TROUBLE_RUN = 3;
|
|
3179
|
+
var TROUBLE_MEANING = {
|
|
3180
|
+
fail_closed: "the gate call failed (model unreachable, too slow, or nothing usable)",
|
|
3181
|
+
tools_unavailable: "no turn could have the hosted tools",
|
|
3182
|
+
texts_missing: "the served texts are not available",
|
|
3183
|
+
abandoned: "the cycle ran past its deadline and was abandoned"
|
|
3184
|
+
};
|
|
3185
|
+
function cycleTroubleLine(recentCycles) {
|
|
3186
|
+
let run = 0;
|
|
3187
|
+
for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i].outcome); i -= 1) run += 1;
|
|
3188
|
+
if (run < CYCLE_TROUBLE_RUN) return null;
|
|
3189
|
+
const last = recentCycles[recentCycles.length - 1];
|
|
3190
|
+
const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))];
|
|
3191
|
+
const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join("; ");
|
|
3192
|
+
return `the last ${run} cycles decided nothing (${kinds.join(", ")}): ${meaning}${last.failure ? ` \u2014 latest: ${last.failure}` : ""}; the cards wait on the tray and AgentChat re-wakes them`;
|
|
3060
3193
|
}
|
|
3061
3194
|
function adaptLog(log) {
|
|
3062
3195
|
if (!log) return void 0;
|
|
@@ -3114,7 +3247,7 @@ var agentchatGatewayAdapter = {
|
|
|
3114
3247
|
}
|
|
3115
3248
|
if (readEnv_js.readLegacyReplyGateFailOpenFromEnv()) {
|
|
3116
3249
|
ctx.log?.warn?.(
|
|
3117
|
-
`[agentchat:${ctx.accountId}] ${readEnv_js.LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured \u2014 a gate that cannot run fails closed (nothing recorded, no turn)
|
|
3250
|
+
`[agentchat:${ctx.accountId}] ${readEnv_js.LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured \u2014 a gate that cannot run fails closed (nothing recorded, no turn); the server re-wakes the cards`
|
|
3118
3251
|
);
|
|
3119
3252
|
}
|
|
3120
3253
|
const refusal = multiAccountRefusal(ctx.cfg);
|
|
@@ -3136,20 +3269,57 @@ var agentchatGatewayAdapter = {
|
|
|
3136
3269
|
}
|
|
3137
3270
|
const client = getClient({ accountId: ctx.accountId, config });
|
|
3138
3271
|
const gateTimeoutMs = readEnv_js.readReplyGateTimeoutMsFromEnv();
|
|
3139
|
-
const
|
|
3272
|
+
const overdueWarned = /* @__PURE__ */ new Map();
|
|
3273
|
+
const turns = accountTurns(ctx.accountId);
|
|
3274
|
+
const reportOverdue = (runId, kind, id, elapsedMs, handed) => {
|
|
3275
|
+
const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS);
|
|
3276
|
+
if (!handed && overdueWarned.get(runId) === mark) return;
|
|
3277
|
+
overdueWarned.set(runId, mark);
|
|
3278
|
+
ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`);
|
|
3279
|
+
};
|
|
3280
|
+
const onStillRunning = ({ runId, sessionKey, elapsedMs }) => {
|
|
3281
|
+
const run = turns.run(runId);
|
|
3282
|
+
if (turns.stateOf(runId) === "released") {
|
|
3283
|
+
logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4) }, "released turn still running in OpenClaw \u2014 it holds nothing");
|
|
3284
|
+
return;
|
|
3285
|
+
}
|
|
3286
|
+
logger.info(
|
|
3287
|
+
{ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4), ...run ? { [run.kind === "reply" ? "conversationId" : run.kind === "invite" ? "inviteId" : "run"]: run.id } : {} },
|
|
3288
|
+
"turn still running \u2014 its conversation stays in flight until OpenClaw reports the run ended"
|
|
3289
|
+
);
|
|
3290
|
+
if (!run || !isOverdue(elapsedMs)) return;
|
|
3291
|
+
const handed = turns.handOff(runId) !== null;
|
|
3292
|
+
reportOverdue(runId, run.kind, run.id, elapsedMs, handed);
|
|
3293
|
+
};
|
|
3294
|
+
const watchRun = createRunWatcher({ onStillRunning });
|
|
3295
|
+
turns.configure({
|
|
3296
|
+
recorder: createAfterTurnRecorder({ client, logger }),
|
|
3297
|
+
store: new TurnStore(ctx.accountId),
|
|
3298
|
+
watch: async (record) => {
|
|
3299
|
+
const outcome = await watchRun(record);
|
|
3300
|
+
return outcome ? turnEndOf(outcome) : null;
|
|
3301
|
+
},
|
|
3302
|
+
readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),
|
|
3303
|
+
logger
|
|
3304
|
+
});
|
|
3305
|
+
turns.adopt();
|
|
3306
|
+
for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`);
|
|
3307
|
+
for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, "removed a file an earlier release kept (no longer used)");
|
|
3308
|
+
const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger });
|
|
3309
|
+
const texts = new OpenClawTexts(textsCache);
|
|
3310
|
+
const first = await textsCache.start();
|
|
3311
|
+
if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, "served texts in hand");
|
|
3312
|
+
else logger.warn({ err: textsCache.lastError }, "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 nothing is gated until the first copy arrives");
|
|
3140
3313
|
const handle = config.agentHandle;
|
|
3141
3314
|
if (handle) {
|
|
3142
|
-
|
|
3143
|
-
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
|
|
3315
|
+
const refresh = (copy) => {
|
|
3316
|
+
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(copy).identity_line);
|
|
3144
3317
|
if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
|
|
3145
3318
|
else if (refreshed.outcome === "failed") ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? "unknown error"}`);
|
|
3146
|
-
}
|
|
3319
|
+
};
|
|
3320
|
+
if (first) refresh(first);
|
|
3321
|
+
textsCache.onChange((copy) => refresh(copy));
|
|
3147
3322
|
}
|
|
3148
|
-
await texts.start();
|
|
3149
|
-
const invites = new InviteLedger({
|
|
3150
|
-
accountId: ctx.accountId,
|
|
3151
|
-
onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
|
|
3152
|
-
});
|
|
3153
3323
|
const metrics = createInMemoryMetrics();
|
|
3154
3324
|
await registerIntegration({
|
|
3155
3325
|
accountId: ctx.accountId,
|
|
@@ -3157,33 +3327,44 @@ var agentchatGatewayAdapter = {
|
|
|
3157
3327
|
logger,
|
|
3158
3328
|
socketOptions: { client, metrics },
|
|
3159
3329
|
build: (socket) => {
|
|
3160
|
-
const
|
|
3330
|
+
const loop = createIntegrationLoop({
|
|
3161
3331
|
accountId: ctx.accountId,
|
|
3162
3332
|
agentId,
|
|
3163
3333
|
client,
|
|
3334
|
+
texts,
|
|
3335
|
+
socket: socket.realtime,
|
|
3336
|
+
handle: config.agentHandle,
|
|
3164
3337
|
callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
|
|
3165
|
-
|
|
3338
|
+
// A turn holds its conversation until OpenClaw confirms its run
|
|
3339
|
+
// ended; a wait that elapses is asked again (`integration/run.ts`).
|
|
3340
|
+
startRun: createRuntimeTurnStarter({
|
|
3341
|
+
onStillRunning,
|
|
3342
|
+
onWaitError: ({ runId, sessionKey, error, attempt, retryInMs }) => logger[attempt === 1 ? "warn" : "debug"]({ runId, sessionKey, error, attempt, retryInMs }, "waiting for the turn to end failed \u2014 asking OpenClaw again")
|
|
3343
|
+
}),
|
|
3166
3344
|
// Gating waits until a turn can have the hosted tools (the MCP
|
|
3167
3345
|
// entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
|
|
3168
3346
|
// its key in this process): a connect wake on a cold gateway
|
|
3169
3347
|
// otherwise spends a gate call and runs a turn that cannot look.
|
|
3170
3348
|
readiness: () => {
|
|
3171
3349
|
const live = readLiveConfig(ctx.cfg);
|
|
3350
|
+
const hung = hungTurnsReason(turns, live.cfg);
|
|
3351
|
+
if (hung) return { ready: false, reason: hung };
|
|
3172
3352
|
return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
|
|
3173
3353
|
},
|
|
3174
|
-
|
|
3175
|
-
|
|
3354
|
+
// The account's runs outlive this loop: a config change restarts
|
|
3355
|
+
// the account while its runs go on in OpenClaw, so every loop for
|
|
3356
|
+
// the account shares the same turns (and the kit tracker in them).
|
|
3357
|
+
turns,
|
|
3176
3358
|
logger,
|
|
3177
3359
|
metrics,
|
|
3178
3360
|
gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
|
|
3179
3361
|
});
|
|
3180
3362
|
let blocked = false;
|
|
3181
3363
|
return {
|
|
3182
|
-
|
|
3364
|
+
loop,
|
|
3183
3365
|
texts,
|
|
3366
|
+
textsCache,
|
|
3184
3367
|
handlers: {
|
|
3185
|
-
onWake: (source) => invoker.wake(source),
|
|
3186
|
-
onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
|
|
3187
3368
|
onConnected: (at) => {
|
|
3188
3369
|
if (blocked) {
|
|
3189
3370
|
blocked = false;
|
|
@@ -3191,7 +3372,6 @@ var agentchatGatewayAdapter = {
|
|
|
3191
3372
|
}
|
|
3192
3373
|
ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
|
|
3193
3374
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: "linked", lastConnectedAt: at }, "ready"));
|
|
3194
|
-
void catchUpInvites(ctx.accountId, client, invoker, logger);
|
|
3195
3375
|
},
|
|
3196
3376
|
onBlocked: (info) => {
|
|
3197
3377
|
const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
|
|
@@ -3247,23 +3427,6 @@ var agentchatGatewayAdapter = {
|
|
|
3247
3427
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
|
|
3248
3428
|
}
|
|
3249
3429
|
};
|
|
3250
|
-
async function catchUpInvites(accountId, client, invoker, logger) {
|
|
3251
|
-
try {
|
|
3252
|
-
const invites = await client.listGroupInvites();
|
|
3253
|
-
if (!Array.isArray(invites)) return;
|
|
3254
|
-
let surfaced = 0;
|
|
3255
|
-
for (const row of invites) {
|
|
3256
|
-
const invite = groupInviteFromRecord(row);
|
|
3257
|
-
if (invite && invoker.groupInvite(invite, "catch-up")) surfaced += 1;
|
|
3258
|
-
}
|
|
3259
|
-
if (surfaced > 0) logger.info({ accountId, surfaced }, "pending group invites surfaced on connect");
|
|
3260
|
-
} catch (err) {
|
|
3261
|
-
logger.warn(
|
|
3262
|
-
{ accountId, err: err instanceof Error ? err.message : String(err) },
|
|
3263
|
-
"pending-invite catch-up failed \u2014 live invite frames are unaffected and the agent can still list invites with the hosted tools"
|
|
3264
|
-
);
|
|
3265
|
-
}
|
|
3266
|
-
}
|
|
3267
3430
|
var PROBE_MIN_MS = 1e3;
|
|
3268
3431
|
var PROBE_MAX_MS = 1e4;
|
|
3269
3432
|
function formatCounts(counts) {
|
|
@@ -3305,15 +3468,27 @@ var agentchatStatusAdapter = {
|
|
|
3305
3468
|
const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
|
|
3306
3469
|
const live = getIntegration(account.accountId);
|
|
3307
3470
|
const health = live?.socket.getHealth();
|
|
3308
|
-
const
|
|
3309
|
-
const
|
|
3471
|
+
const loopStatus = live?.loop?.loop.status();
|
|
3472
|
+
const counters = loopStatus ? {
|
|
3473
|
+
wakes: loopStatus.coalescer.wakes,
|
|
3474
|
+
cycles: loopStatus.coalescer.cycles,
|
|
3475
|
+
turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted
|
|
3476
|
+
} : void 0;
|
|
3477
|
+
const turnsHere = live ? findAccountTurns(account.accountId) ?? null : null;
|
|
3478
|
+
const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null;
|
|
3479
|
+
const overdue = turnsHere ? [...hungReason ? [hungReason] : [], ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : [];
|
|
3480
|
+
const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null;
|
|
3481
|
+
const servedFrom = live?.texts?.source;
|
|
3482
|
+
const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
|
|
3310
3483
|
const socketCounters = live?.metrics?.snapshot?.();
|
|
3311
|
-
const
|
|
3484
|
+
const integration6 = {
|
|
3312
3485
|
mode: readEnv_js.readWakeModeFromEnv().mode,
|
|
3313
3486
|
...health ? { state: health.state } : {},
|
|
3314
3487
|
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
3315
3488
|
...textsSource ? { texts: textsSource } : {},
|
|
3316
|
-
...socketCounters ? { socket: socketCounters } : {}
|
|
3489
|
+
...socketCounters ? { socket: socketCounters } : {},
|
|
3490
|
+
...overdue.length > 0 ? { overdue } : {},
|
|
3491
|
+
...trouble ? { trouble } : {}
|
|
3317
3492
|
};
|
|
3318
3493
|
const refusal = multiAccountRefusal(cfg);
|
|
3319
3494
|
return {
|
|
@@ -3323,7 +3498,7 @@ var agentchatStatusAdapter = {
|
|
|
3323
3498
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3324
3499
|
mcp,
|
|
3325
3500
|
placement,
|
|
3326
|
-
integration,
|
|
3501
|
+
integration: integration6,
|
|
3327
3502
|
...refusal ? { refusal } : {},
|
|
3328
3503
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3329
3504
|
};
|
|
@@ -3361,6 +3536,8 @@ var agentchatStatusAdapter = {
|
|
|
3361
3536
|
tone: "muted"
|
|
3362
3537
|
});
|
|
3363
3538
|
}
|
|
3539
|
+
if (d.trouble) lines.push({ text: d.trouble, tone: "warn" });
|
|
3540
|
+
for (const line of d.overdue ?? []) lines.push({ text: line, tone: "warn" });
|
|
3364
3541
|
if (d.texts === "missing") {
|
|
3365
3542
|
lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
|
|
3366
3543
|
} else if (d.texts === "cache") {
|
|
@@ -3404,6 +3581,18 @@ var agentchatDoctorAdapter = {
|
|
|
3404
3581
|
);
|
|
3405
3582
|
}
|
|
3406
3583
|
}
|
|
3584
|
+
for (const accountId of listActiveAccounts()) {
|
|
3585
|
+
const status = getIntegration(accountId)?.loop?.loop.status();
|
|
3586
|
+
if (!status) continue;
|
|
3587
|
+
const turns = findAccountTurns(accountId);
|
|
3588
|
+
if (turns) {
|
|
3589
|
+
const hung = hungTurnsReason(turns, cfg);
|
|
3590
|
+
if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`);
|
|
3591
|
+
for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`);
|
|
3592
|
+
}
|
|
3593
|
+
const trouble = cycleTroubleLine(status.recentCycles ?? []);
|
|
3594
|
+
if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`);
|
|
3595
|
+
}
|
|
3407
3596
|
return warnings;
|
|
3408
3597
|
},
|
|
3409
3598
|
async repairConfig({ cfg }) {
|
|
@@ -3698,9 +3887,9 @@ var agentchatPlugin = {
|
|
|
3698
3887
|
listAccountIds(cfg) {
|
|
3699
3888
|
const section = readChannelSection(cfg);
|
|
3700
3889
|
if (!section) return [];
|
|
3701
|
-
const { accounts } = section;
|
|
3702
|
-
if (
|
|
3703
|
-
const ids = Object.keys(
|
|
3890
|
+
const { accounts: accounts2 } = section;
|
|
3891
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
3892
|
+
const ids = Object.keys(accounts2);
|
|
3704
3893
|
if (ids.length > 0) return ids;
|
|
3705
3894
|
}
|
|
3706
3895
|
const hasFlatFields = typeof section.apiKey === "string" || typeof section.apiBase === "string" || typeof section.agentHandle === "string";
|
|
@@ -3740,9 +3929,9 @@ var agentchatPlugin = {
|
|
|
3740
3929
|
hasConfiguredState({ cfg }) {
|
|
3741
3930
|
const section = readChannelSection(cfg);
|
|
3742
3931
|
if (!section) return false;
|
|
3743
|
-
const { accounts } = section;
|
|
3744
|
-
if (
|
|
3745
|
-
for (const entry of Object.values(
|
|
3932
|
+
const { accounts: accounts2 } = section;
|
|
3933
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
3934
|
+
for (const entry of Object.values(accounts2)) {
|
|
3746
3935
|
if (entry && typeof entry === "object") {
|
|
3747
3936
|
const candidate = entry.apiKey;
|
|
3748
3937
|
if (isApiKeyPresent(candidate)) return true;
|
|
@@ -3786,7 +3975,15 @@ var agentchatChannelEntry = channelCore.defineChannelPluginEntry({
|
|
|
3786
3975
|
// (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
|
|
3787
3976
|
// The integration reads `runtime.llm.complete` (the gate on the agent's own
|
|
3788
3977
|
// model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
|
|
3789
|
-
setRuntime: (runtime) => setPluginRuntime(runtime)
|
|
3978
|
+
setRuntime: (runtime) => setPluginRuntime(runtime),
|
|
3979
|
+
// `openclaw agentchat release <conversation_id>`: the CLI half is
|
|
3980
|
+
// registered for every CLI (parse-time metadata), the gateway half only
|
|
3981
|
+
// where the integration runs.
|
|
3982
|
+
registerCliMetadata: (api) => registerReleaseCli(api),
|
|
3983
|
+
registerFull: (api) => {
|
|
3984
|
+
registerReleaseGatewayMethod(api);
|
|
3985
|
+
registerRunObserver(api);
|
|
3986
|
+
}
|
|
3790
3987
|
});
|
|
3791
3988
|
var agentchatSetupEntry = channelCore.defineSetupPluginEntry(agentchatPlugin);
|
|
3792
3989
|
|
|
@@ -3803,30 +4000,29 @@ function hasAgentChatConfiguredState(config) {
|
|
|
3803
4000
|
exports.AGENTCHAT_CHANNEL_ID = AGENTCHAT_CHANNEL_ID;
|
|
3804
4001
|
exports.AGENTCHAT_DEFAULT_ACCOUNT_ID = AGENTCHAT_DEFAULT_ACCOUNT_ID;
|
|
3805
4002
|
exports.AgentChatChannelError = AgentChatChannelError;
|
|
3806
|
-
exports.AgentInvoker = AgentInvoker;
|
|
3807
4003
|
exports.IntegrationSocket = IntegrationSocket;
|
|
3808
|
-
exports.
|
|
4004
|
+
exports.MAX_HUNG_TURNS = MAX_HUNG_TURNS;
|
|
3809
4005
|
exports.MCP_SERVER_NAME = MCP_SERVER_NAME;
|
|
3810
4006
|
exports.OPENCLAW_TOOL_NAMER = OPENCLAW_TOOL_NAMER;
|
|
3811
|
-
exports.
|
|
3812
|
-
exports.
|
|
4007
|
+
exports.OpenClawTexts = OpenClawTexts;
|
|
4008
|
+
exports.accountTurns = accountTurns;
|
|
3813
4009
|
exports.agentchatChannelEntry = agentchatChannelEntry;
|
|
3814
4010
|
exports.agentchatPlugin = agentchatPlugin;
|
|
3815
4011
|
exports.agentchatSetupEntry = agentchatSetupEntry;
|
|
3816
4012
|
exports.agentchatSetupPlugin = agentchatPlugin;
|
|
3817
4013
|
exports.assertApiKeyValid = assertApiKeyValid;
|
|
3818
4014
|
exports.createInMemoryMetrics = createInMemoryMetrics;
|
|
4015
|
+
exports.createIntegrationLoop = createIntegrationLoop;
|
|
4016
|
+
exports.createLoopTurnStarter = createLoopTurnStarter;
|
|
3819
4017
|
exports.createMetrics = createMetrics;
|
|
3820
4018
|
exports.createNoopMetrics = createNoopMetrics;
|
|
4019
|
+
exports.createTextsCache = createTextsCache;
|
|
3821
4020
|
exports.default = agentchatChannelEntry;
|
|
3822
|
-
exports.groupInviteFromRecord = groupInviteFromRecord;
|
|
3823
4021
|
exports.hasAgentChatConfiguredState = hasAgentChatConfiguredState;
|
|
3824
4022
|
exports.hostedMcpServerEntry = hostedMcpServerEntry;
|
|
3825
4023
|
exports.hostedMcpSnippet = hostedMcpSnippet;
|
|
3826
4024
|
exports.hostedMcpUrl = hostedMcpUrl;
|
|
3827
|
-
exports.inviteTurnPrompt = inviteTurnPrompt;
|
|
3828
4025
|
exports.loadIdentityLine = loadIdentityLine;
|
|
3829
|
-
exports.loadTexts = loadTexts;
|
|
3830
4026
|
exports.mcpToolName = mcpToolName;
|
|
3831
4027
|
exports.parseChannelConfig = parseChannelConfig;
|
|
3832
4028
|
exports.probeHostedMcp = probeHostedMcp;
|
|
@@ -3835,8 +4031,10 @@ exports.recoverAgentStart = recoverAgentStart;
|
|
|
3835
4031
|
exports.recoverAgentVerify = recoverAgentVerify;
|
|
3836
4032
|
exports.registerAgentStart = registerAgentStart;
|
|
3837
4033
|
exports.registerAgentVerify = registerAgentVerify;
|
|
4034
|
+
exports.spellTextsForOpenClaw = spellTextsForOpenClaw;
|
|
3838
4035
|
exports.spellToolsForOpenClaw = spellToolsForOpenClaw;
|
|
4036
|
+
exports.trackerFor = trackerFor;
|
|
4037
|
+
exports.turnEndOf = turnEndOf;
|
|
3839
4038
|
exports.validateApiKey = validateApiKey;
|
|
3840
|
-
exports.wakeTurnPrompt = wakeTurnPrompt;
|
|
3841
4039
|
//# sourceMappingURL=index.cjs.map
|
|
3842
4040
|
//# sourceMappingURL=index.cjs.map
|