@agentchatme/openclaw 0.9.2 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -1
- package/README.md +53 -37
- package/RUNBOOK.md +57 -21
- package/SECURITY.md +14 -5
- 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 +1713 -1366
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +673 -192
- package/dist/index.d.ts +673 -192
- package/dist/index.js +1707 -1361
- package/dist/index.js.map +1 -1
- package/dist/setup-entry-DFY6cAa6.d.cts +382 -0
- package/dist/setup-entry-DFY6cAa6.d.ts +382 -0
- package/dist/setup-entry.cjs +1700 -1361
- 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 +1702 -1363
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +5 -5
- package/package.json +3 -3
- package/skills/agentchat/SKILL.md +65 -61
- 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.1";
|
|
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,18 +415,25 @@ 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
|
}
|
|
421
|
+
var CLIENT_HEADER = "X-AgentChat-Client";
|
|
422
|
+
function clientIdentityHeaders() {
|
|
423
|
+
return { [CLIENT_HEADER]: AGENTCHAT_CLIENT_NAME };
|
|
424
|
+
}
|
|
425
|
+
function clientIdentityText() {
|
|
426
|
+
return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
|
|
427
|
+
}
|
|
487
428
|
function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
|
|
488
429
|
return {
|
|
489
430
|
url: hostedMcpUrl(apiBase),
|
|
490
431
|
transport: "streamable-http",
|
|
491
|
-
headers: { Authorization: AUTH_HEADER_TEMPLATE }
|
|
432
|
+
headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
|
|
492
433
|
};
|
|
493
434
|
}
|
|
494
435
|
function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
|
|
436
|
+
const identity = clientIdentityHeaders();
|
|
495
437
|
return [
|
|
496
438
|
"{",
|
|
497
439
|
" mcp: {",
|
|
@@ -499,7 +441,10 @@ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
|
|
|
499
441
|
` ${MCP_SERVER_NAME}: {`,
|
|
500
442
|
` url: "${hostedMcpUrl(apiBase)}",`,
|
|
501
443
|
' transport: "streamable-http",',
|
|
502
|
-
|
|
444
|
+
" headers: {",
|
|
445
|
+
` Authorization: "${AUTH_HEADER_TEMPLATE}",`,
|
|
446
|
+
` "${CLIENT_HEADER}": "${identity[CLIENT_HEADER]}",`,
|
|
447
|
+
" },",
|
|
503
448
|
" },",
|
|
504
449
|
" },",
|
|
505
450
|
" },",
|
|
@@ -522,23 +467,99 @@ function pointsAtUs(entry, apiBase, apiKey) {
|
|
|
522
467
|
const headers = entry.headers;
|
|
523
468
|
if (headers === void 0) return true;
|
|
524
469
|
if (!headers || typeof headers !== "object" || Array.isArray(headers)) return false;
|
|
525
|
-
const
|
|
470
|
+
const auths = headerValues(headers, "Authorization");
|
|
471
|
+
if (auths.length > 1) return false;
|
|
472
|
+
const auth = auths[0];
|
|
526
473
|
if (auth === void 0) return true;
|
|
527
474
|
if (typeof auth !== "string") return false;
|
|
528
475
|
if (auth === AUTH_HEADER_TEMPLATE || auth.includes(`\${${readEnv_js.API_KEY_ENV}}`)) return true;
|
|
529
476
|
return apiKey !== void 0 && apiKey.length > 0 && auth.trim() === `Bearer ${apiKey}`;
|
|
530
477
|
}
|
|
478
|
+
function describeMcpIdentity(cfg) {
|
|
479
|
+
const entry = agentchatEntry(cfg);
|
|
480
|
+
const headers = entry && isRecord(entry.headers) ? entry.headers : void 0;
|
|
481
|
+
if (!headers) return "missing";
|
|
482
|
+
const want = clientIdentityHeaders();
|
|
483
|
+
const clients = headerValues(headers, CLIENT_HEADER);
|
|
484
|
+
const client = clients[0];
|
|
485
|
+
return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
|
|
486
|
+
}
|
|
531
487
|
function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
532
488
|
const state = describeMcpEntry(cfg, apiBase, apiKey);
|
|
533
489
|
const base = cfg ?? {};
|
|
534
|
-
if (state === "ours") return { cfg: base, outcome: "present" };
|
|
535
490
|
if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
|
|
536
491
|
if (state === "disabled") return { cfg: base, outcome: "disabled" };
|
|
492
|
+
if (state === "ours" && describeMcpIdentity(base) === "current") return { cfg: base, outcome: "present" };
|
|
537
493
|
const mcp = { ...base.mcp ?? {} };
|
|
538
494
|
const servers = { ...mcp.servers ?? {} };
|
|
539
|
-
servers[MCP_SERVER_NAME]
|
|
495
|
+
const existing = servers[MCP_SERVER_NAME];
|
|
496
|
+
servers[MCP_SERVER_NAME] = state === "ours" && isRecord(existing) ? upgradedHostedMcpEntry(existing, apiBase) : hostedMcpServerEntry(apiBase);
|
|
540
497
|
mcp.servers = servers;
|
|
541
|
-
return { cfg: { ...base, mcp }, outcome: "added" };
|
|
498
|
+
return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
|
|
499
|
+
}
|
|
500
|
+
function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
|
|
501
|
+
const headers = isRecord(entry.headers) ? entry.headers : {};
|
|
502
|
+
const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
|
|
503
|
+
return {
|
|
504
|
+
...entry,
|
|
505
|
+
url: hostedMcpUrl(apiBase),
|
|
506
|
+
transport: "streamable-http",
|
|
507
|
+
headers: { ...kept, ...clientIdentityHeaders() }
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
511
|
+
if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
|
|
512
|
+
const servers = draft.mcp.servers;
|
|
513
|
+
const existing = servers[MCP_SERVER_NAME];
|
|
514
|
+
if (!isRecord(existing)) return false;
|
|
515
|
+
servers[MCP_SERVER_NAME] = upgradedHostedMcpEntry(existing, apiBase);
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
var NoChange = class extends Error {
|
|
519
|
+
constructor(outcome) {
|
|
520
|
+
super(`no change (${outcome})`);
|
|
521
|
+
this.outcome = outcome;
|
|
522
|
+
}
|
|
523
|
+
outcome;
|
|
524
|
+
};
|
|
525
|
+
var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
|
|
526
|
+
async function refreshHostedMcpEntry(params) {
|
|
527
|
+
const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
|
|
528
|
+
if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
|
|
529
|
+
if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
|
|
530
|
+
const mutate = params.config?.mutateConfigFile;
|
|
531
|
+
if (typeof mutate !== "function") return { outcome: "unsupported" };
|
|
532
|
+
try {
|
|
533
|
+
await mutate.call(params.config, {
|
|
534
|
+
afterWrite: { mode: "auto" },
|
|
535
|
+
mutate: ((draft) => {
|
|
536
|
+
if (describeMcpEntry(draft, apiBase, params.apiKey) !== "ours") throw new NoChange("not_ours");
|
|
537
|
+
if (!upgradeHostedMcpEntryInPlace(draft, apiBase, params.apiKey)) throw new NoChange("current");
|
|
538
|
+
})
|
|
539
|
+
});
|
|
540
|
+
return { outcome: "updated" };
|
|
541
|
+
} catch (err) {
|
|
542
|
+
if (err instanceof NoChange) return { outcome: err.outcome };
|
|
543
|
+
const code = err?.code;
|
|
544
|
+
return {
|
|
545
|
+
outcome: "failed",
|
|
546
|
+
error: err instanceof Error ? err.message : String(err),
|
|
547
|
+
...typeof code === "string" ? { code } : {}
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
function isRecord(value) {
|
|
552
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
553
|
+
}
|
|
554
|
+
function agentchatEntry(cfg) {
|
|
555
|
+
const servers = cfg?.mcp?.servers;
|
|
556
|
+
if (!isRecord(servers)) return void 0;
|
|
557
|
+
const entry = servers[MCP_SERVER_NAME];
|
|
558
|
+
return isRecord(entry) ? entry : void 0;
|
|
559
|
+
}
|
|
560
|
+
function headerValues(headers, name) {
|
|
561
|
+
const wanted = name.toLowerCase();
|
|
562
|
+
return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
|
|
542
563
|
}
|
|
543
564
|
function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
544
565
|
if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
|
|
@@ -549,67 +570,24 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
|
549
570
|
return { cfg: { ...cfg, mcp }, removed: true };
|
|
550
571
|
}
|
|
551
572
|
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;
|
|
573
|
+
const result = await agentchatme.integration.probeHostedTools({
|
|
574
|
+
apiBase: params.apiBase ?? DEFAULT_API_BASE2,
|
|
575
|
+
apiKey: params.apiKey,
|
|
576
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
577
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
578
|
+
...params.fetch ? { fetch: params.fetch } : {}
|
|
579
|
+
});
|
|
580
|
+
const missing = result.missing ?? [];
|
|
581
|
+
return {
|
|
582
|
+
ok: result.ok,
|
|
583
|
+
...result.status !== void 0 ? { status: result.status } : {},
|
|
584
|
+
...result.serverName ? { serverName: result.serverName } : {},
|
|
585
|
+
...result.serverVersion ? { serverVersion: result.serverVersion } : {},
|
|
586
|
+
...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {},
|
|
587
|
+
...result.tools ? { tools: result.tools } : {},
|
|
588
|
+
...missing.length > 0 ? { missing } : {},
|
|
589
|
+
...result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(", ")} for this key` } : {}
|
|
590
|
+
};
|
|
613
591
|
}
|
|
614
592
|
|
|
615
593
|
// src/integration/runtime-holder.ts
|
|
@@ -629,11 +607,137 @@ function setPluginRuntime(runtime) {
|
|
|
629
607
|
function getPluginRuntime() {
|
|
630
608
|
return current;
|
|
631
609
|
}
|
|
610
|
+
|
|
611
|
+
// src/integration/run.ts
|
|
612
|
+
var DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 6e4;
|
|
613
|
+
var RUN_WAIT_RETRY_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
|
|
614
|
+
var MIN_WAIT_SPACING_MS = 1e3;
|
|
615
|
+
var TRANSCRIPT_READ_LIMIT = 200;
|
|
616
|
+
var METADATA_KEYS = ["endedAt", "stopReason", "livenessState", "pendingError", "timeoutPhase", "startedAt", "providerStarted"];
|
|
617
|
+
function runEndOf(wait, timing) {
|
|
618
|
+
const status = wait?.status;
|
|
619
|
+
const error = nonEmpty(wait?.error);
|
|
620
|
+
if (status === "ok") return { ended: true, status: "ok" };
|
|
621
|
+
if (status === "error") {
|
|
622
|
+
if (error && error.trim().toLowerCase() === "completed") return { ended: true, status: "ok" };
|
|
623
|
+
return { ended: true, status: "error", ...error ? { error } : {} };
|
|
624
|
+
}
|
|
625
|
+
if (status !== "timeout") {
|
|
626
|
+
return { ended: false };
|
|
627
|
+
}
|
|
628
|
+
const ended = { ended: true, status: "timeout", ...error ? { error } : {} };
|
|
629
|
+
const hasMetadata = wait !== null && wait !== void 0 && METADATA_KEYS.some((key) => key in wait);
|
|
630
|
+
if (!hasMetadata) {
|
|
631
|
+
return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false };
|
|
632
|
+
}
|
|
633
|
+
if (wait.pendingError === true) return { ended: false };
|
|
634
|
+
if (typeof wait.endedAt === "number" || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended;
|
|
635
|
+
if (isHardTimeout(wait)) return ended;
|
|
636
|
+
return error ? ended : { ended: false };
|
|
637
|
+
}
|
|
638
|
+
var HARD_TIMEOUT_PHASES = /* @__PURE__ */ new Set(["preflight", "provider", "tool_execution", "post_turn"]);
|
|
639
|
+
function isHardTimeout(wait) {
|
|
640
|
+
const phase = typeof wait.timeoutPhase === "string" ? wait.timeoutPhase.trim() : "";
|
|
641
|
+
if (HARD_TIMEOUT_PHASES.has(phase)) return true;
|
|
642
|
+
return wait.status === "timeout" && wait.providerStarted === true && nonEmpty(wait.stopReason) !== "restart";
|
|
643
|
+
}
|
|
644
|
+
async function watchRunUntilEnded(options) {
|
|
645
|
+
const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS;
|
|
646
|
+
const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS;
|
|
647
|
+
const now = options.now ?? Date.now;
|
|
648
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
649
|
+
const started = now();
|
|
650
|
+
let failures = 0;
|
|
651
|
+
for (; ; ) {
|
|
652
|
+
const runtime = options.runtime();
|
|
653
|
+
if (!runtime) return { ended: false, reason: "gone", elapsedMs: now() - started };
|
|
654
|
+
const waitStarted = now();
|
|
655
|
+
let observation;
|
|
656
|
+
try {
|
|
657
|
+
observation = await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs });
|
|
658
|
+
} catch (err) {
|
|
659
|
+
const message = describe(err);
|
|
660
|
+
const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 6e4;
|
|
661
|
+
failures += 1;
|
|
662
|
+
options.onWaitError?.(message, failures, delay);
|
|
663
|
+
await sleep(delay);
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
failures = 0;
|
|
667
|
+
const elapsedMs = now() - waitStarted;
|
|
668
|
+
const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs });
|
|
669
|
+
if (end.ended) return { ...end, elapsedMs: now() - started };
|
|
670
|
+
options.onStillRunning?.(now() - started);
|
|
671
|
+
if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
function countAgentChatCalls(messages, runId) {
|
|
675
|
+
if (messages.length === 0) return null;
|
|
676
|
+
let recognised = false;
|
|
677
|
+
let made = 0;
|
|
678
|
+
let failed = 0;
|
|
679
|
+
for (const row of messages) {
|
|
680
|
+
const message = unwrapMessage(row);
|
|
681
|
+
if (!message) continue;
|
|
682
|
+
const role = message.role;
|
|
683
|
+
if (role === "assistant" || role === "user") recognised = true;
|
|
684
|
+
if (role !== "toolResult" && role !== "tool") continue;
|
|
685
|
+
recognised = true;
|
|
686
|
+
const meta = asRecord2(message.__openclaw);
|
|
687
|
+
if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
|
|
688
|
+
if (!isAgentChatToolResult(message)) continue;
|
|
689
|
+
made += 1;
|
|
690
|
+
if (message.isError === true) failed += 1;
|
|
691
|
+
}
|
|
692
|
+
return recognised ? { made, failed } : null;
|
|
693
|
+
}
|
|
694
|
+
async function readAgentChatCalls(runtime, sessionKey, runId) {
|
|
695
|
+
if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
|
|
696
|
+
try {
|
|
697
|
+
const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
|
|
698
|
+
const messages = result?.messages;
|
|
699
|
+
return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
|
|
700
|
+
} catch {
|
|
701
|
+
return null;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
705
|
+
function isAgentChatToolResult(message) {
|
|
706
|
+
const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
|
|
707
|
+
if (toolName.startsWith(TOOL_PREFIX)) return true;
|
|
708
|
+
const tool = asRecord2(asRecord2(message.details)?.tool);
|
|
709
|
+
if (!tool) return false;
|
|
710
|
+
if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
|
|
711
|
+
if (tool.sourceName === MCP_SERVER_NAME) return true;
|
|
712
|
+
const mcp = asRecord2(tool.mcp);
|
|
713
|
+
return mcp?.serverName === MCP_SERVER_NAME;
|
|
714
|
+
}
|
|
715
|
+
function unwrapMessage(row) {
|
|
716
|
+
const record = asRecord2(row);
|
|
717
|
+
if (!record) return null;
|
|
718
|
+
if (typeof record.role === "string") return record;
|
|
719
|
+
const inner = asRecord2(record.message);
|
|
720
|
+
return inner && typeof inner.role === "string" ? inner : null;
|
|
721
|
+
}
|
|
722
|
+
function asRecord2(value) {
|
|
723
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
724
|
+
}
|
|
725
|
+
function nonEmpty(value) {
|
|
726
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
727
|
+
}
|
|
728
|
+
function describe(err) {
|
|
729
|
+
return err instanceof Error ? err.message : String(err);
|
|
730
|
+
}
|
|
731
|
+
function defaultSleep(ms) {
|
|
732
|
+
return new Promise((resolve) => {
|
|
733
|
+
const timer = setTimeout(resolve, ms);
|
|
734
|
+
timer.unref?.();
|
|
735
|
+
});
|
|
736
|
+
}
|
|
632
737
|
var DEFAULT_AGENT_ID = "main";
|
|
633
738
|
var GATE_TEMPERATURE = 0;
|
|
634
739
|
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
635
740
|
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
636
|
-
var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
|
|
637
741
|
var RuntimeUnavailableError = class extends Error {
|
|
638
742
|
constructor(what) {
|
|
639
743
|
super(`OpenClaw plugin runtime unavailable \u2014 ${what} needs setRuntime(...) from defineChannelPluginEntry`);
|
|
@@ -658,16 +762,21 @@ function createRuntimeModelCall(params) {
|
|
|
658
762
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
659
763
|
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
660
764
|
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
661
|
-
return async (prompt) => {
|
|
765
|
+
return async (prompt, options) => {
|
|
662
766
|
const runtime = getRuntime();
|
|
663
767
|
if (!runtime) throw new RuntimeUnavailableError("the gate call");
|
|
768
|
+
const signals = [
|
|
769
|
+
...Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : [],
|
|
770
|
+
...options?.signal ? [options.signal] : []
|
|
771
|
+
];
|
|
772
|
+
const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
664
773
|
const result = await runtime.llm.complete({
|
|
665
774
|
messages: [{ role: "user", content: prompt }],
|
|
666
775
|
maxTokens,
|
|
667
776
|
temperature: GATE_TEMPERATURE,
|
|
668
777
|
...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
|
|
669
778
|
purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
|
|
670
|
-
...
|
|
779
|
+
...signal ? { signal } : {}
|
|
671
780
|
});
|
|
672
781
|
return typeof result?.text === "string" ? result.text : "";
|
|
673
782
|
};
|
|
@@ -697,10 +806,14 @@ function resolveGateAgent(params) {
|
|
|
697
806
|
return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
|
|
698
807
|
}
|
|
699
808
|
function readLiveConfig(fallback, runtime = getPluginRuntime) {
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
if (
|
|
703
|
-
|
|
809
|
+
const config = runtime()?.config;
|
|
810
|
+
for (const read of [config?.current, config?.loadConfig]) {
|
|
811
|
+
if (typeof read !== "function") continue;
|
|
812
|
+
try {
|
|
813
|
+
const loaded = read.call(config);
|
|
814
|
+
if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
|
|
815
|
+
} catch {
|
|
816
|
+
}
|
|
704
817
|
}
|
|
705
818
|
return { cfg: fallback, live: false };
|
|
706
819
|
}
|
|
@@ -728,11 +841,11 @@ function turnReadiness(params) {
|
|
|
728
841
|
}
|
|
729
842
|
function createRuntimeTurnStarter(params = {}) {
|
|
730
843
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
731
|
-
const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
|
|
732
844
|
return async (request) => {
|
|
733
845
|
const runtime = getRuntime();
|
|
734
846
|
if (!runtime) return { ran: false, error: new RuntimeUnavailableError("the agent turn").message };
|
|
735
847
|
let runId;
|
|
848
|
+
let sessionKey = request.sessionKey;
|
|
736
849
|
try {
|
|
737
850
|
const admitted = await runtime.subagent.run({
|
|
738
851
|
sessionKey: request.sessionKey,
|
|
@@ -741,15 +854,46 @@ function createRuntimeTurnStarter(params = {}) {
|
|
|
741
854
|
deliver: false
|
|
742
855
|
});
|
|
743
856
|
runId = admitted.runId;
|
|
857
|
+
const accepted = admitted.sessionKey;
|
|
858
|
+
if (typeof accepted === "string" && accepted.trim().length > 0) sessionKey = accepted.trim();
|
|
744
859
|
} catch (err) {
|
|
745
860
|
return { ran: false, error: err instanceof Error ? err.message : String(err) };
|
|
746
861
|
}
|
|
747
|
-
const done =
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
862
|
+
const done = watchRunUntilEnded({
|
|
863
|
+
runtime: getRuntime,
|
|
864
|
+
runId,
|
|
865
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
866
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {},
|
|
867
|
+
...params.onWaitError ? { onWaitError: (error, attempt, retryInMs) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) } : {},
|
|
868
|
+
...params.now ? { now: params.now } : {},
|
|
869
|
+
...params.sleep ? { sleep: params.sleep } : {}
|
|
870
|
+
}).then(async (watched) => {
|
|
871
|
+
if (!watched.ended) return { ran: true, runId, status: "gone", elapsedMs: watched.elapsedMs };
|
|
872
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
873
|
+
return {
|
|
874
|
+
ran: true,
|
|
875
|
+
runId,
|
|
876
|
+
status: watched.status,
|
|
877
|
+
...watched.error ? { error: watched.error } : {},
|
|
878
|
+
agentchatCalls,
|
|
879
|
+
elapsedMs: watched.elapsedMs
|
|
880
|
+
};
|
|
881
|
+
});
|
|
882
|
+
return { ran: true, runId, sessionKey, done };
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
function createRunWatcher(params = {}) {
|
|
886
|
+
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
887
|
+
return async ({ runId, sessionKey }) => {
|
|
888
|
+
const watched = await watchRunUntilEnded({
|
|
889
|
+
runtime: getRuntime,
|
|
890
|
+
runId,
|
|
891
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
892
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}
|
|
893
|
+
});
|
|
894
|
+
if (!watched.ended) return null;
|
|
895
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
896
|
+
return { ran: true, runId, status: watched.status, ...watched.error ? { error: watched.error } : {}, agentchatCalls, elapsedMs: watched.elapsedMs };
|
|
753
897
|
};
|
|
754
898
|
}
|
|
755
899
|
var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
@@ -838,6 +982,7 @@ function applyIntegrationConfig(cfg, params) {
|
|
|
838
982
|
const mcp = withHostedMcpEntry(next, params.apiBase, params.apiKey);
|
|
839
983
|
next = mcp.cfg;
|
|
840
984
|
if (mcp.outcome === "added") changes.push(`mcp.servers.agentchat \u2192 ${hostedMcpUrl(params.apiBase)} (bearer template on ${readEnv_js.API_KEY_ENV})`);
|
|
985
|
+
if (mcp.outcome === "updated") changes.push(`mcp.servers.agentchat names this client (${clientIdentityText()})`);
|
|
841
986
|
const bound = openclawLayout_js.resolveBoundAgentId(next, AGENTCHAT_CHANNEL_ID, params.accountId);
|
|
842
987
|
const ambient = openclawLayout_js.resolveOpenClawDefaultAgentId(next);
|
|
843
988
|
if (bound && bound !== (ambient ?? bound)) {
|
|
@@ -888,7 +1033,7 @@ function restoreIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
888
1033
|
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
|
|
889
1034
|
return { outcome: "placed", path: written.path };
|
|
890
1035
|
} catch (err) {
|
|
891
|
-
return { outcome: "failed", path: filePath, detail:
|
|
1036
|
+
return { outcome: "failed", path: filePath, detail: describe2(err) };
|
|
892
1037
|
}
|
|
893
1038
|
}
|
|
894
1039
|
function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
@@ -900,7 +1045,7 @@ function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
900
1045
|
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
|
|
901
1046
|
return { outcome: "updated", path: written.path };
|
|
902
1047
|
} catch (err) {
|
|
903
|
-
return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail:
|
|
1048
|
+
return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail: describe2(err) };
|
|
904
1049
|
}
|
|
905
1050
|
}
|
|
906
1051
|
function placeIntegration(params) {
|
|
@@ -914,7 +1059,7 @@ function placeIntegration(params) {
|
|
|
914
1059
|
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
1060
|
});
|
|
916
1061
|
} catch (err) {
|
|
917
|
-
steps.push({ name: "key", status: "failed", detail: `could not write ${readEnv_js.API_KEY_ENV} to the OpenClaw .env: ${
|
|
1062
|
+
steps.push({ name: "key", status: "failed", detail: `could not write ${readEnv_js.API_KEY_ENV} to the OpenClaw .env: ${describe2(err)}` });
|
|
918
1063
|
}
|
|
919
1064
|
}
|
|
920
1065
|
const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
|
|
@@ -930,7 +1075,7 @@ function placeIntegration(params) {
|
|
|
930
1075
|
const anchor = agentsAnchor_js.writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
|
|
931
1076
|
steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
|
|
932
1077
|
} catch (err) {
|
|
933
|
-
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${
|
|
1078
|
+
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe2(err)}` });
|
|
934
1079
|
}
|
|
935
1080
|
}
|
|
936
1081
|
steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
|
|
@@ -942,6 +1087,8 @@ function describeMcpOutcome(outcome, apiBase) {
|
|
|
942
1087
|
switch (outcome) {
|
|
943
1088
|
case "added":
|
|
944
1089
|
return { name: "mcp", status: "changed", detail: `hosted tools registered as mcp.servers.agentchat \u2192 ${hostedMcpUrl(apiBase)} (bearer template on ${readEnv_js.API_KEY_ENV})` };
|
|
1090
|
+
case "updated":
|
|
1091
|
+
return { name: "mcp", status: "changed", detail: `mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()})` };
|
|
945
1092
|
case "present":
|
|
946
1093
|
return { name: "mcp", status: "ok", detail: "hosted tools already registered as mcp.servers.agentchat" };
|
|
947
1094
|
case "disabled":
|
|
@@ -983,15 +1130,40 @@ function checkPlacement(params) {
|
|
|
983
1130
|
checks.push({ name: "anchor", ok: false, detail: `agentHandle not in config \u2014 the identity line cannot be checked; ${remedy("run openclaw doctor --fix (it learns the handle from the key)")}` });
|
|
984
1131
|
}
|
|
985
1132
|
checks.push({ name: "manual", ok: true, detail: "manual bundled as the agentchat skill" });
|
|
986
|
-
|
|
987
|
-
checks.push({
|
|
988
|
-
name: "mcp",
|
|
989
|
-
ok: mcpState === "ours" || mcpState === "user_managed",
|
|
990
|
-
detail: mcpState === "ours" ? "hosted tools registered as mcp.servers.agentchat" : mcpState === "user_managed" ? "mcp.servers.agentchat is managed by hand" : mcpState === "disabled" ? "mcp.servers.agentchat is disabled \u2014 the agent has no AgentChat tools" : `mcp.servers.agentchat missing \u2014 ${remedy("run openclaw doctor --fix (or openclaw channels add agentchat)")}`
|
|
991
|
-
});
|
|
1133
|
+
checks.push(checkMcpEntry(params.cfg, params.apiBase, params.apiKey, remedy));
|
|
992
1134
|
return checks;
|
|
993
1135
|
}
|
|
994
|
-
function
|
|
1136
|
+
function checkMcpEntry(cfg, apiBase, apiKey, remedy) {
|
|
1137
|
+
const unknownClient = "AgentChat treats the agent as an unknown client and lists the webhook-setup tools it does not need";
|
|
1138
|
+
switch (describeMcpEntry(cfg, apiBase, apiKey)) {
|
|
1139
|
+
case "ours": {
|
|
1140
|
+
const identity = describeMcpIdentity(cfg);
|
|
1141
|
+
if (identity === "current") return { name: "mcp", ok: true, detail: "hosted tools registered as mcp.servers.agentchat" };
|
|
1142
|
+
return {
|
|
1143
|
+
name: "mcp",
|
|
1144
|
+
ok: true,
|
|
1145
|
+
notice: true,
|
|
1146
|
+
repair: true,
|
|
1147
|
+
detail: `hosted tools registered as mcp.servers.agentchat, without ${CLIENT_HEADER} \u2014 ${unknownClient}; the gateway adds ${clientIdentityText()} to the entry when it starts (its log says if it could not), and openclaw doctor --fix does now`
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
case "user_managed": {
|
|
1151
|
+
if (describeMcpIdentity(cfg) === "current") return { name: "mcp", ok: true, detail: "mcp.servers.agentchat is managed by hand" };
|
|
1152
|
+
const identity = clientIdentityHeaders();
|
|
1153
|
+
return {
|
|
1154
|
+
name: "mcp",
|
|
1155
|
+
ok: true,
|
|
1156
|
+
notice: true,
|
|
1157
|
+
detail: `mcp.servers.agentchat is managed by hand and does not name this client, so ${unknownClient} \u2014 add "${CLIENT_HEADER}": "${identity[CLIENT_HEADER]}" to its headers`
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
case "disabled":
|
|
1161
|
+
return { name: "mcp", ok: false, detail: "mcp.servers.agentchat is disabled \u2014 the agent has no AgentChat tools" };
|
|
1162
|
+
case "missing":
|
|
1163
|
+
return { name: "mcp", ok: false, repair: true, detail: `mcp.servers.agentchat missing \u2014 ${remedy("run openclaw doctor --fix (or openclaw channels add agentchat)")}` };
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
function describe2(err) {
|
|
995
1167
|
return err instanceof Error ? err.message : String(err);
|
|
996
1168
|
}
|
|
997
1169
|
var PLUGIN_STATE_DIRNAME = "agentchat";
|
|
@@ -1002,236 +1174,115 @@ function safeSegment(value) {
|
|
|
1002
1174
|
function integrationStateDir(accountId, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
1003
1175
|
return path2__namespace.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
|
|
1004
1176
|
}
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1177
|
+
var OLD_INVITE_LEDGER_FILE = "invites.json";
|
|
1178
|
+
function removeOldStateFiles(accountId, stateDir) {
|
|
1179
|
+
const dir = integrationStateDir(accountId, stateDir);
|
|
1180
|
+
const removed = [];
|
|
1181
|
+
const ledger = path2__namespace.join(dir, OLD_INVITE_LEDGER_FILE);
|
|
1182
|
+
if (tryUnlink(ledger)) removed.push(ledger);
|
|
1183
|
+
const texts = path2__namespace.join(dir, "texts.json");
|
|
1012
1184
|
try {
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1185
|
+
const entry = JSON.parse(fs__namespace.readFileSync(texts, "utf8"));
|
|
1186
|
+
if (entry.version !== 1 || typeof entry.runtime !== "string") {
|
|
1187
|
+
if (tryUnlink(texts)) removed.push(texts);
|
|
1188
|
+
}
|
|
1189
|
+
} catch (err) {
|
|
1190
|
+
if (err?.code !== "ENOENT" && tryUnlink(texts)) removed.push(texts);
|
|
1016
1191
|
}
|
|
1192
|
+
return removed;
|
|
1017
1193
|
}
|
|
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");
|
|
1194
|
+
function tryUnlink(file) {
|
|
1023
1195
|
try {
|
|
1024
|
-
fs__namespace.
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
} catch {
|
|
1029
|
-
}
|
|
1030
|
-
throw err;
|
|
1196
|
+
fs__namespace.unlinkSync(file);
|
|
1197
|
+
return true;
|
|
1198
|
+
} catch {
|
|
1199
|
+
return false;
|
|
1031
1200
|
}
|
|
1032
1201
|
}
|
|
1033
1202
|
|
|
1034
1203
|
// src/integration/texts.ts
|
|
1035
1204
|
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
1205
|
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
1206
|
function textsCachePath(accountId, stateDir) {
|
|
1047
1207
|
return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1048
1208
|
}
|
|
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
1209
|
function spellTextsForOpenClaw(texts) {
|
|
1063
1210
|
return {
|
|
1064
1211
|
...texts,
|
|
1065
1212
|
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1066
1213
|
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1067
1214
|
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
1068
|
-
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
|
|
1215
|
+
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),
|
|
1216
|
+
...typeof texts.gate_call_preamble === "string" ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {},
|
|
1217
|
+
...typeof texts.gate_call_answer_format === "string" ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}
|
|
1069
1218
|
};
|
|
1070
1219
|
}
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1220
|
+
function createTextsCache(params) {
|
|
1221
|
+
return new agentchatme.integration.TextsCache({
|
|
1222
|
+
client: params.client,
|
|
1223
|
+
runtime: TEXTS_RUNTIME,
|
|
1224
|
+
filePath: textsCachePath(params.accountId, params.stateDir),
|
|
1225
|
+
...params.logger ? { onError: (err) => params.logger?.warn({ err: err.message }, "served texts") } : {}
|
|
1226
|
+
});
|
|
1075
1227
|
}
|
|
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;
|
|
1228
|
+
var OpenClawTexts = class {
|
|
1229
|
+
constructor(cache2) {
|
|
1230
|
+
this.cache = cache2;
|
|
1095
1231
|
}
|
|
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));
|
|
1232
|
+
cache;
|
|
1233
|
+
spelledFrom = null;
|
|
1234
|
+
spelled = null;
|
|
1235
|
+
current() {
|
|
1236
|
+
return this.spell(this.cache.current());
|
|
1135
1237
|
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
return this.loaded?.texts ?? null;
|
|
1238
|
+
async ensure() {
|
|
1239
|
+
return this.spell(await this.cache.ensure());
|
|
1139
1240
|
}
|
|
1140
1241
|
get source() {
|
|
1141
|
-
return this.
|
|
1242
|
+
return this.cache.source;
|
|
1142
1243
|
}
|
|
1143
1244
|
get fetchedAt() {
|
|
1144
|
-
return this.
|
|
1245
|
+
return this.cache.fetchedAt;
|
|
1145
1246
|
}
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
this.listeners.add(listener);
|
|
1149
|
-
return () => {
|
|
1150
|
-
this.listeners.delete(listener);
|
|
1151
|
-
};
|
|
1247
|
+
get lastError() {
|
|
1248
|
+
return this.cache.lastError;
|
|
1152
1249
|
}
|
|
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
|
-
);
|
|
1250
|
+
spell(texts) {
|
|
1251
|
+
if (texts === null) return null;
|
|
1252
|
+
if (texts !== this.spelledFrom) {
|
|
1253
|
+
this.spelledFrom = texts;
|
|
1254
|
+
this.spelled = spellTextsForOpenClaw(texts);
|
|
1162
1255
|
}
|
|
1163
|
-
this.
|
|
1164
|
-
return texts;
|
|
1256
|
+
return this.spelled;
|
|
1165
1257
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1258
|
+
};
|
|
1259
|
+
async function loadIdentityLine(params) {
|
|
1260
|
+
const cache2 = createTextsCache(params);
|
|
1261
|
+
try {
|
|
1262
|
+
const texts = await cache2.start();
|
|
1263
|
+
return texts ? spellToolsForOpenClaw(texts.identity_line) : null;
|
|
1264
|
+
} catch {
|
|
1265
|
+
return null;
|
|
1266
|
+
} finally {
|
|
1267
|
+
cache2.stop();
|
|
1175
1268
|
}
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1269
|
+
}
|
|
1270
|
+
function cachedIdentityLine(accountId, stateDir) {
|
|
1271
|
+
let raw;
|
|
1272
|
+
try {
|
|
1273
|
+
raw = fs__namespace.readFileSync(textsCachePath(accountId, stateDir), "utf8");
|
|
1274
|
+
} catch {
|
|
1275
|
+
return null;
|
|
1183
1276
|
}
|
|
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?.();
|
|
1277
|
+
try {
|
|
1278
|
+
const entry = JSON.parse(raw);
|
|
1279
|
+
if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null;
|
|
1280
|
+
return spellToolsForOpenClaw(entry.texts.identity_line);
|
|
1281
|
+
} catch {
|
|
1282
|
+
return null;
|
|
1230
1283
|
}
|
|
1231
|
-
};
|
|
1232
|
-
function describe2(err) {
|
|
1233
|
-
return err instanceof Error ? err.message : String(err);
|
|
1234
1284
|
}
|
|
1285
|
+
var isTexts = agentchatme.integration.isTexts;
|
|
1235
1286
|
var cache = /* @__PURE__ */ new Map();
|
|
1236
1287
|
function createSdkClient(params) {
|
|
1237
1288
|
return new agentchatme.AgentChatClient({
|
|
@@ -1815,7 +1866,7 @@ var agentchatSetupWizard = {
|
|
|
1815
1866
|
{
|
|
1816
1867
|
value: "paste",
|
|
1817
1868
|
label: "I already have an API key",
|
|
1818
|
-
hint: "paste
|
|
1869
|
+
hint: "paste ac_\u2026 on the next prompt"
|
|
1819
1870
|
},
|
|
1820
1871
|
{
|
|
1821
1872
|
value: "recover",
|
|
@@ -1886,10 +1937,10 @@ var agentchatSetupWizard = {
|
|
|
1886
1937
|
preferredEnvVar: "AGENTCHAT_API_KEY",
|
|
1887
1938
|
envPrompt: "AGENTCHAT_API_KEY detected in env. Use it?",
|
|
1888
1939
|
keepPrompt: "AgentChat API key already configured. Keep it?",
|
|
1889
|
-
inputPrompt: "Paste your AgentChat API key (
|
|
1940
|
+
inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
|
|
1890
1941
|
helpTitle: "AgentChat API key",
|
|
1891
1942
|
helpLines: [
|
|
1892
|
-
"Format:
|
|
1943
|
+
"Format: ac_ followed by 43 base64url characters. Validated against",
|
|
1893
1944
|
"GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
|
|
1894
1945
|
"of flapping reconnects at runtime."
|
|
1895
1946
|
],
|
|
@@ -2037,9 +2088,646 @@ var agentchatChannelConfigSchema = zod.z.object({
|
|
|
2037
2088
|
function parseChannelConfig(input) {
|
|
2038
2089
|
return agentchatChannelConfigSchema.parse(input);
|
|
2039
2090
|
}
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2091
|
+
var TRAY_LIMIT = 50;
|
|
2092
|
+
function createAfterTurnRecorder(options) {
|
|
2093
|
+
const { client, logger } = options;
|
|
2094
|
+
return async (record, end) => {
|
|
2095
|
+
if (end.status === "still_running" || record.kind === "run") return;
|
|
2096
|
+
let fresh;
|
|
2097
|
+
try {
|
|
2098
|
+
fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true });
|
|
2099
|
+
} catch (err) {
|
|
2100
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn tray read failed \u2014 nothing recorded; the server re-wakes the card");
|
|
2101
|
+
fresh = null;
|
|
2102
|
+
}
|
|
2103
|
+
try {
|
|
2104
|
+
if (record.kind === "reply") {
|
|
2105
|
+
if (!record.card) return;
|
|
2106
|
+
const outcome2 = agentchatme.integration.turnOutcome({
|
|
2107
|
+
turn: end,
|
|
2108
|
+
turnStartedAt: record.startedAt,
|
|
2109
|
+
gateCard: record.card,
|
|
2110
|
+
category: record.category ?? null,
|
|
2111
|
+
freshTray: fresh,
|
|
2112
|
+
silentBefore: 0
|
|
2113
|
+
});
|
|
2114
|
+
const recorded2 = await agentchatme.integration.applyOutcome(client, outcome2);
|
|
2115
|
+
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)");
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
if (!record.invite) return;
|
|
2119
|
+
const outcome = agentchatme.integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 });
|
|
2120
|
+
const recorded = await agentchatme.integration.applyInviteOutcome(client, outcome);
|
|
2121
|
+
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)");
|
|
2122
|
+
} catch (err) {
|
|
2123
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn recording failed \u2014 the card stays on the tray; the server re-wakes it");
|
|
2124
|
+
}
|
|
2125
|
+
};
|
|
2126
|
+
}
|
|
2127
|
+
function cardFromStored(stored) {
|
|
2128
|
+
return { preview: null, ...stored };
|
|
2129
|
+
}
|
|
2130
|
+
function describe3(err) {
|
|
2131
|
+
return err instanceof Error ? err.message : String(err);
|
|
2132
|
+
}
|
|
2133
|
+
var TURN_STORE_FILE = "turns.json";
|
|
2134
|
+
var KEEP_ENDED_MS = 6e4;
|
|
2135
|
+
function storedCard(card, anchor) {
|
|
2136
|
+
return {
|
|
2137
|
+
conversation_id: card.conversation_id,
|
|
2138
|
+
...anchor ? { last_message_id: anchor } : {},
|
|
2139
|
+
...card.your_last_message_at !== void 0 ? { your_last_message_at: card.your_last_message_at } : {},
|
|
2140
|
+
...card.you_owe_reply !== void 0 ? { you_owe_reply: card.you_owe_reply } : {},
|
|
2141
|
+
...card.your_last_decision !== void 0 ? { your_last_decision: card.your_last_decision } : {}
|
|
2142
|
+
};
|
|
2143
|
+
}
|
|
2144
|
+
var TurnStore = class {
|
|
2145
|
+
file;
|
|
2146
|
+
constructor(accountId, stateDir) {
|
|
2147
|
+
this.file = path2__namespace.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE);
|
|
2148
|
+
}
|
|
2149
|
+
/** What the last process left. Empty when there is no file or it cannot be read. */
|
|
2150
|
+
load() {
|
|
2151
|
+
let parsed;
|
|
2152
|
+
try {
|
|
2153
|
+
parsed = JSON.parse(fs__namespace.readFileSync(this.file, "utf8"));
|
|
2154
|
+
} catch {
|
|
2155
|
+
return [];
|
|
2156
|
+
}
|
|
2157
|
+
const turns = parsed?.turns;
|
|
2158
|
+
if (parsed?.version !== 1 || !Array.isArray(turns)) return [];
|
|
2159
|
+
return turns.filter(isStoredTurn);
|
|
2160
|
+
}
|
|
2161
|
+
/** Replace the file with `turns` (removed when empty). Returns false when the write failed. */
|
|
2162
|
+
write(turns) {
|
|
2163
|
+
try {
|
|
2164
|
+
if (turns.length === 0) {
|
|
2165
|
+
fs__namespace.rmSync(this.file, { force: true });
|
|
2166
|
+
return true;
|
|
2167
|
+
}
|
|
2168
|
+
fs__namespace.mkdirSync(path2__namespace.dirname(this.file), { recursive: true });
|
|
2169
|
+
const body = { version: 1, turns };
|
|
2170
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
2171
|
+
fs__namespace.writeFileSync(tmp, `${JSON.stringify(body)}
|
|
2172
|
+
`, { mode: 384 });
|
|
2173
|
+
fs__namespace.renameSync(tmp, this.file);
|
|
2174
|
+
return true;
|
|
2175
|
+
} catch {
|
|
2176
|
+
return false;
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
};
|
|
2180
|
+
function isStoredTurn(value) {
|
|
2181
|
+
const turn = value;
|
|
2182
|
+
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");
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
// src/integration/running.ts
|
|
2186
|
+
var TURN_OVERDUE_MS = 30 * 6e4;
|
|
2187
|
+
var OVERDUE_SLACK_MS = 5e3;
|
|
2188
|
+
function isOverdue(elapsedMs) {
|
|
2189
|
+
return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS;
|
|
2190
|
+
}
|
|
2191
|
+
var MAX_HUNG_TURNS = 2;
|
|
2192
|
+
var OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60;
|
|
2193
|
+
var RESTART_HOLD_MS = 3 * 6e4;
|
|
2194
|
+
var STORED_TURN_MAX_AGE_MS = 24 * 60 * 6e4;
|
|
2195
|
+
var RESTART_END_DETAIL = "the gateway restarted during the turn";
|
|
2196
|
+
function trackerKey(kind, id) {
|
|
2197
|
+
return kind === "reply" ? `conversation:${id}` : kind === "invite" ? `invite:${id}` : `run:${id}`;
|
|
2198
|
+
}
|
|
2199
|
+
function trackedTurn(record) {
|
|
2200
|
+
if (record.kind === "reply") return { kind: "reply", conversationId: record.id, anchor: record.anchor };
|
|
2201
|
+
if (record.kind === "invite") return { kind: "invite", inviteId: record.id };
|
|
2202
|
+
return null;
|
|
2203
|
+
}
|
|
2204
|
+
function storedOf(record) {
|
|
2205
|
+
if (record.kind === "run") return null;
|
|
2206
|
+
return {
|
|
2207
|
+
runId: record.runId,
|
|
2208
|
+
kind: record.kind,
|
|
2209
|
+
id: record.id,
|
|
2210
|
+
anchor: record.anchor,
|
|
2211
|
+
sessionKey: record.sessionKey,
|
|
2212
|
+
startedAt: record.startedAt,
|
|
2213
|
+
...record.firstStartedAt !== void 0 ? { firstStartedAt: record.firstStartedAt } : {},
|
|
2214
|
+
...record.category !== void 0 ? { category: record.category } : {},
|
|
2215
|
+
...record.kind === "reply" && record.card ? { card: storedCard(record.card, record.anchor) } : {}
|
|
2216
|
+
};
|
|
2217
|
+
}
|
|
2218
|
+
function recordOf(stored) {
|
|
2219
|
+
return {
|
|
2220
|
+
runId: stored.runId,
|
|
2221
|
+
kind: stored.kind,
|
|
2222
|
+
id: stored.id,
|
|
2223
|
+
anchor: stored.anchor,
|
|
2224
|
+
sessionKey: stored.sessionKey,
|
|
2225
|
+
startedAt: stored.startedAt,
|
|
2226
|
+
firstStartedAt: stored.firstStartedAt ?? stored.startedAt,
|
|
2227
|
+
owner: "previous-process",
|
|
2228
|
+
...stored.category !== void 0 ? { category: stored.category } : {},
|
|
2229
|
+
...stored.kind === "reply" && stored.card ? { card: cardFromStored(stored.card) } : {},
|
|
2230
|
+
...stored.kind === "invite" ? { invite: { invite_id: stored.id } } : {}
|
|
2231
|
+
};
|
|
2232
|
+
}
|
|
2233
|
+
var AccountTurns = class {
|
|
2234
|
+
/** The kit's tracker for the account, shared by every loop for it. */
|
|
2235
|
+
tracker;
|
|
2236
|
+
entries = /* @__PURE__ */ new Map();
|
|
2237
|
+
/** Turns the last process left in flight, by session key. */
|
|
2238
|
+
adopted = /* @__PURE__ */ new Map();
|
|
2239
|
+
/** Turns OpenClaw is admitting right now. */
|
|
2240
|
+
admitting = /* @__PURE__ */ new Set();
|
|
2241
|
+
/** Ended runs still written to the store (`KEEP_ENDED_MS`). */
|
|
2242
|
+
kept = /* @__PURE__ */ new Map();
|
|
2243
|
+
keptTimer = null;
|
|
2244
|
+
live = null;
|
|
2245
|
+
wiring = {};
|
|
2246
|
+
/** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */
|
|
2247
|
+
lane = 0;
|
|
2248
|
+
now;
|
|
2249
|
+
constructor(options = {}) {
|
|
2250
|
+
this.now = options.now ?? Date.now;
|
|
2251
|
+
this.tracker = new agentchatme.integration.TurnTracker({ now: this.now });
|
|
2252
|
+
this.tracker.onRelease((handle) => {
|
|
2253
|
+
for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true;
|
|
2254
|
+
});
|
|
2255
|
+
}
|
|
2256
|
+
/** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */
|
|
2257
|
+
configure(wiring) {
|
|
2258
|
+
this.wiring = { ...this.wiring, ...wiring };
|
|
2259
|
+
}
|
|
2260
|
+
/** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */
|
|
2261
|
+
setLive(owner, wake, run = (fn) => fn()) {
|
|
2262
|
+
this.live = { owner, wake, run };
|
|
2263
|
+
}
|
|
2264
|
+
clearLive(owner) {
|
|
2265
|
+
if (this.live?.owner === owner) this.live = null;
|
|
2266
|
+
}
|
|
2267
|
+
/** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */
|
|
2268
|
+
admission(kind, id) {
|
|
2269
|
+
const admission = { key: trackerKey(kind, id), released: false };
|
|
2270
|
+
this.admitting.add(admission);
|
|
2271
|
+
return admission;
|
|
2272
|
+
}
|
|
2273
|
+
/** OpenClaw refused the turn: nothing to watch. */
|
|
2274
|
+
admitted(admission) {
|
|
2275
|
+
this.admitting.delete(admission);
|
|
2276
|
+
}
|
|
2277
|
+
/**
|
|
2278
|
+
* A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting
|
|
2279
|
+
* on it when it is handed off or released. `admission`: a turn whose kit
|
|
2280
|
+
* hold was released during admission starts out let go of.
|
|
2281
|
+
*/
|
|
2282
|
+
started(record, options = {}) {
|
|
2283
|
+
const releasedMeanwhile = options.admission?.released === true;
|
|
2284
|
+
if (options.admission) this.admitting.delete(options.admission);
|
|
2285
|
+
this.entries.set(record.runId, {
|
|
2286
|
+
record,
|
|
2287
|
+
state: releasedMeanwhile ? "released" : "kit",
|
|
2288
|
+
handle: null,
|
|
2289
|
+
since: 0,
|
|
2290
|
+
...options.letGo ? { letGo: options.letGo } : {}
|
|
2291
|
+
});
|
|
2292
|
+
this.persist();
|
|
2293
|
+
}
|
|
2294
|
+
run(runId) {
|
|
2295
|
+
return this.entries.get(runId)?.record;
|
|
2296
|
+
}
|
|
2297
|
+
/** Where the run stands (`null`: not a run of this account, or ended). */
|
|
2298
|
+
stateOf(runId) {
|
|
2299
|
+
return this.entries.get(runId)?.state ?? null;
|
|
2300
|
+
}
|
|
2301
|
+
/** Every run OpenClaw has not reported ended that still holds something, oldest first. */
|
|
2302
|
+
runningRuns() {
|
|
2303
|
+
return [...this.entries.values()].filter((entry) => entry.state !== "released").map((entry) => entry.record).sort((a, b) => a.startedAt - b.startedAt);
|
|
2304
|
+
}
|
|
2305
|
+
hungRuns() {
|
|
2306
|
+
return [...this.entries.values()].filter((entry) => entry.state === "hung").map((entry) => entry.record);
|
|
2307
|
+
}
|
|
2308
|
+
get hungCount() {
|
|
2309
|
+
let count = 0;
|
|
2310
|
+
for (const entry of this.entries.values()) if (entry.state === "hung") count += 1;
|
|
2311
|
+
return count;
|
|
2312
|
+
}
|
|
2313
|
+
/** The handed-off gate-off run still going, if any: no new run starts while it lives. */
|
|
2314
|
+
hungSingleRun() {
|
|
2315
|
+
for (const entry of this.entries.values()) if (entry.state === "hung" && entry.record.kind === "run") return entry.record;
|
|
2316
|
+
return null;
|
|
2317
|
+
}
|
|
2318
|
+
/** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */
|
|
2319
|
+
restartHolds() {
|
|
2320
|
+
const holds = [...this.adopted.values()].map((a) => ({
|
|
2321
|
+
record: a.record,
|
|
2322
|
+
until: a.until,
|
|
2323
|
+
watching: null
|
|
2324
|
+
}));
|
|
2325
|
+
for (const entry of this.entries.values()) if (entry.state === "watch") holds.push({ record: entry.record, until: null, watching: entry.record.runId });
|
|
2326
|
+
return holds;
|
|
2327
|
+
}
|
|
2328
|
+
/** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */
|
|
2329
|
+
get laneGeneration() {
|
|
2330
|
+
return this.lane;
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* OpenClaw reported the run ended (`end`: what it did, when known). A turn
|
|
2334
|
+
* held here (handed off, or continued after a restart) gets the after-turn
|
|
2335
|
+
* rule, then its hold drops and the live loop is woken. A turn the kit
|
|
2336
|
+
* still holds is the kit's to record; the live loop is woken once the card
|
|
2337
|
+
* is free, only when an earlier loop started it. A run let go of records
|
|
2338
|
+
* nothing.
|
|
2339
|
+
*/
|
|
2340
|
+
async ended(runId, end) {
|
|
2341
|
+
const entry = this.entries.get(runId);
|
|
2342
|
+
if (!entry) return;
|
|
2343
|
+
this.entries.delete(runId);
|
|
2344
|
+
if (entry.state !== "released") this.keep(entry.record);
|
|
2345
|
+
else this.persist();
|
|
2346
|
+
if (entry.state === "hung" || entry.state === "watch") {
|
|
2347
|
+
try {
|
|
2348
|
+
if (end && this.wiring.recorder && entry.record.kind !== "run") await this.wiring.recorder(entry.record, end);
|
|
2349
|
+
} finally {
|
|
2350
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2351
|
+
this.live?.wake();
|
|
2352
|
+
}
|
|
2353
|
+
return;
|
|
2354
|
+
}
|
|
2355
|
+
if (entry.state === "released" || entry.record.kind === "run") return;
|
|
2356
|
+
if (!this.live || this.live.owner === entry.record.owner) return;
|
|
2357
|
+
this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id));
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Hand a long run off, once, by run id: release the kit's slot for it (its
|
|
2361
|
+
* loop records nothing for it and may start other turns) and hold the
|
|
2362
|
+
* conversation here until the run ends. A gate-off run: the cycle waiting
|
|
2363
|
+
* on it is let go of. A continued run is already held here: it becomes
|
|
2364
|
+
* hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was
|
|
2365
|
+
* handed off now; null when it was already handed off or let go of.
|
|
2366
|
+
*/
|
|
2367
|
+
handOff(runId) {
|
|
2368
|
+
const entry = this.entries.get(runId);
|
|
2369
|
+
if (!entry || entry.state !== "kit" && entry.state !== "watch") return null;
|
|
2370
|
+
const record = entry.record;
|
|
2371
|
+
entry.since = this.now();
|
|
2372
|
+
if (entry.state === "watch") {
|
|
2373
|
+
entry.state = "hung";
|
|
2374
|
+
this.live?.wake();
|
|
2375
|
+
return record;
|
|
2376
|
+
}
|
|
2377
|
+
this.lane += 1;
|
|
2378
|
+
entry.state = "hung";
|
|
2379
|
+
const turn = trackedTurn(record);
|
|
2380
|
+
if (turn === null) {
|
|
2381
|
+
entry.letGo?.();
|
|
2382
|
+
} else {
|
|
2383
|
+
this.tracker.release(trackerKey(record.kind, record.id));
|
|
2384
|
+
entry.handle = this.tracker.begin(turn);
|
|
2385
|
+
if (!entry.handle) entry.state = "released";
|
|
2386
|
+
}
|
|
2387
|
+
this.live?.wake();
|
|
2388
|
+
return entry.state === "hung" ? record : null;
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* An operator lets go of a conversation's (or invite's) turn: a hung hold,
|
|
2392
|
+
* a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn
|
|
2393
|
+
* still running. Its run may still be live and answer: a second reply is
|
|
2394
|
+
* then possible, which is why a turn under 30 minutes (most likely still
|
|
2395
|
+
* working) is refused without `force`. A gate-off run always needs
|
|
2396
|
+
* `force`: it reads the whole tray, so a new run would answer the same
|
|
2397
|
+
* cards while it may still be going.
|
|
2398
|
+
*/
|
|
2399
|
+
release(id, options = {}) {
|
|
2400
|
+
const live = this.live;
|
|
2401
|
+
return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true);
|
|
2402
|
+
}
|
|
2403
|
+
releaseNow(id, force) {
|
|
2404
|
+
const matches = (record) => record.id === id || record.runId === id;
|
|
2405
|
+
for (const entry of this.entries.values()) {
|
|
2406
|
+
if (entry.state !== "hung" || !matches(entry.record)) continue;
|
|
2407
|
+
if (entry.record.kind === "run" && !force) return this.refuseSingleRun(entry.record);
|
|
2408
|
+
entry.state = "released";
|
|
2409
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2410
|
+
entry.handle = null;
|
|
2411
|
+
this.persist();
|
|
2412
|
+
this.live?.wake();
|
|
2413
|
+
return { released: true, what: "hung", key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId };
|
|
2414
|
+
}
|
|
2415
|
+
for (const [sessionKey, adopted] of this.adopted) {
|
|
2416
|
+
if (adopted.record.id !== id) continue;
|
|
2417
|
+
this.finishAdopted(sessionKey);
|
|
2418
|
+
return { released: true, what: "restart", key: trackerKey(adopted.record.kind, adopted.record.id), runId: null };
|
|
2419
|
+
}
|
|
2420
|
+
for (const entry of this.entries.values()) {
|
|
2421
|
+
if (entry.state !== "kit" && entry.state !== "watch" || !matches(entry.record)) continue;
|
|
2422
|
+
const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force);
|
|
2423
|
+
if (refused) return refused;
|
|
2424
|
+
const key = trackerKey(entry.record.kind, entry.record.id);
|
|
2425
|
+
if (entry.state === "watch") {
|
|
2426
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2427
|
+
entry.handle = null;
|
|
2428
|
+
} else {
|
|
2429
|
+
this.lane += 1;
|
|
2430
|
+
if (entry.record.kind === "run") entry.letGo?.();
|
|
2431
|
+
else this.tracker.release(key);
|
|
2432
|
+
}
|
|
2433
|
+
entry.state = "released";
|
|
2434
|
+
this.persist();
|
|
2435
|
+
this.live?.wake();
|
|
2436
|
+
return { released: true, what: "running", key, runId: entry.record.runId };
|
|
2437
|
+
}
|
|
2438
|
+
for (const held of this.tracker.running()) {
|
|
2439
|
+
const heldId = held.kind === "reply" ? held.conversationId : held.inviteId;
|
|
2440
|
+
if (heldId !== id) continue;
|
|
2441
|
+
const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force);
|
|
2442
|
+
if (refused) return refused;
|
|
2443
|
+
this.lane += 1;
|
|
2444
|
+
const key = trackerKey(held.kind, heldId);
|
|
2445
|
+
if (this.tracker.release(key)) {
|
|
2446
|
+
this.live?.wake();
|
|
2447
|
+
return { released: true, what: "running", key, runId: null };
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
return { released: false, reason: `no turn holds ${id}` };
|
|
2451
|
+
}
|
|
2452
|
+
refuseYoung(kind, id, startedAt, force) {
|
|
2453
|
+
const age = this.now() - startedAt;
|
|
2454
|
+
if (force || age >= TURN_OVERDUE_MS) return null;
|
|
2455
|
+
return {
|
|
2456
|
+
released: false,
|
|
2457
|
+
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`
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
refuseSingleRun(record) {
|
|
2461
|
+
return {
|
|
2462
|
+
released: false,
|
|
2463
|
+
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`
|
|
2464
|
+
};
|
|
2465
|
+
}
|
|
2466
|
+
/**
|
|
2467
|
+
* Adopt the turns the last process left in flight (the store). Each one's
|
|
2468
|
+
* conversation (or invite) is held at once — before the loop's first gate —
|
|
2469
|
+
* for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended
|
|
2470
|
+
* run did now and again when the hold expires. A run OpenClaw starts in the
|
|
2471
|
+
* turn's session meanwhile (`observeRun`) takes the hold over. A turn first
|
|
2472
|
+
* started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what
|
|
2473
|
+
* was adopted.
|
|
2474
|
+
*/
|
|
2475
|
+
adopt(stored = this.wiring.store?.load() ?? []) {
|
|
2476
|
+
const adopted = [];
|
|
2477
|
+
const now = this.now();
|
|
2478
|
+
for (const turn of stored) {
|
|
2479
|
+
if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue;
|
|
2480
|
+
const first = turn.firstStartedAt ?? turn.startedAt;
|
|
2481
|
+
if (now - first > STORED_TURN_MAX_AGE_MS) {
|
|
2482
|
+
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");
|
|
2483
|
+
continue;
|
|
2484
|
+
}
|
|
2485
|
+
const record = recordOf(turn);
|
|
2486
|
+
const tracked = trackedTurn(record);
|
|
2487
|
+
const handle = tracked ? this.tracker.begin(tracked) : null;
|
|
2488
|
+
if (!handle) continue;
|
|
2489
|
+
const entry = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null };
|
|
2490
|
+
this.adopted.set(turn.sessionKey, entry);
|
|
2491
|
+
entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS);
|
|
2492
|
+
entry.timer.unref?.();
|
|
2493
|
+
adopted.push(record);
|
|
2494
|
+
void this.recordRestartEnded(entry);
|
|
2495
|
+
}
|
|
2496
|
+
this.persist();
|
|
2497
|
+
return adopted;
|
|
2498
|
+
}
|
|
2499
|
+
/**
|
|
2500
|
+
* A run started in some session (the `model_call_started` hook). One in
|
|
2501
|
+
* the session of a turn adopted after a restart is OpenClaw continuing
|
|
2502
|
+
* that turn: it takes the hold over as a turn of its own (`watch`), handed
|
|
2503
|
+
* off past `TURN_OVERDUE_MS` like any other.
|
|
2504
|
+
*/
|
|
2505
|
+
observeRun(runId, sessionKey) {
|
|
2506
|
+
if (!sessionKey || this.entries.has(runId)) return;
|
|
2507
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2508
|
+
if (!adopted) return;
|
|
2509
|
+
this.adopted.delete(sessionKey);
|
|
2510
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2511
|
+
const record = { ...adopted.record, runId, startedAt: this.now(), owner: "restart" };
|
|
2512
|
+
this.entries.set(runId, { record, state: "watch", handle: adopted.handle, since: 0 });
|
|
2513
|
+
this.persist();
|
|
2514
|
+
this.wiring.logger?.info(
|
|
2515
|
+
{ runId, sessionKey, [record.kind === "reply" ? "conversationId" : "inviteId"]: record.id },
|
|
2516
|
+
"OpenClaw continued a turn session after the restart \u2014 its conversation stays held until that run ends"
|
|
2517
|
+
);
|
|
2518
|
+
void this.watchContinued(record);
|
|
2519
|
+
}
|
|
2520
|
+
async watchContinued(record) {
|
|
2521
|
+
let end = null;
|
|
2522
|
+
try {
|
|
2523
|
+
end = this.wiring.watch ? await this.wiring.watch(record) : null;
|
|
2524
|
+
} catch {
|
|
2525
|
+
end = null;
|
|
2526
|
+
}
|
|
2527
|
+
if (end === null) return;
|
|
2528
|
+
await this.ended(record.runId, end);
|
|
2529
|
+
}
|
|
2530
|
+
async recordRestartEnded(adopted) {
|
|
2531
|
+
const { record } = adopted;
|
|
2532
|
+
let calls = null;
|
|
2533
|
+
try {
|
|
2534
|
+
calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null;
|
|
2535
|
+
} catch {
|
|
2536
|
+
calls = null;
|
|
2537
|
+
}
|
|
2538
|
+
adopted.end = { status: "failed", agentchatCalls: calls, detail: RESTART_END_DETAIL };
|
|
2539
|
+
if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return;
|
|
2540
|
+
await this.wiring.recorder(record, adopted.end);
|
|
2541
|
+
}
|
|
2542
|
+
/**
|
|
2543
|
+
* The hold expired with nothing continuing the turn: the after-turn rule
|
|
2544
|
+
* once more — the resumed main session may have answered the card
|
|
2545
|
+
* meanwhile — then the conversation is free.
|
|
2546
|
+
*/
|
|
2547
|
+
expireAdopted(sessionKey, adopted) {
|
|
2548
|
+
if (this.adopted.get(sessionKey) !== adopted) return;
|
|
2549
|
+
void (async () => {
|
|
2550
|
+
try {
|
|
2551
|
+
if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: "failed", agentchatCalls: null, detail: RESTART_END_DETAIL });
|
|
2552
|
+
} catch {
|
|
2553
|
+
}
|
|
2554
|
+
if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey);
|
|
2555
|
+
})();
|
|
2556
|
+
}
|
|
2557
|
+
finishAdopted(sessionKey) {
|
|
2558
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2559
|
+
if (!adopted) return;
|
|
2560
|
+
this.adopted.delete(sessionKey);
|
|
2561
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2562
|
+
this.tracker.end(adopted.handle);
|
|
2563
|
+
this.persist();
|
|
2564
|
+
this.live?.wake();
|
|
2565
|
+
}
|
|
2566
|
+
/** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */
|
|
2567
|
+
keep(record) {
|
|
2568
|
+
const turn = storedOf(record);
|
|
2569
|
+
if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() });
|
|
2570
|
+
this.persist();
|
|
2571
|
+
if (!this.keptTimer) this.schedulePrune();
|
|
2572
|
+
}
|
|
2573
|
+
/** The next prune at the oldest kept entry's expiry. */
|
|
2574
|
+
schedulePrune() {
|
|
2575
|
+
let oldest = Infinity;
|
|
2576
|
+
for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt);
|
|
2577
|
+
if (oldest === Infinity) return;
|
|
2578
|
+
this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()));
|
|
2579
|
+
this.keptTimer.unref?.();
|
|
2580
|
+
}
|
|
2581
|
+
pruneKept() {
|
|
2582
|
+
this.keptTimer = null;
|
|
2583
|
+
const cutoff = this.now() - KEEP_ENDED_MS;
|
|
2584
|
+
for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId);
|
|
2585
|
+
this.persist();
|
|
2586
|
+
this.schedulePrune();
|
|
2587
|
+
}
|
|
2588
|
+
persist() {
|
|
2589
|
+
const store = this.wiring.store;
|
|
2590
|
+
if (!store) return;
|
|
2591
|
+
const turns = /* @__PURE__ */ new Map();
|
|
2592
|
+
for (const entry of this.entries.values()) {
|
|
2593
|
+
if (entry.state === "released") continue;
|
|
2594
|
+
const turn = storedOf(entry.record);
|
|
2595
|
+
if (turn) turns.set(turn.runId, turn);
|
|
2596
|
+
}
|
|
2597
|
+
for (const [runId, kept] of this.kept) turns.set(runId, kept.turn);
|
|
2598
|
+
for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored);
|
|
2599
|
+
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)");
|
|
2600
|
+
}
|
|
2601
|
+
wakeWhenFree(key, attempts = 300) {
|
|
2602
|
+
const held = key.startsWith("conversation:") ? this.tracker.conversationRunning(key.slice("conversation:".length)) : this.tracker.inviteRunning(key.slice("invite:".length));
|
|
2603
|
+
if (!held || attempts <= 0) {
|
|
2604
|
+
this.live?.wake();
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100);
|
|
2608
|
+
timer.unref?.();
|
|
2609
|
+
}
|
|
2610
|
+
};
|
|
2611
|
+
var accounts = /* @__PURE__ */ new Map();
|
|
2612
|
+
function accountTurns(accountId) {
|
|
2613
|
+
let turns = accounts.get(accountId);
|
|
2614
|
+
if (!turns) {
|
|
2615
|
+
turns = new AccountTurns();
|
|
2616
|
+
accounts.set(accountId, turns);
|
|
2617
|
+
}
|
|
2618
|
+
return turns;
|
|
2619
|
+
}
|
|
2620
|
+
function findAccountTurns(accountId) {
|
|
2621
|
+
return accounts.get(accountId);
|
|
2622
|
+
}
|
|
2623
|
+
function trackerFor(accountId) {
|
|
2624
|
+
return accountTurns(accountId).tracker;
|
|
2625
|
+
}
|
|
2626
|
+
function observeRunStarted(runId, sessionKey) {
|
|
2627
|
+
if (typeof runId !== "string" || runId.length === 0 || typeof sessionKey !== "string" || sessionKey.length === 0) return;
|
|
2628
|
+
for (const turns of accounts.values()) turns.observeRun(runId, sessionKey);
|
|
2629
|
+
}
|
|
2630
|
+
function runDeadline(cfg) {
|
|
2631
|
+
const value = cfg?.agents?.defaults?.timeoutSeconds;
|
|
2632
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true };
|
|
2633
|
+
return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false };
|
|
2634
|
+
}
|
|
2635
|
+
function whatOf(kind, id) {
|
|
2636
|
+
return kind === "reply" ? `conversation ${id}` : kind === "invite" ? `invite ${id}` : `the gate-off run ${id}`;
|
|
2637
|
+
}
|
|
2638
|
+
function deadlineText(cfg) {
|
|
2639
|
+
const deadline = runDeadline(cfg);
|
|
2640
|
+
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)"}`;
|
|
2641
|
+
}
|
|
2642
|
+
function overdueTurnLine(turn, cfg) {
|
|
2643
|
+
const minutes = Math.round(turn.elapsedMs / 6e4);
|
|
2644
|
+
if (turn.kind === "run") {
|
|
2645
|
+
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)}`;
|
|
2646
|
+
}
|
|
2647
|
+
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`;
|
|
2648
|
+
}
|
|
2649
|
+
function overdueTurnLines(runs, cfg, now = Date.now()) {
|
|
2650
|
+
return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg));
|
|
2651
|
+
}
|
|
2652
|
+
function restartHoldLines(turns, now = Date.now()) {
|
|
2653
|
+
return turns.restartHolds().map(
|
|
2654
|
+
({ 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`
|
|
2655
|
+
);
|
|
2656
|
+
}
|
|
2657
|
+
function hungTurnsReason(turns, cfg, now = Date.now()) {
|
|
2658
|
+
const single = turns.hungSingleRun();
|
|
2659
|
+
if (single) {
|
|
2660
|
+
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)`;
|
|
2661
|
+
}
|
|
2662
|
+
if (turns.hungCount < MAX_HUNG_TURNS) return null;
|
|
2663
|
+
const held = turns.hungRuns().map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 6e4)} min`).join(", ");
|
|
2664
|
+
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`;
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2667
|
+
// src/binding/release.ts
|
|
2668
|
+
var RELEASE_METHOD = "agentchat.release";
|
|
2669
|
+
function releaseTurnFor(params) {
|
|
2670
|
+
const id = typeof params.id === "string" ? params.id.trim() : "";
|
|
2671
|
+
if (!id) return { ok: false, error: "a conversation (or invite) id is required" };
|
|
2672
|
+
const accountId = typeof params.accountId === "string" && params.accountId.trim() ? params.accountId.trim() : "default";
|
|
2673
|
+
const turns = findAccountTurns(accountId);
|
|
2674
|
+
if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account "${accountId}" has no turns in this gateway` } };
|
|
2675
|
+
return { ok: true, result: turns.release(id, { force: params.force === true }) };
|
|
2676
|
+
}
|
|
2677
|
+
function registerReleaseGatewayMethod(api) {
|
|
2678
|
+
api.registerGatewayMethod(
|
|
2679
|
+
RELEASE_METHOD,
|
|
2680
|
+
({ params, respond }) => {
|
|
2681
|
+
const outcome = releaseTurnFor(params);
|
|
2682
|
+
if (!outcome.ok) {
|
|
2683
|
+
respond(false, void 0, { code: "INVALID_REQUEST", message: outcome.error });
|
|
2684
|
+
return;
|
|
2685
|
+
}
|
|
2686
|
+
respond(true, outcome.result);
|
|
2687
|
+
},
|
|
2688
|
+
{ scope: "operator.admin" }
|
|
2689
|
+
);
|
|
2690
|
+
}
|
|
2691
|
+
function registerReleaseCli(api) {
|
|
2692
|
+
api.registerCli(
|
|
2693
|
+
({ program }) => {
|
|
2694
|
+
const root = program.command(AGENTCHAT_CHANNEL_ID).description("The AgentChat integration");
|
|
2695
|
+
root.command("release <id>").description(
|
|
2696
|
+
`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.`
|
|
2697
|
+
).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) => {
|
|
2698
|
+
const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime');
|
|
2699
|
+
const result = await callGatewayFromCli(
|
|
2700
|
+
RELEASE_METHOD,
|
|
2701
|
+
{ ...opts.url ? { url: opts.url } : {}, ...opts.token ? { token: opts.token } : {}, ...opts.json ? { json: true } : {} },
|
|
2702
|
+
{ id, accountId: opts.account ?? "default", ...opts.force ? { force: true } : {} }
|
|
2703
|
+
);
|
|
2704
|
+
process.stdout.write(opts.json ? `${JSON.stringify(result)}
|
|
2705
|
+
` : `${releaseLine(id, result)}
|
|
2706
|
+
`);
|
|
2707
|
+
});
|
|
2708
|
+
},
|
|
2709
|
+
{
|
|
2710
|
+
commands: [AGENTCHAT_CHANNEL_ID],
|
|
2711
|
+
descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: "The AgentChat integration (release a hung turn)", hasSubcommands: true }]
|
|
2712
|
+
}
|
|
2713
|
+
);
|
|
2714
|
+
}
|
|
2715
|
+
function releaseLine(id, result) {
|
|
2716
|
+
if (!result?.released) return `nothing released: ${result?.reason ?? "unknown"}`;
|
|
2717
|
+
if (result.what === "restart") return `released ${id} (held after a gateway restart) \u2014 it may be gated again now`;
|
|
2718
|
+
const what = result.what === "hung" ? "a hung turn" : "a running turn";
|
|
2719
|
+
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`;
|
|
2720
|
+
}
|
|
2721
|
+
|
|
2722
|
+
// src/binding/run-observer.ts
|
|
2723
|
+
function registerRunObserver(api) {
|
|
2724
|
+
api.on("model_call_started", (event, ctx) => {
|
|
2725
|
+
observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey);
|
|
2726
|
+
});
|
|
2727
|
+
}
|
|
2728
|
+
function createLogger(options) {
|
|
2729
|
+
if (options.delegate) {
|
|
2730
|
+
return options.delegate;
|
|
2043
2731
|
}
|
|
2044
2732
|
const pinoLogger = pino__default.default({
|
|
2045
2733
|
level: options.level,
|
|
@@ -2135,85 +2823,12 @@ function createNoopMetrics() {
|
|
|
2135
2823
|
incWake: () => void 0
|
|
2136
2824
|
};
|
|
2137
2825
|
}
|
|
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
2826
|
|
|
2214
2827
|
// src/integration/socket.ts
|
|
2215
2828
|
function wakeSourceOf(reason) {
|
|
2216
|
-
|
|
2829
|
+
if (reason === "reminder") return "reminder";
|
|
2830
|
+
if (reason === "unanswered") return "unanswered";
|
|
2831
|
+
return "other";
|
|
2217
2832
|
}
|
|
2218
2833
|
function realtimeOptionsFor(config, extra = {}) {
|
|
2219
2834
|
return {
|
|
@@ -2221,6 +2836,10 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2221
2836
|
baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
|
|
2222
2837
|
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
2223
2838
|
ackOnReceipt: true,
|
|
2839
|
+
// `rewake`: the server re-wakes this socket while cards stay unanswered
|
|
2840
|
+
// (contract v1, D3) — the integration keeps no retry ladder of its own.
|
|
2841
|
+
// `heartbeat` is offered by default (the idle watchdog's proof of life).
|
|
2842
|
+
capabilities: { rewake: true },
|
|
2224
2843
|
reconnect: true,
|
|
2225
2844
|
reconnectInterval: config.reconnect.initialBackoffMs,
|
|
2226
2845
|
maxReconnectInterval: config.reconnect.maxBackoffMs,
|
|
@@ -2229,169 +2848,118 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2229
2848
|
};
|
|
2230
2849
|
}
|
|
2231
2850
|
var IntegrationSocket = class {
|
|
2232
|
-
|
|
2851
|
+
/** The SDK client: handed to the receive loop, which connects and disconnects it. */
|
|
2852
|
+
realtime;
|
|
2233
2853
|
logger;
|
|
2234
2854
|
handlers;
|
|
2235
2855
|
metrics;
|
|
2236
|
-
client;
|
|
2237
|
-
createRealtime;
|
|
2238
|
-
webSocket;
|
|
2239
2856
|
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. */
|
|
2857
|
+
/** The SDK's state as last reported through its `state` event. */
|
|
2243
2858
|
state = "idle";
|
|
2244
2859
|
connectedAt = null;
|
|
2860
|
+
bound = false;
|
|
2245
2861
|
stopping = false;
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
wakes = 0;
|
|
2249
|
-
invites = 0;
|
|
2862
|
+
unbind = [];
|
|
2863
|
+
wakeFrames = 0;
|
|
2250
2864
|
disconnects = 0;
|
|
2251
2865
|
constructor(options) {
|
|
2252
|
-
this.config = options.config;
|
|
2253
2866
|
this.logger = options.logger.child({ component: "socket" });
|
|
2254
2867
|
this.handlers = options.handlers ?? {};
|
|
2255
2868
|
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
2869
|
this.now = options.now ?? Date.now;
|
|
2260
|
-
|
|
2870
|
+
const create = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
|
|
2871
|
+
this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }));
|
|
2261
2872
|
this.metrics.setConnectionState(this.state);
|
|
2262
2873
|
}
|
|
2263
|
-
/**
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2874
|
+
/** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */
|
|
2875
|
+
bind() {
|
|
2876
|
+
if (this.bound || this.stopping) return;
|
|
2877
|
+
this.bound = true;
|
|
2878
|
+
const realtime = this.realtime;
|
|
2879
|
+
this.unbind.push(
|
|
2880
|
+
realtime.on("state", (next, prev) => this.onState(next, prev)),
|
|
2881
|
+
realtime.onConnect(() => {
|
|
2882
|
+
const at = this.now();
|
|
2883
|
+
this.connectedAt = at;
|
|
2884
|
+
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2885
|
+
this.metrics.incWake({ source: "connect" });
|
|
2886
|
+
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2887
|
+
}),
|
|
2888
|
+
realtime.onDisconnect((info) => {
|
|
2889
|
+
if (this.stopping) return;
|
|
2890
|
+
this.disconnects += 1;
|
|
2891
|
+
this.connectedAt = null;
|
|
2892
|
+
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2893
|
+
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2894
|
+
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2895
|
+
}),
|
|
2896
|
+
realtime.on("blocked", (info) => {
|
|
2897
|
+
if (this.stopping) return;
|
|
2898
|
+
this.metrics.incError({ errorClass: "auth" });
|
|
2899
|
+
this.logger.warn(
|
|
2900
|
+
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2901
|
+
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2902
|
+
);
|
|
2903
|
+
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2904
|
+
}),
|
|
2905
|
+
realtime.onError((error) => {
|
|
2906
|
+
if (this.stopping) return;
|
|
2907
|
+
if (realtime.state === "blocked") {
|
|
2908
|
+
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2909
|
+
return;
|
|
2910
|
+
}
|
|
2911
|
+
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2912
|
+
this.logger.debug({ err: error.message }, "socket error");
|
|
2913
|
+
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2914
|
+
}),
|
|
2915
|
+
// The loop turns a wake frame into a cycle; here it is only labelled
|
|
2916
|
+
// by its reason for the log line and the metric.
|
|
2917
|
+
realtime.on("wake", (frame) => {
|
|
2918
|
+
this.wakeFrames += 1;
|
|
2919
|
+
const payload = frame.payload ?? {};
|
|
2920
|
+
const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : void 0;
|
|
2921
|
+
this.metrics.incWake({ source: wakeSourceOf(payload.reason) });
|
|
2922
|
+
this.logger.info(
|
|
2923
|
+
{
|
|
2924
|
+
reason: payload.reason,
|
|
2925
|
+
step: payload.step,
|
|
2926
|
+
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2927
|
+
...conversations !== void 0 ? { conversations } : {}
|
|
2928
|
+
},
|
|
2929
|
+
"wake \u2014 server wake frame"
|
|
2930
|
+
);
|
|
2931
|
+
})
|
|
2932
|
+
);
|
|
2278
2933
|
}
|
|
2279
|
-
/**
|
|
2280
|
-
|
|
2934
|
+
/** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */
|
|
2935
|
+
stopped() {
|
|
2281
2936
|
this.stopping = true;
|
|
2282
|
-
const realtime = this.realtime;
|
|
2283
|
-
this.realtime = null;
|
|
2284
2937
|
this.connectedAt = null;
|
|
2285
|
-
|
|
2938
|
+
for (const off of this.unbind.splice(0)) {
|
|
2286
2939
|
try {
|
|
2287
|
-
|
|
2288
|
-
} catch
|
|
2289
|
-
this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
|
|
2940
|
+
off();
|
|
2941
|
+
} catch {
|
|
2290
2942
|
}
|
|
2291
2943
|
}
|
|
2292
2944
|
if (this.state !== "stopped") this.onState("stopped", this.state);
|
|
2293
2945
|
}
|
|
2294
2946
|
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));
|
|
2947
|
+
return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } };
|
|
2381
2948
|
}
|
|
2382
2949
|
/** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
|
|
2383
2950
|
onState(next, prev) {
|
|
2951
|
+
if (this.state === next) return;
|
|
2384
2952
|
this.state = next;
|
|
2385
2953
|
this.metrics.setConnectionState(next);
|
|
2386
2954
|
this.logger.debug({ from: prev, to: next }, "socket state");
|
|
2387
2955
|
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2388
2956
|
}
|
|
2389
|
-
/** A failing handler never takes the socket down
|
|
2957
|
+
/** A failing handler never takes the socket down. */
|
|
2390
2958
|
guard(name, fn) {
|
|
2391
2959
|
try {
|
|
2392
2960
|
fn();
|
|
2393
2961
|
} catch (err) {
|
|
2394
|
-
this.logger.error({ err:
|
|
2962
|
+
this.logger.error({ err: describe4(err), handler: name }, "handler threw \u2014 continuing");
|
|
2395
2963
|
}
|
|
2396
2964
|
}
|
|
2397
2965
|
};
|
|
@@ -2402,7 +2970,7 @@ function classifyRealtimeError(error) {
|
|
|
2402
2970
|
if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
|
|
2403
2971
|
return "other";
|
|
2404
2972
|
}
|
|
2405
|
-
function
|
|
2973
|
+
function describe4(err) {
|
|
2406
2974
|
return err instanceof Error ? err.message : String(err);
|
|
2407
2975
|
}
|
|
2408
2976
|
|
|
@@ -2432,8 +3000,6 @@ function registerIntegration(params) {
|
|
|
2432
3000
|
}
|
|
2433
3001
|
let built = null;
|
|
2434
3002
|
const handlers = {
|
|
2435
|
-
onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
|
|
2436
|
-
onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
|
|
2437
3003
|
onConnected: (at) => built?.handlers.onConnected?.(at),
|
|
2438
3004
|
onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
|
|
2439
3005
|
onBlocked: (info) => built?.handlers.onBlocked?.(info),
|
|
@@ -2445,19 +3011,20 @@ function registerIntegration(params) {
|
|
|
2445
3011
|
built = params.build(socket);
|
|
2446
3012
|
const entry = {
|
|
2447
3013
|
socket,
|
|
2448
|
-
|
|
3014
|
+
loop: built.loop,
|
|
2449
3015
|
texts: built.texts ?? null,
|
|
3016
|
+
textsCache: built.textsCache ?? null,
|
|
2450
3017
|
metrics: params.socketOptions?.metrics ?? null,
|
|
2451
3018
|
config: params.config,
|
|
2452
3019
|
logger: params.logger
|
|
2453
3020
|
};
|
|
2454
3021
|
registry.set(params.accountId, entry);
|
|
3022
|
+
socket.bind();
|
|
2455
3023
|
try {
|
|
2456
|
-
await
|
|
3024
|
+
await built.loop?.loop.start();
|
|
2457
3025
|
} catch (err) {
|
|
2458
3026
|
registry.delete(params.accountId);
|
|
2459
|
-
|
|
2460
|
-
built.texts?.stop();
|
|
3027
|
+
await stopEntry(entry);
|
|
2461
3028
|
throw err;
|
|
2462
3029
|
}
|
|
2463
3030
|
return entry;
|
|
@@ -2472,591 +3039,272 @@ function unregisterIntegration(accountId) {
|
|
|
2472
3039
|
});
|
|
2473
3040
|
}
|
|
2474
3041
|
async function stopEntry(entry) {
|
|
2475
|
-
entry.invoker?.stop();
|
|
2476
|
-
entry.texts?.stop();
|
|
2477
3042
|
try {
|
|
2478
|
-
await entry.
|
|
3043
|
+
await entry.loop?.stop();
|
|
2479
3044
|
} catch (err) {
|
|
2480
|
-
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "
|
|
3045
|
+
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "receive loop stop threw during unregister");
|
|
2481
3046
|
}
|
|
3047
|
+
if (!entry.loop) {
|
|
3048
|
+
try {
|
|
3049
|
+
entry.socket.realtime.disconnect();
|
|
3050
|
+
} catch {
|
|
3051
|
+
}
|
|
3052
|
+
}
|
|
3053
|
+
entry.socket.stopped();
|
|
3054
|
+
entry.textsCache?.stop();
|
|
2482
3055
|
}
|
|
2483
3056
|
function getIntegration(accountId) {
|
|
2484
3057
|
return registry.get(accountId);
|
|
2485
3058
|
}
|
|
3059
|
+
function listActiveAccounts() {
|
|
3060
|
+
return [...registry.keys()];
|
|
3061
|
+
}
|
|
2486
3062
|
|
|
2487
|
-
// src/integration/
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
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;
|
|
2588
|
-
try {
|
|
2589
|
-
this.onFire();
|
|
2590
|
-
} catch {
|
|
3063
|
+
// src/integration/turns.ts
|
|
3064
|
+
function createLoopTurnStarter(options) {
|
|
3065
|
+
const now = options.now ?? Date.now;
|
|
3066
|
+
return async (request) => {
|
|
3067
|
+
const id = request.kind === "reply" ? request.conversationId : request.invite.invite_id;
|
|
3068
|
+
const sessionKey = request.kind === "reply" ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now());
|
|
3069
|
+
const watch = options.turns.admission(request.kind, id);
|
|
3070
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
3071
|
+
if (!admission.ran) {
|
|
3072
|
+
options.turns.admitted(watch);
|
|
3073
|
+
return { started: false, error: admission.error };
|
|
2591
3074
|
}
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
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"
|
|
3075
|
+
options.turns.started({
|
|
3076
|
+
runId: admission.runId,
|
|
3077
|
+
kind: request.kind,
|
|
3078
|
+
id,
|
|
3079
|
+
anchor: request.kind === "reply" ? request.anchor : null,
|
|
3080
|
+
sessionKey: admission.sessionKey,
|
|
3081
|
+
startedAt: now(),
|
|
3082
|
+
owner: options.owner,
|
|
3083
|
+
// What the after-turn rule compares when the turn ends outside the
|
|
3084
|
+
// kit's watch (handed off, or after a restart).
|
|
3085
|
+
...request.kind === "reply" ? { card: request.card, category: request.category } : { invite: request.invite }
|
|
3086
|
+
}, { admission: watch });
|
|
3087
|
+
options.logger.info(
|
|
3088
|
+
{ kind: request.kind, sessionKey, runId: admission.runId, ...request.kind === "reply" ? { conversationId: id } : { inviteId: id } },
|
|
3089
|
+
request.kind === "reply" ? "turn start" : "group-invite turn start"
|
|
2679
3090
|
);
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
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;
|
|
3091
|
+
const done = admission.done.then((outcome) => {
|
|
3092
|
+
if (outcome.status === "gone") {
|
|
3093
|
+
options.logger.warn({ sessionKey, runId: outcome.runId }, "turn end not confirmed: the plugin runtime is gone \u2014 its card stays held");
|
|
3094
|
+
return { status: "still_running", detail: "the plugin runtime is gone" };
|
|
2735
3095
|
}
|
|
2736
|
-
|
|
3096
|
+
const end = turnEndOf(outcome);
|
|
3097
|
+
void options.turns.ended(admission.runId, end);
|
|
3098
|
+
options.logger[outcome.status === "ok" ? "info" : "warn"](
|
|
3099
|
+
{
|
|
3100
|
+
sessionKey,
|
|
3101
|
+
runId: outcome.runId,
|
|
3102
|
+
status: outcome.status,
|
|
3103
|
+
...outcome.error ? { error: outcome.error } : {},
|
|
3104
|
+
...outcome.elapsedMs !== void 0 ? { elapsedMs: outcome.elapsedMs } : {},
|
|
3105
|
+
agentchatCalls: outcome.agentchatCalls ?? null
|
|
3106
|
+
},
|
|
3107
|
+
request.kind === "reply" ? "turn ended (final text discarded; the send is a hosted-tool call)" : "group-invite turn ended"
|
|
3108
|
+
);
|
|
3109
|
+
return end;
|
|
3110
|
+
});
|
|
3111
|
+
return { started: true, done };
|
|
3112
|
+
};
|
|
3113
|
+
}
|
|
3114
|
+
function turnEndOf(outcome) {
|
|
3115
|
+
const agentchatCalls = outcome.agentchatCalls ?? null;
|
|
3116
|
+
if (outcome.status === "ok" && !outcome.error) return { status: "completed", agentchatCalls };
|
|
3117
|
+
return { status: "failed", agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? "unknown"}` };
|
|
3118
|
+
}
|
|
3119
|
+
|
|
3120
|
+
// src/integration/loop.ts
|
|
3121
|
+
var generation = 0;
|
|
3122
|
+
function createIntegrationLoop(options) {
|
|
3123
|
+
const logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
3124
|
+
const metrics = options.metrics ?? createNoopMetrics();
|
|
3125
|
+
const now = options.now ?? Date.now;
|
|
3126
|
+
generation += 1;
|
|
3127
|
+
const owner = `${options.accountId}#${generation}`;
|
|
3128
|
+
const gateEnabled = options.gateEnabled ?? true;
|
|
3129
|
+
let unreadyReason = null;
|
|
3130
|
+
const readiness = options.readiness ? () => {
|
|
3131
|
+
const ready = options.readiness();
|
|
3132
|
+
if (ready.ready) {
|
|
3133
|
+
if (unreadyReason !== null) logger.info({}, "turns can start again \u2014 gating resumes");
|
|
3134
|
+
unreadyReason = null;
|
|
3135
|
+
return ready;
|
|
2737
3136
|
}
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
}
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
}
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
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) });
|
|
2801
|
-
if (!admission.ran) {
|
|
2802
|
-
this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, "turn not started \u2014 re-waking later");
|
|
2803
|
-
} else {
|
|
2804
|
-
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
|
|
2805
|
-
this.retryRung = 0;
|
|
3137
|
+
if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, "not gating \u2014 no turn can start now; the cards wait on the tray");
|
|
3138
|
+
unreadyReason = ready.reason;
|
|
3139
|
+
return ready;
|
|
3140
|
+
} : void 0;
|
|
3141
|
+
const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now });
|
|
3142
|
+
const loop = new agentchatme.integration.ReceiveLoop({
|
|
3143
|
+
client: options.client,
|
|
3144
|
+
texts: options.texts,
|
|
3145
|
+
mode: gateEnabled ? "gateCall" : "singleRun",
|
|
3146
|
+
...gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) },
|
|
3147
|
+
socket: options.socket,
|
|
3148
|
+
...options.handle ? { handle: options.handle } : {},
|
|
3149
|
+
toolNamer: OPENCLAW_TOOL_NAMER,
|
|
3150
|
+
// One account's turns run on one OpenClaw lane anyway; one slot keeps
|
|
3151
|
+
// the rest held out of the gate (no second model call decides them).
|
|
3152
|
+
maxConcurrentTurns: 1,
|
|
3153
|
+
tracker: options.turns.tracker,
|
|
3154
|
+
...readiness ? { readiness } : {},
|
|
3155
|
+
...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {},
|
|
3156
|
+
...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
|
|
3157
|
+
...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
|
|
3158
|
+
now,
|
|
3159
|
+
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
3160
|
+
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {},
|
|
3161
|
+
onEvent: (event) => logEvent(event, logger, metrics)
|
|
3162
|
+
});
|
|
3163
|
+
const inLoopContext = async_hooks.AsyncLocalStorage.snapshot();
|
|
3164
|
+
options.turns.setLive(
|
|
3165
|
+
owner,
|
|
3166
|
+
() => inLoopContext(() => loop.wake()),
|
|
3167
|
+
(fn) => inLoopContext(fn)
|
|
3168
|
+
);
|
|
3169
|
+
return {
|
|
3170
|
+
loop,
|
|
3171
|
+
async stop() {
|
|
3172
|
+
options.turns.clearLive(owner);
|
|
3173
|
+
await loop.stop();
|
|
2806
3174
|
}
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
const latencyMs = this.now() - started;
|
|
2816
|
-
const counts = { reply: 0, dismiss: 0, defer: 0 };
|
|
2817
|
-
for (const verdict of decided.verdicts) counts[verdict.decision] += 1;
|
|
2818
|
-
if (decided.outcome === "fail_closed") {
|
|
2819
|
-
this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, "gate failed closed \u2014 nothing recorded, no turn started");
|
|
2820
|
-
return { ...this.result("fail_closed", cards, truncated, started, decided.failure), undecided: cards, latencyMs };
|
|
2821
|
-
}
|
|
2822
|
-
if (decided.outcome === "empty") {
|
|
2823
|
-
this.retryRung = 0;
|
|
2824
|
-
return this.result("empty", cards, truncated, started);
|
|
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;
|
|
2842
|
-
}
|
|
2843
|
-
turnsStarted += 1;
|
|
2844
|
-
this.replyTurnsInFlight.add(entry.conversationId);
|
|
2845
|
-
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)", entry);
|
|
2846
|
-
}
|
|
2847
|
-
const summary = {
|
|
2848
|
-
cards,
|
|
2849
|
-
reply: counts.reply,
|
|
2850
|
-
dismiss: counts.dismiss,
|
|
2851
|
-
defer: counts.defer,
|
|
2852
|
-
undecided: decided.undecided.length,
|
|
2853
|
-
recorded,
|
|
2854
|
-
recordFailures,
|
|
2855
|
-
turnsStarted,
|
|
2856
|
-
turnsRefused,
|
|
2857
|
-
skippedInFlight,
|
|
2858
|
-
latencyMs
|
|
2859
|
-
};
|
|
2860
|
-
if (turnsRefused > 0) {
|
|
2861
|
-
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 some turns were refused; re-waking later");
|
|
2862
|
-
} else if (recordFailures > 0 || decided.undecided.length > 0) {
|
|
2863
|
-
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 cards left on the tray; re-waking later");
|
|
2864
|
-
} else {
|
|
2865
|
-
this.retryRung = 0;
|
|
2866
|
-
this.logger.info(summary, "gate");
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
function singleRunStarter(options, owner, logger, now) {
|
|
3178
|
+
return async (request) => {
|
|
3179
|
+
const hung = options.turns.hungSingleRun();
|
|
3180
|
+
if (hung) {
|
|
3181
|
+
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)");
|
|
3182
|
+
return { status: "not_started", detail: `the gate-off run ${hung.runId} is still going` };
|
|
2867
3183
|
}
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
return {
|
|
2872
|
-
|
|
2873
|
-
cards,
|
|
2874
|
-
reply: 0,
|
|
2875
|
-
dismiss: 0,
|
|
2876
|
-
defer: 0,
|
|
2877
|
-
undecided: 0,
|
|
2878
|
-
recorded: 0,
|
|
2879
|
-
recordFailures: 0,
|
|
2880
|
-
turnsStarted: 0,
|
|
2881
|
-
turnsRefused: 0,
|
|
2882
|
-
skippedInFlight: 0,
|
|
2883
|
-
truncated,
|
|
2884
|
-
latencyMs: this.now() - started,
|
|
2885
|
-
failure
|
|
3184
|
+
const sessionKey = wakeSessionKey(options.agentId, now());
|
|
3185
|
+
logger.info({ sessionKey, cards: request.cards, invites: request.invites }, "gate off \u2014 one run with the served wake instruction");
|
|
3186
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
3187
|
+
if (!admission.ran) return { status: "not_started", detail: admission.error };
|
|
3188
|
+
let letGo = () => {
|
|
2886
3189
|
};
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
3190
|
+
const handedOff = new Promise((resolve) => {
|
|
3191
|
+
letGo = () => resolve("let_go");
|
|
3192
|
+
});
|
|
3193
|
+
const { runId } = admission;
|
|
3194
|
+
options.turns.started({ runId, kind: "run", id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo });
|
|
3195
|
+
const ended = admission.done.then((outcome) => {
|
|
3196
|
+
if (outcome.status !== "gone") void options.turns.ended(runId);
|
|
3197
|
+
logger[outcome.status === "ok" ? "info" : "warn"]({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, "gate off \u2014 run ended");
|
|
3198
|
+
return outcome;
|
|
3199
|
+
});
|
|
3200
|
+
const first = await Promise.race([ended, handedOff]);
|
|
3201
|
+
if (first === "let_go") {
|
|
3202
|
+
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`)");
|
|
3203
|
+
return { status: "failed", detail: "the run was handed off while still going" };
|
|
2895
3204
|
}
|
|
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);
|
|
3205
|
+
return first.status === "ok" && !first.error ? { status: "completed" } : { status: "failed", detail: first.error ?? `run ended: ${first.status ?? "unknown"}` };
|
|
3206
|
+
};
|
|
3207
|
+
}
|
|
3208
|
+
function logEvent(event, logger, metrics) {
|
|
3209
|
+
switch (event.type) {
|
|
3210
|
+
case "wake":
|
|
3211
|
+
if (event.source === "message") metrics.incWake({ source: "message" });
|
|
3212
|
+
else if (event.source === "invite") metrics.incWake({ source: "invite" });
|
|
3213
|
+
logger.debug({ source: event.source, ...event.conversationId ? { conversationId: event.conversationId } : {} }, "wake");
|
|
3214
|
+
return;
|
|
3215
|
+
case "echo":
|
|
3216
|
+
logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
|
|
3217
|
+
return;
|
|
3218
|
+
case "cycle": {
|
|
3219
|
+
const s = event.summary;
|
|
3220
|
+
const fields = {
|
|
3221
|
+
outcome: s.outcome,
|
|
3222
|
+
cards: s.cards,
|
|
3223
|
+
invites: s.invites,
|
|
3224
|
+
reply: s.reply,
|
|
3225
|
+
dismiss: s.dismiss,
|
|
3226
|
+
defer: s.defer,
|
|
3227
|
+
undecided: s.undecided,
|
|
3228
|
+
recordFailures: s.recordFailures,
|
|
3229
|
+
turnsStarted: s.turnsStarted,
|
|
3230
|
+
turnsRefused: s.turnsRefused,
|
|
3231
|
+
heldByTurns: s.heldByTurns,
|
|
3232
|
+
...s.truncated ? { truncated: true } : {},
|
|
3233
|
+
...s.failure ? { failure: s.failure } : {}
|
|
3234
|
+
};
|
|
3235
|
+
switch (s.outcome) {
|
|
3236
|
+
case "empty":
|
|
3237
|
+
logger.info({}, "tray empty \u2014 nothing to decide");
|
|
3238
|
+
return;
|
|
3239
|
+
case "nothing_owed":
|
|
3240
|
+
logger.info(fields, "nothing new to decide (muted cards, or cards a running turn holds)");
|
|
3241
|
+
return;
|
|
3242
|
+
case "fail_closed":
|
|
3243
|
+
logger.warn(fields, "gate failed closed \u2014 nothing recorded, no turn started; the server re-wakes");
|
|
3244
|
+
return;
|
|
3245
|
+
case "tray_failed":
|
|
3246
|
+
logger.warn(fields, "tray read failed \u2014 the cards stay on the tray; the server re-wakes");
|
|
3247
|
+
return;
|
|
3248
|
+
case "texts_missing":
|
|
3249
|
+
logger.warn(fields, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
3250
|
+
return;
|
|
3251
|
+
case "tools_unavailable":
|
|
3252
|
+
logger.debug(fields, "not gating \u2014 no turn can start now");
|
|
3253
|
+
return;
|
|
3254
|
+
case "abandoned":
|
|
3255
|
+
logger.warn(fields, "cycle abandoned \u2014 it ran past its deadline; nothing more is done for it, the next wake starts a new one");
|
|
3256
|
+
return;
|
|
3257
|
+
default: {
|
|
3258
|
+
const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0;
|
|
3259
|
+
logger[incomplete ? "warn" : "info"](fields, incomplete ? "gate \u2014 some cards were left on the tray; the server re-wakes" : "gate");
|
|
3260
|
+
return;
|
|
2953
3261
|
}
|
|
2954
3262
|
}
|
|
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
3263
|
}
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
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
|
-
}
|
|
2984
|
-
const card = agentchatme.gate.cardsOf(tray).find((c) => c.conversation_id === reply.conversationId);
|
|
2985
|
-
if (!card) return tray.truncated !== true;
|
|
2986
|
-
return lastDecisionAt(card) !== lastDecisionAt(reply.card);
|
|
2987
|
-
}
|
|
2988
|
-
/** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
|
|
2989
|
-
async recordReply(sessionKey, reply) {
|
|
2990
|
-
try {
|
|
2991
|
-
await reply.record();
|
|
2992
|
-
this.logger.info({ sessionKey, conversationId: reply.conversationId }, "reply verdict recorded \u2014 turn completed");
|
|
2993
|
-
} catch (err) {
|
|
2994
|
-
this.logger.warn(
|
|
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"
|
|
3264
|
+
case "turn_started":
|
|
3265
|
+
return;
|
|
3266
|
+
// the turn starter logs it with the OpenClaw session and run
|
|
3267
|
+
case "turn_refused":
|
|
3268
|
+
logger.warn({ kind: event.kind, id: event.id, error: event.error }, "turn not started \u2014 nothing recorded; the card stays on the tray");
|
|
3269
|
+
return;
|
|
3270
|
+
case "turn_outcome": {
|
|
3271
|
+
const o = event.outcome;
|
|
3272
|
+
logger.info(
|
|
3273
|
+
{ conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...o.action !== "none" ? { through: o.throughMessageId } : {} },
|
|
3274
|
+
event.recorded ? `${o.action === "record_reply" ? "reply" : "dismiss"} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`
|
|
2997
3275
|
);
|
|
3276
|
+
return;
|
|
2998
3277
|
}
|
|
3278
|
+
case "invite_outcome":
|
|
3279
|
+
logger.info(
|
|
3280
|
+
{ inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },
|
|
3281
|
+
event.recorded ? "invite dismissed after a second silent turn (left pending)" : `nothing recorded for the invite (${event.outcome.reason})`
|
|
3282
|
+
);
|
|
3283
|
+
return;
|
|
3284
|
+
case "run":
|
|
3285
|
+
return;
|
|
3286
|
+
// single-run mode logs the run itself
|
|
3287
|
+
case "error":
|
|
3288
|
+
logger.debug({ err: event.error.message }, "receive loop notice");
|
|
3289
|
+
return;
|
|
2999
3290
|
}
|
|
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
3291
|
}
|
|
3058
|
-
|
|
3059
|
-
|
|
3292
|
+
var TROUBLE_OUTCOMES = /* @__PURE__ */ new Set(["fail_closed", "tools_unavailable", "texts_missing", "abandoned"]);
|
|
3293
|
+
var CYCLE_TROUBLE_RUN = 3;
|
|
3294
|
+
var TROUBLE_MEANING = {
|
|
3295
|
+
fail_closed: "the gate call failed (model unreachable, too slow, or nothing usable)",
|
|
3296
|
+
tools_unavailable: "no turn could have the hosted tools",
|
|
3297
|
+
texts_missing: "the served texts are not available",
|
|
3298
|
+
abandoned: "the cycle ran past its deadline and was abandoned"
|
|
3299
|
+
};
|
|
3300
|
+
function cycleTroubleLine(recentCycles) {
|
|
3301
|
+
let run = 0;
|
|
3302
|
+
for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i].outcome); i -= 1) run += 1;
|
|
3303
|
+
if (run < CYCLE_TROUBLE_RUN) return null;
|
|
3304
|
+
const last = recentCycles[recentCycles.length - 1];
|
|
3305
|
+
const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))];
|
|
3306
|
+
const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join("; ");
|
|
3307
|
+
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
3308
|
}
|
|
3061
3309
|
function adaptLog(log) {
|
|
3062
3310
|
if (!log) return void 0;
|
|
@@ -3089,6 +3337,32 @@ async function waitUntilAbort(signal, onAbort) {
|
|
|
3089
3337
|
}
|
|
3090
3338
|
await onAbort();
|
|
3091
3339
|
}
|
|
3340
|
+
var mcpUpdateWarned = /* @__PURE__ */ new Set();
|
|
3341
|
+
async function updateHostedMcpEntry(ctx, apiBase, apiKey, runtime = getPluginRuntime) {
|
|
3342
|
+
const prefix = `[agentchat:${ctx.accountId}]`;
|
|
3343
|
+
const warnOnce = (line) => {
|
|
3344
|
+
if (mcpUpdateWarned.has(ctx.accountId)) return;
|
|
3345
|
+
mcpUpdateWarned.add(ctx.accountId);
|
|
3346
|
+
ctx.log?.warn?.(`${prefix} ${line}`);
|
|
3347
|
+
};
|
|
3348
|
+
try {
|
|
3349
|
+
const { cfg: liveCfg } = readLiveConfig(ctx.cfg, runtime);
|
|
3350
|
+
const config = runtime()?.config;
|
|
3351
|
+
const result = await refreshHostedMcpEntry({ liveCfg, config, apiBase, apiKey });
|
|
3352
|
+
if (result.outcome === "updated") {
|
|
3353
|
+
mcpUpdateWarned.delete(ctx.accountId);
|
|
3354
|
+
ctx.log?.info?.(`${prefix} mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()}); under the default reload mode OpenClaw applies it without a restart`);
|
|
3355
|
+
} else if (result.outcome === "unsupported") {
|
|
3356
|
+
warnOnce(`mcp.servers.agentchat does not name this client (${clientIdentityText()}) and this OpenClaw cannot update its config from a plugin \u2014 run \`openclaw doctor --fix\``);
|
|
3357
|
+
} else if (result.outcome === "failed") {
|
|
3358
|
+
warnOnce(
|
|
3359
|
+
result.code === NIX_MODE_ERROR_CODE ? `mcp.servers.agentchat does not name this client and OpenClaw's config is read-only here (Nix mode) \u2014 add ${clientIdentityText()} to its headers in the Nix-managed config` : `mcp.servers.agentchat could not be updated to name this client (${result.error ?? "unknown error"}) \u2014 run \`openclaw doctor --fix\``
|
|
3360
|
+
);
|
|
3361
|
+
}
|
|
3362
|
+
} catch (err) {
|
|
3363
|
+
warnOnce(`mcp.servers.agentchat check failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3092
3366
|
var agentchatGatewayAdapter = {
|
|
3093
3367
|
async startAccount(ctx) {
|
|
3094
3368
|
const account = ctx.account;
|
|
@@ -3103,6 +3377,7 @@ var agentchatGatewayAdapter = {
|
|
|
3103
3377
|
const config = account.config;
|
|
3104
3378
|
const logger = adaptLog(ctx.log) ?? createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys });
|
|
3105
3379
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, "starting"));
|
|
3380
|
+
void updateHostedMcpEntry(ctx, config.apiBase, config.apiKey);
|
|
3106
3381
|
const wakeMode = readEnv_js.readWakeModeFromEnv();
|
|
3107
3382
|
if (wakeMode.mode === "off") {
|
|
3108
3383
|
ctx.log?.info?.(
|
|
@@ -3114,7 +3389,7 @@ var agentchatGatewayAdapter = {
|
|
|
3114
3389
|
}
|
|
3115
3390
|
if (readEnv_js.readLegacyReplyGateFailOpenFromEnv()) {
|
|
3116
3391
|
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)
|
|
3392
|
+
`[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
3393
|
);
|
|
3119
3394
|
}
|
|
3120
3395
|
const refusal = multiAccountRefusal(ctx.cfg);
|
|
@@ -3136,20 +3411,57 @@ var agentchatGatewayAdapter = {
|
|
|
3136
3411
|
}
|
|
3137
3412
|
const client = getClient({ accountId: ctx.accountId, config });
|
|
3138
3413
|
const gateTimeoutMs = readEnv_js.readReplyGateTimeoutMsFromEnv();
|
|
3139
|
-
const
|
|
3414
|
+
const overdueWarned = /* @__PURE__ */ new Map();
|
|
3415
|
+
const turns = accountTurns(ctx.accountId);
|
|
3416
|
+
const reportOverdue = (runId, kind, id, elapsedMs, handed) => {
|
|
3417
|
+
const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS);
|
|
3418
|
+
if (!handed && overdueWarned.get(runId) === mark) return;
|
|
3419
|
+
overdueWarned.set(runId, mark);
|
|
3420
|
+
ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`);
|
|
3421
|
+
};
|
|
3422
|
+
const onStillRunning = ({ runId, sessionKey, elapsedMs }) => {
|
|
3423
|
+
const run = turns.run(runId);
|
|
3424
|
+
if (turns.stateOf(runId) === "released") {
|
|
3425
|
+
logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4) }, "released turn still running in OpenClaw \u2014 it holds nothing");
|
|
3426
|
+
return;
|
|
3427
|
+
}
|
|
3428
|
+
logger.info(
|
|
3429
|
+
{ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4), ...run ? { [run.kind === "reply" ? "conversationId" : run.kind === "invite" ? "inviteId" : "run"]: run.id } : {} },
|
|
3430
|
+
"turn still running \u2014 its conversation stays in flight until OpenClaw reports the run ended"
|
|
3431
|
+
);
|
|
3432
|
+
if (!run || !isOverdue(elapsedMs)) return;
|
|
3433
|
+
const handed = turns.handOff(runId) !== null;
|
|
3434
|
+
reportOverdue(runId, run.kind, run.id, elapsedMs, handed);
|
|
3435
|
+
};
|
|
3436
|
+
const watchRun = createRunWatcher({ onStillRunning });
|
|
3437
|
+
turns.configure({
|
|
3438
|
+
recorder: createAfterTurnRecorder({ client, logger }),
|
|
3439
|
+
store: new TurnStore(ctx.accountId),
|
|
3440
|
+
watch: async (record) => {
|
|
3441
|
+
const outcome = await watchRun(record);
|
|
3442
|
+
return outcome ? turnEndOf(outcome) : null;
|
|
3443
|
+
},
|
|
3444
|
+
readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),
|
|
3445
|
+
logger
|
|
3446
|
+
});
|
|
3447
|
+
turns.adopt();
|
|
3448
|
+
for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`);
|
|
3449
|
+
for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, "removed a file an earlier release kept (no longer used)");
|
|
3450
|
+
const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger });
|
|
3451
|
+
const texts = new OpenClawTexts(textsCache);
|
|
3452
|
+
const first = await textsCache.start();
|
|
3453
|
+
if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, "served texts in hand");
|
|
3454
|
+
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
3455
|
const handle = config.agentHandle;
|
|
3141
3456
|
if (handle) {
|
|
3142
|
-
|
|
3143
|
-
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
|
|
3457
|
+
const refresh = (copy) => {
|
|
3458
|
+
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(copy).identity_line);
|
|
3144
3459
|
if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
|
|
3145
3460
|
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
|
-
}
|
|
3461
|
+
};
|
|
3462
|
+
if (first) refresh(first);
|
|
3463
|
+
textsCache.onChange((copy) => refresh(copy));
|
|
3147
3464
|
}
|
|
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
3465
|
const metrics = createInMemoryMetrics();
|
|
3154
3466
|
await registerIntegration({
|
|
3155
3467
|
accountId: ctx.accountId,
|
|
@@ -3157,33 +3469,44 @@ var agentchatGatewayAdapter = {
|
|
|
3157
3469
|
logger,
|
|
3158
3470
|
socketOptions: { client, metrics },
|
|
3159
3471
|
build: (socket) => {
|
|
3160
|
-
const
|
|
3472
|
+
const loop = createIntegrationLoop({
|
|
3161
3473
|
accountId: ctx.accountId,
|
|
3162
3474
|
agentId,
|
|
3163
3475
|
client,
|
|
3476
|
+
texts,
|
|
3477
|
+
socket: socket.realtime,
|
|
3478
|
+
handle: config.agentHandle,
|
|
3164
3479
|
callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
|
|
3165
|
-
|
|
3480
|
+
// A turn holds its conversation until OpenClaw confirms its run
|
|
3481
|
+
// ended; a wait that elapses is asked again (`integration/run.ts`).
|
|
3482
|
+
startRun: createRuntimeTurnStarter({
|
|
3483
|
+
onStillRunning,
|
|
3484
|
+
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")
|
|
3485
|
+
}),
|
|
3166
3486
|
// Gating waits until a turn can have the hosted tools (the MCP
|
|
3167
3487
|
// entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
|
|
3168
3488
|
// its key in this process): a connect wake on a cold gateway
|
|
3169
3489
|
// otherwise spends a gate call and runs a turn that cannot look.
|
|
3170
3490
|
readiness: () => {
|
|
3171
3491
|
const live = readLiveConfig(ctx.cfg);
|
|
3492
|
+
const hung = hungTurnsReason(turns, live.cfg);
|
|
3493
|
+
if (hung) return { ready: false, reason: hung };
|
|
3172
3494
|
return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
|
|
3173
3495
|
},
|
|
3174
|
-
|
|
3175
|
-
|
|
3496
|
+
// The account's runs outlive this loop: a config change restarts
|
|
3497
|
+
// the account while its runs go on in OpenClaw, so every loop for
|
|
3498
|
+
// the account shares the same turns (and the kit tracker in them).
|
|
3499
|
+
turns,
|
|
3176
3500
|
logger,
|
|
3177
3501
|
metrics,
|
|
3178
3502
|
gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
|
|
3179
3503
|
});
|
|
3180
3504
|
let blocked = false;
|
|
3181
3505
|
return {
|
|
3182
|
-
|
|
3506
|
+
loop,
|
|
3183
3507
|
texts,
|
|
3508
|
+
textsCache,
|
|
3184
3509
|
handlers: {
|
|
3185
|
-
onWake: (source) => invoker.wake(source),
|
|
3186
|
-
onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
|
|
3187
3510
|
onConnected: (at) => {
|
|
3188
3511
|
if (blocked) {
|
|
3189
3512
|
blocked = false;
|
|
@@ -3191,7 +3514,6 @@ var agentchatGatewayAdapter = {
|
|
|
3191
3514
|
}
|
|
3192
3515
|
ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
|
|
3193
3516
|
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
3517
|
},
|
|
3196
3518
|
onBlocked: (info) => {
|
|
3197
3519
|
const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
|
|
@@ -3247,23 +3569,6 @@ var agentchatGatewayAdapter = {
|
|
|
3247
3569
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
|
|
3248
3570
|
}
|
|
3249
3571
|
};
|
|
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
3572
|
var PROBE_MIN_MS = 1e3;
|
|
3268
3573
|
var PROBE_MAX_MS = 1e4;
|
|
3269
3574
|
function formatCounts(counts) {
|
|
@@ -3305,15 +3610,27 @@ var agentchatStatusAdapter = {
|
|
|
3305
3610
|
const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
|
|
3306
3611
|
const live = getIntegration(account.accountId);
|
|
3307
3612
|
const health = live?.socket.getHealth();
|
|
3308
|
-
const
|
|
3309
|
-
const
|
|
3613
|
+
const loopStatus = live?.loop?.loop.status();
|
|
3614
|
+
const counters = loopStatus ? {
|
|
3615
|
+
wakes: loopStatus.coalescer.wakes,
|
|
3616
|
+
cycles: loopStatus.coalescer.cycles,
|
|
3617
|
+
turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted
|
|
3618
|
+
} : void 0;
|
|
3619
|
+
const turnsHere = live ? findAccountTurns(account.accountId) ?? null : null;
|
|
3620
|
+
const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null;
|
|
3621
|
+
const overdue = turnsHere ? [...hungReason ? [hungReason] : [], ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : [];
|
|
3622
|
+
const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null;
|
|
3623
|
+
const servedFrom = live?.texts?.source;
|
|
3624
|
+
const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
|
|
3310
3625
|
const socketCounters = live?.metrics?.snapshot?.();
|
|
3311
|
-
const
|
|
3626
|
+
const integration6 = {
|
|
3312
3627
|
mode: readEnv_js.readWakeModeFromEnv().mode,
|
|
3313
3628
|
...health ? { state: health.state } : {},
|
|
3314
3629
|
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
3315
3630
|
...textsSource ? { texts: textsSource } : {},
|
|
3316
|
-
...socketCounters ? { socket: socketCounters } : {}
|
|
3631
|
+
...socketCounters ? { socket: socketCounters } : {},
|
|
3632
|
+
...overdue.length > 0 ? { overdue } : {},
|
|
3633
|
+
...trouble ? { trouble } : {}
|
|
3317
3634
|
};
|
|
3318
3635
|
const refusal = multiAccountRefusal(cfg);
|
|
3319
3636
|
return {
|
|
@@ -3323,7 +3640,7 @@ var agentchatStatusAdapter = {
|
|
|
3323
3640
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3324
3641
|
mcp,
|
|
3325
3642
|
placement,
|
|
3326
|
-
integration,
|
|
3643
|
+
integration: integration6,
|
|
3327
3644
|
...refusal ? { refusal } : {},
|
|
3328
3645
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3329
3646
|
};
|
|
@@ -3344,7 +3661,7 @@ var agentchatStatusAdapter = {
|
|
|
3344
3661
|
}
|
|
3345
3662
|
if (probe.mcp) lines.push({ text: probe.mcp.detail, tone: probe.mcp.ok ? "success" : "error" });
|
|
3346
3663
|
for (const check of probe.placement ?? []) {
|
|
3347
|
-
lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? "muted" : "warn" });
|
|
3664
|
+
lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok && !check.notice ? "muted" : "warn" });
|
|
3348
3665
|
}
|
|
3349
3666
|
if (probe.refusal) lines.push({ text: `integration not started \u2014 ${probe.refusal}`, tone: "error" });
|
|
3350
3667
|
if (probe.integration) {
|
|
@@ -3361,6 +3678,8 @@ var agentchatStatusAdapter = {
|
|
|
3361
3678
|
tone: "muted"
|
|
3362
3679
|
});
|
|
3363
3680
|
}
|
|
3681
|
+
if (d.trouble) lines.push({ text: d.trouble, tone: "warn" });
|
|
3682
|
+
for (const line of d.overdue ?? []) lines.push({ text: line, tone: "warn" });
|
|
3364
3683
|
if (d.texts === "missing") {
|
|
3365
3684
|
lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
|
|
3366
3685
|
} else if (d.texts === "cache") {
|
|
@@ -3392,8 +3711,8 @@ var agentchatDoctorAdapter = {
|
|
|
3392
3711
|
const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
|
|
3393
3712
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
3394
3713
|
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
|
|
3395
|
-
if (check.ok) continue;
|
|
3396
|
-
const fix = check.name === "mcp" ? ` (${doctorFixCommand} adds it)` : "";
|
|
3714
|
+
if (check.ok && !check.notice) continue;
|
|
3715
|
+
const fix = check.name === "mcp" && check.repair && !check.ok ? ` (${doctorFixCommand} adds it)` : "";
|
|
3397
3716
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`);
|
|
3398
3717
|
}
|
|
3399
3718
|
const bound = openclawLayout_js.resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId);
|
|
@@ -3404,6 +3723,18 @@ var agentchatDoctorAdapter = {
|
|
|
3404
3723
|
);
|
|
3405
3724
|
}
|
|
3406
3725
|
}
|
|
3726
|
+
for (const accountId of listActiveAccounts()) {
|
|
3727
|
+
const status = getIntegration(accountId)?.loop?.loop.status();
|
|
3728
|
+
if (!status) continue;
|
|
3729
|
+
const turns = findAccountTurns(accountId);
|
|
3730
|
+
if (turns) {
|
|
3731
|
+
const hung = hungTurnsReason(turns, cfg);
|
|
3732
|
+
if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`);
|
|
3733
|
+
for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`);
|
|
3734
|
+
}
|
|
3735
|
+
const trouble = cycleTroubleLine(status.recentCycles ?? []);
|
|
3736
|
+
if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`);
|
|
3737
|
+
}
|
|
3407
3738
|
return warnings;
|
|
3408
3739
|
},
|
|
3409
3740
|
async repairConfig({ cfg }) {
|
|
@@ -3450,6 +3781,7 @@ var agentchatDoctorAdapter = {
|
|
|
3450
3781
|
const result = withHostedMcpEntry(next, apiBase, apiKey);
|
|
3451
3782
|
next = result.cfg;
|
|
3452
3783
|
if (result.outcome === "added") changes.push(`added mcp.servers.agentchat \u2192 ${apiBase}/mcp (bearer template on AGENTCHAT_API_KEY)`);
|
|
3784
|
+
if (result.outcome === "updated") changes.push(`updated mcp.servers.agentchat to name this client (${clientIdentityText()})`);
|
|
3453
3785
|
}
|
|
3454
3786
|
return { config: next, changes, ...warnings.length > 0 ? { warnings } : {} };
|
|
3455
3787
|
}
|
|
@@ -3476,9 +3808,9 @@ function resolveAgentchatAccount(cfg, accountId) {
|
|
|
3476
3808
|
var uiHints = {
|
|
3477
3809
|
apiKey: {
|
|
3478
3810
|
label: "AgentChat API key",
|
|
3479
|
-
placeholder: "
|
|
3811
|
+
placeholder: "ac_\u2026",
|
|
3480
3812
|
sensitive: true,
|
|
3481
|
-
help: "The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing
|
|
3813
|
+
help: "The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing ac_\u2026 key."
|
|
3482
3814
|
},
|
|
3483
3815
|
apiBase: {
|
|
3484
3816
|
label: "API base URL",
|
|
@@ -3689,8 +4021,14 @@ var agentchatPlugin = {
|
|
|
3689
4021
|
threads: false,
|
|
3690
4022
|
nativeCommands: false
|
|
3691
4023
|
},
|
|
4024
|
+
// OpenClaw matches a reload prefix as `path === prefix` or `path` starting
|
|
4025
|
+
// with `prefix.` (src/gateway/config-reload-plan.ts), so the prefix carries
|
|
4026
|
+
// no trailing dot: `channels.agentchat.` matched nothing, and every
|
|
4027
|
+
// channels.agentchat change restarted the gateway (2026.6.x–2026.8.x) or
|
|
4028
|
+
// reloaded the plugin (2026.11.x). With this one OpenClaw restarts just the
|
|
4029
|
+
// channel, after a running turn has ended.
|
|
3692
4030
|
reload: {
|
|
3693
|
-
configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}
|
|
4031
|
+
configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}`]
|
|
3694
4032
|
},
|
|
3695
4033
|
configSchema: channelCore.buildChannelConfigSchema(agentchatChannelConfigSchema, { uiHints }),
|
|
3696
4034
|
setupWizard: agentchatSetupWizard,
|
|
@@ -3698,9 +4036,9 @@ var agentchatPlugin = {
|
|
|
3698
4036
|
listAccountIds(cfg) {
|
|
3699
4037
|
const section = readChannelSection(cfg);
|
|
3700
4038
|
if (!section) return [];
|
|
3701
|
-
const { accounts } = section;
|
|
3702
|
-
if (
|
|
3703
|
-
const ids = Object.keys(
|
|
4039
|
+
const { accounts: accounts2 } = section;
|
|
4040
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
4041
|
+
const ids = Object.keys(accounts2);
|
|
3704
4042
|
if (ids.length > 0) return ids;
|
|
3705
4043
|
}
|
|
3706
4044
|
const hasFlatFields = typeof section.apiKey === "string" || typeof section.apiBase === "string" || typeof section.agentHandle === "string";
|
|
@@ -3740,9 +4078,9 @@ var agentchatPlugin = {
|
|
|
3740
4078
|
hasConfiguredState({ cfg }) {
|
|
3741
4079
|
const section = readChannelSection(cfg);
|
|
3742
4080
|
if (!section) return false;
|
|
3743
|
-
const { accounts } = section;
|
|
3744
|
-
if (
|
|
3745
|
-
for (const entry of Object.values(
|
|
4081
|
+
const { accounts: accounts2 } = section;
|
|
4082
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
4083
|
+
for (const entry of Object.values(accounts2)) {
|
|
3746
4084
|
if (entry && typeof entry === "object") {
|
|
3747
4085
|
const candidate = entry.apiKey;
|
|
3748
4086
|
if (isApiKeyPresent(candidate)) return true;
|
|
@@ -3786,7 +4124,15 @@ var agentchatChannelEntry = channelCore.defineChannelPluginEntry({
|
|
|
3786
4124
|
// (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
|
|
3787
4125
|
// The integration reads `runtime.llm.complete` (the gate on the agent's own
|
|
3788
4126
|
// model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
|
|
3789
|
-
setRuntime: (runtime) => setPluginRuntime(runtime)
|
|
4127
|
+
setRuntime: (runtime) => setPluginRuntime(runtime),
|
|
4128
|
+
// `openclaw agentchat release <conversation_id>`: the CLI half is
|
|
4129
|
+
// registered for every CLI (parse-time metadata), the gateway half only
|
|
4130
|
+
// where the integration runs.
|
|
4131
|
+
registerCliMetadata: (api) => registerReleaseCli(api),
|
|
4132
|
+
registerFull: (api) => {
|
|
4133
|
+
registerReleaseGatewayMethod(api);
|
|
4134
|
+
registerRunObserver(api);
|
|
4135
|
+
}
|
|
3790
4136
|
});
|
|
3791
4137
|
var agentchatSetupEntry = channelCore.defineSetupPluginEntry(agentchatPlugin);
|
|
3792
4138
|
|
|
@@ -3803,30 +4149,29 @@ function hasAgentChatConfiguredState(config) {
|
|
|
3803
4149
|
exports.AGENTCHAT_CHANNEL_ID = AGENTCHAT_CHANNEL_ID;
|
|
3804
4150
|
exports.AGENTCHAT_DEFAULT_ACCOUNT_ID = AGENTCHAT_DEFAULT_ACCOUNT_ID;
|
|
3805
4151
|
exports.AgentChatChannelError = AgentChatChannelError;
|
|
3806
|
-
exports.AgentInvoker = AgentInvoker;
|
|
3807
4152
|
exports.IntegrationSocket = IntegrationSocket;
|
|
3808
|
-
exports.
|
|
4153
|
+
exports.MAX_HUNG_TURNS = MAX_HUNG_TURNS;
|
|
3809
4154
|
exports.MCP_SERVER_NAME = MCP_SERVER_NAME;
|
|
3810
4155
|
exports.OPENCLAW_TOOL_NAMER = OPENCLAW_TOOL_NAMER;
|
|
3811
|
-
exports.
|
|
3812
|
-
exports.
|
|
4156
|
+
exports.OpenClawTexts = OpenClawTexts;
|
|
4157
|
+
exports.accountTurns = accountTurns;
|
|
3813
4158
|
exports.agentchatChannelEntry = agentchatChannelEntry;
|
|
3814
4159
|
exports.agentchatPlugin = agentchatPlugin;
|
|
3815
4160
|
exports.agentchatSetupEntry = agentchatSetupEntry;
|
|
3816
4161
|
exports.agentchatSetupPlugin = agentchatPlugin;
|
|
3817
4162
|
exports.assertApiKeyValid = assertApiKeyValid;
|
|
3818
4163
|
exports.createInMemoryMetrics = createInMemoryMetrics;
|
|
4164
|
+
exports.createIntegrationLoop = createIntegrationLoop;
|
|
4165
|
+
exports.createLoopTurnStarter = createLoopTurnStarter;
|
|
3819
4166
|
exports.createMetrics = createMetrics;
|
|
3820
4167
|
exports.createNoopMetrics = createNoopMetrics;
|
|
4168
|
+
exports.createTextsCache = createTextsCache;
|
|
3821
4169
|
exports.default = agentchatChannelEntry;
|
|
3822
|
-
exports.groupInviteFromRecord = groupInviteFromRecord;
|
|
3823
4170
|
exports.hasAgentChatConfiguredState = hasAgentChatConfiguredState;
|
|
3824
4171
|
exports.hostedMcpServerEntry = hostedMcpServerEntry;
|
|
3825
4172
|
exports.hostedMcpSnippet = hostedMcpSnippet;
|
|
3826
4173
|
exports.hostedMcpUrl = hostedMcpUrl;
|
|
3827
|
-
exports.inviteTurnPrompt = inviteTurnPrompt;
|
|
3828
4174
|
exports.loadIdentityLine = loadIdentityLine;
|
|
3829
|
-
exports.loadTexts = loadTexts;
|
|
3830
4175
|
exports.mcpToolName = mcpToolName;
|
|
3831
4176
|
exports.parseChannelConfig = parseChannelConfig;
|
|
3832
4177
|
exports.probeHostedMcp = probeHostedMcp;
|
|
@@ -3835,8 +4180,10 @@ exports.recoverAgentStart = recoverAgentStart;
|
|
|
3835
4180
|
exports.recoverAgentVerify = recoverAgentVerify;
|
|
3836
4181
|
exports.registerAgentStart = registerAgentStart;
|
|
3837
4182
|
exports.registerAgentVerify = registerAgentVerify;
|
|
4183
|
+
exports.spellTextsForOpenClaw = spellTextsForOpenClaw;
|
|
3838
4184
|
exports.spellToolsForOpenClaw = spellToolsForOpenClaw;
|
|
4185
|
+
exports.trackerFor = trackerFor;
|
|
4186
|
+
exports.turnEndOf = turnEndOf;
|
|
3839
4187
|
exports.validateApiKey = validateApiKey;
|
|
3840
|
-
exports.wakeTurnPrompt = wakeTurnPrompt;
|
|
3841
4188
|
//# sourceMappingURL=index.cjs.map
|
|
3842
4189
|
//# sourceMappingURL=index.cjs.map
|