@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.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { buildChannelConfigSchema, defineChannelPluginEntry, defineSetupPluginEntry } from 'openclaw/plugin-sdk/channel-core';
|
|
2
2
|
import { setAccountEnabledInConfigSection, deleteAccountFromConfigSection } from 'openclaw/plugin-sdk/channel-plugin-common';
|
|
3
3
|
import { setSetupChannelEnabled, WizardCancelledError } from 'openclaw/plugin-sdk/setup';
|
|
4
|
+
import { integration, AgentChatClient, AgentChatError, RateLimitedError, RealtimeClient } from 'agentchatme';
|
|
4
5
|
import { readApiKeyFromEnv } from './credentials/read-env.js';
|
|
5
6
|
import * as fs from 'fs';
|
|
6
7
|
import * as path2 from 'path';
|
|
7
8
|
import { WAKE_MODE_ENV, LEGACY_WAKE_MODE_ENV, readWakeModeFromEnv, readLegacyReplyGateFailOpenFromEnv, LEGACY_REPLY_GATE_FAIL_OPEN_ENV, readReplyGateTimeoutMsFromEnv, API_KEY_ENV, readReplyGateEnabledFromEnv } from './credentials/read-env.js';
|
|
8
9
|
import { resolveBoundAgentId, resolveOpenClawDefaultAgentId, resolveOpenClawStateDir } from './openclaw-layout.js';
|
|
9
10
|
import { removeAgentsAnchor, agentsAnchorPath, hasAgentsAnchorFor, writeAgentsAnchor, readAgentsAnchor } from './binding/agents-anchor.js';
|
|
10
|
-
import { AgentChatClient, RealtimeClient, gate } from 'agentchatme';
|
|
11
11
|
import { z } from 'zod';
|
|
12
12
|
import pino from 'pino';
|
|
13
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
13
14
|
|
|
14
15
|
// src/channel.ts
|
|
15
16
|
|
|
@@ -24,9 +25,9 @@ function readChannelSection(cfg) {
|
|
|
24
25
|
}
|
|
25
26
|
function readAccountRaw(section, accountId) {
|
|
26
27
|
if (!section) return void 0;
|
|
27
|
-
const { accounts } = section;
|
|
28
|
-
if (
|
|
29
|
-
const entry =
|
|
28
|
+
const { accounts: accounts2 } = section;
|
|
29
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
30
|
+
const entry = accounts2[accountId];
|
|
30
31
|
if (entry && typeof entry === "object") return entry;
|
|
31
32
|
}
|
|
32
33
|
if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID) {
|
|
@@ -51,8 +52,8 @@ function agentchatEnabledConfigPath(cfg, accountId) {
|
|
|
51
52
|
const section = readChannelSection(cfg);
|
|
52
53
|
const sectionPath = `channels.${AGENTCHAT_CHANNEL_ID}.enabled`;
|
|
53
54
|
if (!section || section.enabled === false) return sectionPath;
|
|
54
|
-
const { accounts } = section;
|
|
55
|
-
const entry =
|
|
55
|
+
const { accounts: accounts2 } = section;
|
|
56
|
+
const entry = accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2) ? accounts2[accountId] : void 0;
|
|
56
57
|
if (entry && typeof entry === "object") return `channels.${AGENTCHAT_CHANNEL_ID}.accounts.${accountId}.enabled`;
|
|
57
58
|
return sectionPath;
|
|
58
59
|
}
|
|
@@ -62,9 +63,9 @@ function agentchatReenableHint(cfg, accountId) {
|
|
|
62
63
|
function listConfiguredAccountIds(cfg) {
|
|
63
64
|
const section = readChannelSection(cfg);
|
|
64
65
|
if (!section) return [];
|
|
65
|
-
const { accounts } = section;
|
|
66
|
-
if (
|
|
67
|
-
const ids = Object.keys(
|
|
66
|
+
const { accounts: accounts2 } = section;
|
|
67
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
68
|
+
const ids = Object.keys(accounts2);
|
|
68
69
|
if (ids.length > 0) return ids;
|
|
69
70
|
}
|
|
70
71
|
return typeof section.apiKey === "string" ? [AGENTCHAT_DEFAULT_ACCOUNT_ID] : [];
|
|
@@ -93,12 +94,12 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
|
|
|
93
94
|
if (accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID && !section.accounts) {
|
|
94
95
|
Object.assign(section, patch);
|
|
95
96
|
} else {
|
|
96
|
-
const
|
|
97
|
+
const accounts2 = {
|
|
97
98
|
...section.accounts ?? {}
|
|
98
99
|
};
|
|
99
|
-
const prevAccount = typeof
|
|
100
|
-
|
|
101
|
-
section.accounts =
|
|
100
|
+
const prevAccount = typeof accounts2[accountId] === "object" && accounts2[accountId] !== null ? accounts2[accountId] : {};
|
|
101
|
+
accounts2[accountId] = { ...prevAccount, ...patch };
|
|
102
|
+
section.accounts = accounts2;
|
|
102
103
|
}
|
|
103
104
|
channels[AGENTCHAT_CHANNEL_ID] = section;
|
|
104
105
|
return { ...cfg ?? {}, channels };
|
|
@@ -119,7 +120,7 @@ var AgentChatChannelError = class extends Error {
|
|
|
119
120
|
};
|
|
120
121
|
|
|
121
122
|
// src/version.ts
|
|
122
|
-
var PACKAGE_VERSION = "0.
|
|
123
|
+
var PACKAGE_VERSION = "0.10.1";
|
|
123
124
|
|
|
124
125
|
// src/client-identity.ts
|
|
125
126
|
var AGENTCHAT_CLIENT_NAME = "openclaw";
|
|
@@ -127,10 +128,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
|
|
|
127
128
|
name: AGENTCHAT_CLIENT_NAME,
|
|
128
129
|
version: PACKAGE_VERSION
|
|
129
130
|
};
|
|
130
|
-
var AGENTCHAT_CLIENT_HEADERS = {
|
|
131
|
-
"X-AgentChat-Client": AGENTCHAT_CLIENT_NAME,
|
|
132
|
-
"X-AgentChat-Client-Version": PACKAGE_VERSION
|
|
133
|
-
};
|
|
134
131
|
|
|
135
132
|
// src/setup-client.ts
|
|
136
133
|
var DEFAULT_API_BASE = "https://api.agentchat.me";
|
|
@@ -139,63 +136,37 @@ async function validateApiKey(apiKey, opts = {}) {
|
|
|
139
136
|
if (!apiKey || typeof apiKey !== "string") {
|
|
140
137
|
return { ok: false, reason: "unauthorized", message: "API key is empty" };
|
|
141
138
|
}
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
139
|
+
const client = new AgentChatClient({
|
|
140
|
+
apiKey,
|
|
141
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
142
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
143
|
+
timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
144
|
+
retry: ONE_ATTEMPT,
|
|
145
|
+
...opts.fetch ? { fetch: opts.fetch } : {}
|
|
146
|
+
});
|
|
147
|
+
let me;
|
|
149
148
|
try {
|
|
150
|
-
|
|
151
|
-
method: "GET",
|
|
152
|
-
headers: {
|
|
153
|
-
Authorization: `Bearer ${apiKey}`,
|
|
154
|
-
Accept: "application/json",
|
|
155
|
-
...AGENTCHAT_CLIENT_HEADERS
|
|
156
|
-
},
|
|
157
|
-
signal: controller.signal
|
|
158
|
-
});
|
|
149
|
+
me = await client.getMe();
|
|
159
150
|
} catch (err) {
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
return { ok: false, reason: "
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
return { ok: false, reason: "forbidden", status: 403, message: "API key lacks permission to read /agents/me" };
|
|
175
|
-
}
|
|
176
|
-
if (res.status === 410) {
|
|
177
|
-
return { ok: false, reason: "deleted", status: 410, message: "Agent account has been deleted" };
|
|
178
|
-
}
|
|
179
|
-
if (res.status >= 500) {
|
|
180
|
-
return { ok: false, reason: "server-error", status: res.status, message: `AgentChat API returned ${res.status}` };
|
|
181
|
-
}
|
|
182
|
-
if (!res.ok) {
|
|
183
|
-
return {
|
|
184
|
-
ok: false,
|
|
185
|
-
reason: "server-error",
|
|
186
|
-
status: res.status,
|
|
187
|
-
message: `AgentChat API returned ${res.status}`
|
|
188
|
-
};
|
|
151
|
+
const failure = describeFailure(err);
|
|
152
|
+
if (failure.kind === "network") {
|
|
153
|
+
const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
|
|
154
|
+
return {
|
|
155
|
+
ok: false,
|
|
156
|
+
reason: unreachable ? "unreachable" : "network-error",
|
|
157
|
+
message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
const status = failure.status;
|
|
161
|
+
if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
|
|
162
|
+
if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
|
|
163
|
+
if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
|
|
164
|
+
return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
|
|
189
165
|
}
|
|
190
|
-
const body =
|
|
166
|
+
const body = asRecord(me);
|
|
191
167
|
const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
|
|
192
168
|
if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
|
|
193
|
-
return {
|
|
194
|
-
ok: false,
|
|
195
|
-
reason: "unexpected-shape",
|
|
196
|
-
status: res.status,
|
|
197
|
-
message: "AgentChat /agents/me returned an unrecognized shape"
|
|
198
|
-
};
|
|
169
|
+
return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
|
|
199
170
|
}
|
|
200
171
|
return {
|
|
201
172
|
ok: true,
|
|
@@ -208,139 +179,122 @@ async function validateApiKey(apiKey, opts = {}) {
|
|
|
208
179
|
};
|
|
209
180
|
}
|
|
210
181
|
async function registerAgentStart(input, opts = {}) {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
239
|
-
if (res.status === 429) {
|
|
240
|
-
return {
|
|
241
|
-
ok: false,
|
|
242
|
-
reason: "rate-limited",
|
|
243
|
-
message,
|
|
244
|
-
status: 429,
|
|
245
|
-
retryAfterSeconds: res.retryAfterSeconds
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
if (res.status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status: res.status };
|
|
249
|
-
return { ok: false, reason: "server-error", status: res.status, message };
|
|
182
|
+
let data;
|
|
183
|
+
try {
|
|
184
|
+
data = await AgentChatClient.register({
|
|
185
|
+
email: input.email,
|
|
186
|
+
handle: input.handle,
|
|
187
|
+
...input.displayName !== void 0 ? { display_name: input.displayName } : {},
|
|
188
|
+
...input.description !== void 0 ? { description: input.description } : {},
|
|
189
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
190
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
191
|
+
});
|
|
192
|
+
} catch (err) {
|
|
193
|
+
const failure = describeFailure(err);
|
|
194
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
195
|
+
const { status, code, message } = failure;
|
|
196
|
+
if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
|
|
197
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
198
|
+
if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
|
|
199
|
+
const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
200
|
+
if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
|
|
201
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
202
|
+
if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
|
|
203
|
+
return { ok: false, reason: "server-error", status, message };
|
|
204
|
+
}
|
|
205
|
+
const pendingId = asRecord(data)?.pending_id;
|
|
206
|
+
if (typeof pendingId !== "string") {
|
|
207
|
+
return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
|
|
208
|
+
}
|
|
209
|
+
return { ok: true, pendingId };
|
|
250
210
|
}
|
|
251
211
|
async function registerAgentVerify(input, opts = {}) {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
}
|
|
277
|
-
const code = typeof body.code === "string" ? body.code : "";
|
|
278
|
-
const message = typeof body.message === "string" ? body.message : `status ${res.status}`;
|
|
279
|
-
if (res.status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status: 400 };
|
|
280
|
-
if (res.status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status: 400 };
|
|
281
|
-
if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
|
|
282
|
-
if (res.status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status: 409 };
|
|
283
|
-
const emailPolicy = res.status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
284
|
-
if (emailPolicy) {
|
|
285
|
-
return { ok: false, reason: emailPolicy, message, status: 409, limit: readPolicyLimit(body.details) };
|
|
286
|
-
}
|
|
287
|
-
if (res.status === 429) {
|
|
288
|
-
return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
|
|
212
|
+
let verified;
|
|
213
|
+
try {
|
|
214
|
+
verified = await AgentChatClient.verify(input.pendingId, input.code, {
|
|
215
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
216
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
217
|
+
});
|
|
218
|
+
} catch (err) {
|
|
219
|
+
const failure = describeFailure(err);
|
|
220
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
221
|
+
const { status, code, message } = failure;
|
|
222
|
+
if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
|
|
223
|
+
if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
|
|
224
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
225
|
+
if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
|
|
226
|
+
const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
227
|
+
if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
|
|
228
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
229
|
+
return { ok: false, reason: "server-error", status, message };
|
|
230
|
+
}
|
|
231
|
+
const agent = asRecord(verified.agent);
|
|
232
|
+
if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
|
|
233
|
+
return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
|
|
289
234
|
}
|
|
290
|
-
return {
|
|
235
|
+
return {
|
|
236
|
+
ok: true,
|
|
237
|
+
apiKey: verified.apiKey,
|
|
238
|
+
agent: {
|
|
239
|
+
handle: agent.handle,
|
|
240
|
+
displayName: typeof agent.display_name === "string" ? agent.display_name : null,
|
|
241
|
+
email: agent.email,
|
|
242
|
+
createdAt: agent.created_at
|
|
243
|
+
}
|
|
244
|
+
};
|
|
291
245
|
}
|
|
292
246
|
async function recoverAgentStart(input, opts = {}) {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const
|
|
310
|
-
if (
|
|
311
|
-
|
|
312
|
-
|
|
247
|
+
let data;
|
|
248
|
+
try {
|
|
249
|
+
data = await AgentChatClient.recover(input.email, {
|
|
250
|
+
handle: input.handle,
|
|
251
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
252
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
253
|
+
});
|
|
254
|
+
} catch (err) {
|
|
255
|
+
const failure = describeFailure(err);
|
|
256
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
257
|
+
const { status, code, message: message2 } = failure;
|
|
258
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
|
|
259
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
260
|
+
return { ok: false, reason: "server-error", status, message: message2 };
|
|
261
|
+
}
|
|
262
|
+
const body = asRecord(data);
|
|
263
|
+
const message = typeof body?.message === "string" ? body.message : "status 200";
|
|
264
|
+
if (typeof body?.pending_id !== "string") {
|
|
265
|
+
return {
|
|
266
|
+
ok: false,
|
|
267
|
+
reason: "unexpected-shape",
|
|
268
|
+
status: 200,
|
|
269
|
+
message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
|
|
270
|
+
};
|
|
313
271
|
}
|
|
314
|
-
return { ok:
|
|
272
|
+
return { ok: true, pendingId: body.pending_id, message };
|
|
315
273
|
}
|
|
316
274
|
async function recoverAgentVerify(input, opts = {}) {
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
275
|
+
let recovered;
|
|
276
|
+
try {
|
|
277
|
+
recovered = await AgentChatClient.recoverVerify(input.pendingId, input.code, {
|
|
278
|
+
baseUrl: apiBaseOf(opts.apiBase),
|
|
279
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
280
|
+
});
|
|
281
|
+
} catch (err) {
|
|
282
|
+
const failure = describeFailure(err);
|
|
283
|
+
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
284
|
+
const { status, code, message } = failure;
|
|
285
|
+
if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
|
|
286
|
+
if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
|
|
287
|
+
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
288
|
+
if (status === 409 && code === "HANDLE_REQUIRED") {
|
|
289
|
+
return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
|
|
329
290
|
}
|
|
330
|
-
return { ok:
|
|
291
|
+
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
292
|
+
return { ok: false, reason: "server-error", status, message };
|
|
331
293
|
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
if (res.status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status: 400 };
|
|
335
|
-
if (res.status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status: 400 };
|
|
336
|
-
if (res.status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status: 400 };
|
|
337
|
-
if (res.status === 409 && code === "HANDLE_REQUIRED") {
|
|
338
|
-
return { ok: false, reason: "handle-required", message, status: 409, handles: readHandleList(body.details) };
|
|
294
|
+
if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
|
|
295
|
+
return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
|
|
339
296
|
}
|
|
340
|
-
|
|
341
|
-
return { ok: false, reason: "rate-limited", message, status: 429, retryAfterSeconds: res.retryAfterSeconds };
|
|
342
|
-
}
|
|
343
|
-
return { ok: false, reason: "server-error", status: res.status, message };
|
|
297
|
+
return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
|
|
344
298
|
}
|
|
345
299
|
function classifyEmailPolicyRejection(code) {
|
|
346
300
|
if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
|
|
@@ -358,39 +312,34 @@ function readHandleList(details) {
|
|
|
358
312
|
if (!Array.isArray(handles)) return [];
|
|
359
313
|
return handles.filter((h) => typeof h === "string" && h.length > 0);
|
|
360
314
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
headers: {
|
|
372
|
-
"content-type": "application/json",
|
|
373
|
-
accept: "application/json",
|
|
374
|
-
...AGENTCHAT_CLIENT_HEADERS
|
|
375
|
-
},
|
|
376
|
-
body: JSON.stringify(body),
|
|
377
|
-
signal: controller.signal
|
|
378
|
-
});
|
|
379
|
-
const parsed = await res.json().catch(() => null);
|
|
380
|
-
const retryAfterHeader = res.headers.get("retry-after");
|
|
381
|
-
const retryAfterSeconds = retryAfterHeader ? Number(retryAfterHeader) : void 0;
|
|
315
|
+
var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
|
|
316
|
+
function apiBaseOf(apiBase) {
|
|
317
|
+
return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
|
|
318
|
+
}
|
|
319
|
+
function describeFailure(err) {
|
|
320
|
+
if (err instanceof AgentChatError) {
|
|
321
|
+
const raw = asRecord(asRecord(err.details)?.body);
|
|
322
|
+
const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
|
|
323
|
+
const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
|
|
324
|
+
const retryAfterMs = err instanceof RateLimitedError ? err.retryAfterMs : null;
|
|
382
325
|
return {
|
|
383
326
|
kind: "http",
|
|
384
|
-
status:
|
|
385
|
-
|
|
386
|
-
|
|
327
|
+
status: err.status,
|
|
328
|
+
code,
|
|
329
|
+
message: message2,
|
|
330
|
+
details: raw ? raw.details : err.details,
|
|
331
|
+
...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
|
|
387
332
|
};
|
|
388
|
-
} catch (err) {
|
|
389
|
-
if (err instanceof Error && err.name === "AbortError") return { kind: "timeout" };
|
|
390
|
-
return { kind: "network", message: err instanceof Error ? err.message : String(err) };
|
|
391
|
-
} finally {
|
|
392
|
-
clearTimeout(timer);
|
|
393
333
|
}
|
|
334
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
335
|
+
const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
|
|
336
|
+
return { kind: "network", message, timedOut };
|
|
337
|
+
}
|
|
338
|
+
function networkMessage(failure) {
|
|
339
|
+
return failure.timedOut ? "request timed out" : failure.message;
|
|
340
|
+
}
|
|
341
|
+
function asRecord(value) {
|
|
342
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
394
343
|
}
|
|
395
344
|
async function assertApiKeyValid(apiKey, opts = {}) {
|
|
396
345
|
const result = await validateApiKey(apiKey, opts);
|
|
@@ -408,34 +357,20 @@ var MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
|
408
357
|
function mcpToolName(tool) {
|
|
409
358
|
return `${MCP_TOOL_PREFIX}${tool}`;
|
|
410
359
|
}
|
|
411
|
-
var DECIDE_TOOL = mcpToolName("agentchat_decide");
|
|
412
|
-
var GET_CONVERSATION_TOOL = mcpToolName("agentchat_get_conversation");
|
|
413
360
|
var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
|
|
414
361
|
var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
|
|
415
362
|
function spellToolsForOpenClaw(text) {
|
|
416
363
|
return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token));
|
|
417
364
|
}
|
|
418
|
-
function wakeTurnPrompt(texts, conversationId) {
|
|
419
|
-
const instruction = texts.wake_instruction.trim();
|
|
420
|
-
if (!conversationId) return instruction;
|
|
421
|
-
return `${instruction}
|
|
422
|
-
|
|
423
|
-
${conversationLine(conversationId)}`;
|
|
424
|
-
}
|
|
425
|
-
function conversationLine(conversationId) {
|
|
426
|
-
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.`;
|
|
427
|
-
}
|
|
428
|
-
function inviteTurnPrompt(texts) {
|
|
429
|
-
return texts.invite_prompt.trim();
|
|
430
|
-
}
|
|
431
365
|
function wakeSessionKey(agentId, now = Date.now(), nonce = randomNonce()) {
|
|
432
366
|
return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`;
|
|
433
367
|
}
|
|
434
|
-
function inviteSessionKey(agentId, inviteId) {
|
|
435
|
-
return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`;
|
|
368
|
+
function inviteSessionKey(agentId, inviteId, now = Date.now(), nonce = randomNonce()) {
|
|
369
|
+
return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}-${utcStamp(now)}-${nonce}`;
|
|
436
370
|
}
|
|
437
|
-
function integrationLane(accountId) {
|
|
438
|
-
|
|
371
|
+
function integrationLane(accountId, generation2 = 0) {
|
|
372
|
+
const base = `agentchat-integration:${sanitizeKeyPart(accountId)}`;
|
|
373
|
+
return generation2 > 0 ? `${base}:${generation2}` : base;
|
|
439
374
|
}
|
|
440
375
|
function utcStamp(ms) {
|
|
441
376
|
return new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
@@ -452,18 +387,25 @@ function sanitizeKeyPart(value) {
|
|
|
452
387
|
var MCP_PATH = "/mcp";
|
|
453
388
|
var AUTH_HEADER_TEMPLATE = `Bearer \${${API_KEY_ENV}}`;
|
|
454
389
|
var DEFAULT_API_BASE2 = "https://api.agentchat.me";
|
|
455
|
-
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
456
390
|
function hostedMcpUrl(apiBase = DEFAULT_API_BASE2) {
|
|
457
391
|
return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
|
|
458
392
|
}
|
|
393
|
+
var CLIENT_HEADER = "X-AgentChat-Client";
|
|
394
|
+
function clientIdentityHeaders() {
|
|
395
|
+
return { [CLIENT_HEADER]: AGENTCHAT_CLIENT_NAME };
|
|
396
|
+
}
|
|
397
|
+
function clientIdentityText() {
|
|
398
|
+
return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
|
|
399
|
+
}
|
|
459
400
|
function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE2) {
|
|
460
401
|
return {
|
|
461
402
|
url: hostedMcpUrl(apiBase),
|
|
462
403
|
transport: "streamable-http",
|
|
463
|
-
headers: { Authorization: AUTH_HEADER_TEMPLATE }
|
|
404
|
+
headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
|
|
464
405
|
};
|
|
465
406
|
}
|
|
466
407
|
function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
|
|
408
|
+
const identity = clientIdentityHeaders();
|
|
467
409
|
return [
|
|
468
410
|
"{",
|
|
469
411
|
" mcp: {",
|
|
@@ -471,7 +413,10 @@ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
|
|
|
471
413
|
` ${MCP_SERVER_NAME}: {`,
|
|
472
414
|
` url: "${hostedMcpUrl(apiBase)}",`,
|
|
473
415
|
' transport: "streamable-http",',
|
|
474
|
-
|
|
416
|
+
" headers: {",
|
|
417
|
+
` Authorization: "${AUTH_HEADER_TEMPLATE}",`,
|
|
418
|
+
` "${CLIENT_HEADER}": "${identity[CLIENT_HEADER]}",`,
|
|
419
|
+
" },",
|
|
475
420
|
" },",
|
|
476
421
|
" },",
|
|
477
422
|
" },",
|
|
@@ -494,23 +439,99 @@ function pointsAtUs(entry, apiBase, apiKey) {
|
|
|
494
439
|
const headers = entry.headers;
|
|
495
440
|
if (headers === void 0) return true;
|
|
496
441
|
if (!headers || typeof headers !== "object" || Array.isArray(headers)) return false;
|
|
497
|
-
const
|
|
442
|
+
const auths = headerValues(headers, "Authorization");
|
|
443
|
+
if (auths.length > 1) return false;
|
|
444
|
+
const auth = auths[0];
|
|
498
445
|
if (auth === void 0) return true;
|
|
499
446
|
if (typeof auth !== "string") return false;
|
|
500
447
|
if (auth === AUTH_HEADER_TEMPLATE || auth.includes(`\${${API_KEY_ENV}}`)) return true;
|
|
501
448
|
return apiKey !== void 0 && apiKey.length > 0 && auth.trim() === `Bearer ${apiKey}`;
|
|
502
449
|
}
|
|
450
|
+
function describeMcpIdentity(cfg) {
|
|
451
|
+
const entry = agentchatEntry(cfg);
|
|
452
|
+
const headers = entry && isRecord(entry.headers) ? entry.headers : void 0;
|
|
453
|
+
if (!headers) return "missing";
|
|
454
|
+
const want = clientIdentityHeaders();
|
|
455
|
+
const clients = headerValues(headers, CLIENT_HEADER);
|
|
456
|
+
const client = clients[0];
|
|
457
|
+
return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
|
|
458
|
+
}
|
|
503
459
|
function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
504
460
|
const state = describeMcpEntry(cfg, apiBase, apiKey);
|
|
505
461
|
const base = cfg ?? {};
|
|
506
|
-
if (state === "ours") return { cfg: base, outcome: "present" };
|
|
507
462
|
if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
|
|
508
463
|
if (state === "disabled") return { cfg: base, outcome: "disabled" };
|
|
464
|
+
if (state === "ours" && describeMcpIdentity(base) === "current") return { cfg: base, outcome: "present" };
|
|
509
465
|
const mcp = { ...base.mcp ?? {} };
|
|
510
466
|
const servers = { ...mcp.servers ?? {} };
|
|
511
|
-
servers[MCP_SERVER_NAME]
|
|
467
|
+
const existing = servers[MCP_SERVER_NAME];
|
|
468
|
+
servers[MCP_SERVER_NAME] = state === "ours" && isRecord(existing) ? upgradedHostedMcpEntry(existing, apiBase) : hostedMcpServerEntry(apiBase);
|
|
512
469
|
mcp.servers = servers;
|
|
513
|
-
return { cfg: { ...base, mcp }, outcome: "added" };
|
|
470
|
+
return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
|
|
471
|
+
}
|
|
472
|
+
function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
|
|
473
|
+
const headers = isRecord(entry.headers) ? entry.headers : {};
|
|
474
|
+
const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
|
|
475
|
+
return {
|
|
476
|
+
...entry,
|
|
477
|
+
url: hostedMcpUrl(apiBase),
|
|
478
|
+
transport: "streamable-http",
|
|
479
|
+
headers: { ...kept, ...clientIdentityHeaders() }
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
483
|
+
if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
|
|
484
|
+
const servers = draft.mcp.servers;
|
|
485
|
+
const existing = servers[MCP_SERVER_NAME];
|
|
486
|
+
if (!isRecord(existing)) return false;
|
|
487
|
+
servers[MCP_SERVER_NAME] = upgradedHostedMcpEntry(existing, apiBase);
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
var NoChange = class extends Error {
|
|
491
|
+
constructor(outcome) {
|
|
492
|
+
super(`no change (${outcome})`);
|
|
493
|
+
this.outcome = outcome;
|
|
494
|
+
}
|
|
495
|
+
outcome;
|
|
496
|
+
};
|
|
497
|
+
var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
|
|
498
|
+
async function refreshHostedMcpEntry(params) {
|
|
499
|
+
const apiBase = params.apiBase ?? DEFAULT_API_BASE2;
|
|
500
|
+
if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
|
|
501
|
+
if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
|
|
502
|
+
const mutate = params.config?.mutateConfigFile;
|
|
503
|
+
if (typeof mutate !== "function") return { outcome: "unsupported" };
|
|
504
|
+
try {
|
|
505
|
+
await mutate.call(params.config, {
|
|
506
|
+
afterWrite: { mode: "auto" },
|
|
507
|
+
mutate: ((draft) => {
|
|
508
|
+
if (describeMcpEntry(draft, apiBase, params.apiKey) !== "ours") throw new NoChange("not_ours");
|
|
509
|
+
if (!upgradeHostedMcpEntryInPlace(draft, apiBase, params.apiKey)) throw new NoChange("current");
|
|
510
|
+
})
|
|
511
|
+
});
|
|
512
|
+
return { outcome: "updated" };
|
|
513
|
+
} catch (err) {
|
|
514
|
+
if (err instanceof NoChange) return { outcome: err.outcome };
|
|
515
|
+
const code = err?.code;
|
|
516
|
+
return {
|
|
517
|
+
outcome: "failed",
|
|
518
|
+
error: err instanceof Error ? err.message : String(err),
|
|
519
|
+
...typeof code === "string" ? { code } : {}
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
function isRecord(value) {
|
|
524
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
525
|
+
}
|
|
526
|
+
function agentchatEntry(cfg) {
|
|
527
|
+
const servers = cfg?.mcp?.servers;
|
|
528
|
+
if (!isRecord(servers)) return void 0;
|
|
529
|
+
const entry = servers[MCP_SERVER_NAME];
|
|
530
|
+
return isRecord(entry) ? entry : void 0;
|
|
531
|
+
}
|
|
532
|
+
function headerValues(headers, name) {
|
|
533
|
+
const wanted = name.toLowerCase();
|
|
534
|
+
return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
|
|
514
535
|
}
|
|
515
536
|
function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
516
537
|
if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
|
|
@@ -521,67 +542,24 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
|
521
542
|
return { cfg: { ...cfg, mcp }, removed: true };
|
|
522
543
|
}
|
|
523
544
|
async function probeHostedMcp(params) {
|
|
524
|
-
const
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
capabilities: {},
|
|
543
|
-
clientInfo: { name: "@agentchatme/openclaw doctor", version: "0" }
|
|
544
|
-
}
|
|
545
|
-
}),
|
|
546
|
-
signal: controller.signal
|
|
547
|
-
});
|
|
548
|
-
if (!res.ok) {
|
|
549
|
-
return { ok: false, status: res.status, error: res.status === 401 ? "the key does not authenticate against the hosted MCP server" : `HTTP ${res.status}` };
|
|
550
|
-
}
|
|
551
|
-
const text = await res.text();
|
|
552
|
-
const result = readInitializeResult(text);
|
|
553
|
-
if (!result) return { ok: false, status: res.status, error: "no initialize result in the answer" };
|
|
554
|
-
const serverInfo = result.serverInfo ?? {};
|
|
555
|
-
return {
|
|
556
|
-
ok: true,
|
|
557
|
-
status: res.status,
|
|
558
|
-
serverName: typeof serverInfo.name === "string" ? serverInfo.name : void 0,
|
|
559
|
-
serverVersion: typeof serverInfo.version === "string" ? serverInfo.version : void 0,
|
|
560
|
-
protocolVersion: typeof result.protocolVersion === "string" ? result.protocolVersion : void 0,
|
|
561
|
-
hasInstructions: typeof result.instructions === "string" && result.instructions.trim().length > 0
|
|
562
|
-
};
|
|
563
|
-
} catch (err) {
|
|
564
|
-
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
565
|
-
} finally {
|
|
566
|
-
clearTimeout(timer);
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
function readInitializeResult(text) {
|
|
570
|
-
const candidates = [];
|
|
571
|
-
const trimmed = text.trim();
|
|
572
|
-
if (trimmed.startsWith("{")) candidates.push(trimmed);
|
|
573
|
-
for (const line of text.split(/\r?\n/)) {
|
|
574
|
-
if (line.startsWith("data:")) candidates.push(line.slice(5).trim());
|
|
575
|
-
}
|
|
576
|
-
for (const candidate of candidates) {
|
|
577
|
-
try {
|
|
578
|
-
const parsed = JSON.parse(candidate);
|
|
579
|
-
const result = parsed.result;
|
|
580
|
-
if (result && typeof result === "object" && !Array.isArray(result)) return result;
|
|
581
|
-
} catch {
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
return null;
|
|
545
|
+
const result = await integration.probeHostedTools({
|
|
546
|
+
apiBase: params.apiBase ?? DEFAULT_API_BASE2,
|
|
547
|
+
apiKey: params.apiKey,
|
|
548
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
549
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
550
|
+
...params.fetch ? { fetch: params.fetch } : {}
|
|
551
|
+
});
|
|
552
|
+
const missing = result.missing ?? [];
|
|
553
|
+
return {
|
|
554
|
+
ok: result.ok,
|
|
555
|
+
...result.status !== void 0 ? { status: result.status } : {},
|
|
556
|
+
...result.serverName ? { serverName: result.serverName } : {},
|
|
557
|
+
...result.serverVersion ? { serverVersion: result.serverVersion } : {},
|
|
558
|
+
...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {},
|
|
559
|
+
...result.tools ? { tools: result.tools } : {},
|
|
560
|
+
...missing.length > 0 ? { missing } : {},
|
|
561
|
+
...result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(", ")} for this key` } : {}
|
|
562
|
+
};
|
|
585
563
|
}
|
|
586
564
|
|
|
587
565
|
// src/integration/runtime-holder.ts
|
|
@@ -601,11 +579,137 @@ function setPluginRuntime(runtime) {
|
|
|
601
579
|
function getPluginRuntime() {
|
|
602
580
|
return current;
|
|
603
581
|
}
|
|
582
|
+
|
|
583
|
+
// src/integration/run.ts
|
|
584
|
+
var DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 6e4;
|
|
585
|
+
var RUN_WAIT_RETRY_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
|
|
586
|
+
var MIN_WAIT_SPACING_MS = 1e3;
|
|
587
|
+
var TRANSCRIPT_READ_LIMIT = 200;
|
|
588
|
+
var METADATA_KEYS = ["endedAt", "stopReason", "livenessState", "pendingError", "timeoutPhase", "startedAt", "providerStarted"];
|
|
589
|
+
function runEndOf(wait, timing) {
|
|
590
|
+
const status = wait?.status;
|
|
591
|
+
const error = nonEmpty(wait?.error);
|
|
592
|
+
if (status === "ok") return { ended: true, status: "ok" };
|
|
593
|
+
if (status === "error") {
|
|
594
|
+
if (error && error.trim().toLowerCase() === "completed") return { ended: true, status: "ok" };
|
|
595
|
+
return { ended: true, status: "error", ...error ? { error } : {} };
|
|
596
|
+
}
|
|
597
|
+
if (status !== "timeout") {
|
|
598
|
+
return { ended: false };
|
|
599
|
+
}
|
|
600
|
+
const ended = { ended: true, status: "timeout", ...error ? { error } : {} };
|
|
601
|
+
const hasMetadata = wait !== null && wait !== void 0 && METADATA_KEYS.some((key) => key in wait);
|
|
602
|
+
if (!hasMetadata) {
|
|
603
|
+
return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false };
|
|
604
|
+
}
|
|
605
|
+
if (wait.pendingError === true) return { ended: false };
|
|
606
|
+
if (typeof wait.endedAt === "number" || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended;
|
|
607
|
+
if (isHardTimeout(wait)) return ended;
|
|
608
|
+
return error ? ended : { ended: false };
|
|
609
|
+
}
|
|
610
|
+
var HARD_TIMEOUT_PHASES = /* @__PURE__ */ new Set(["preflight", "provider", "tool_execution", "post_turn"]);
|
|
611
|
+
function isHardTimeout(wait) {
|
|
612
|
+
const phase = typeof wait.timeoutPhase === "string" ? wait.timeoutPhase.trim() : "";
|
|
613
|
+
if (HARD_TIMEOUT_PHASES.has(phase)) return true;
|
|
614
|
+
return wait.status === "timeout" && wait.providerStarted === true && nonEmpty(wait.stopReason) !== "restart";
|
|
615
|
+
}
|
|
616
|
+
async function watchRunUntilEnded(options) {
|
|
617
|
+
const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS;
|
|
618
|
+
const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS;
|
|
619
|
+
const now = options.now ?? Date.now;
|
|
620
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
621
|
+
const started = now();
|
|
622
|
+
let failures = 0;
|
|
623
|
+
for (; ; ) {
|
|
624
|
+
const runtime = options.runtime();
|
|
625
|
+
if (!runtime) return { ended: false, reason: "gone", elapsedMs: now() - started };
|
|
626
|
+
const waitStarted = now();
|
|
627
|
+
let observation;
|
|
628
|
+
try {
|
|
629
|
+
observation = await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs });
|
|
630
|
+
} catch (err) {
|
|
631
|
+
const message = describe(err);
|
|
632
|
+
const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 6e4;
|
|
633
|
+
failures += 1;
|
|
634
|
+
options.onWaitError?.(message, failures, delay);
|
|
635
|
+
await sleep(delay);
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
failures = 0;
|
|
639
|
+
const elapsedMs = now() - waitStarted;
|
|
640
|
+
const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs });
|
|
641
|
+
if (end.ended) return { ...end, elapsedMs: now() - started };
|
|
642
|
+
options.onStillRunning?.(now() - started);
|
|
643
|
+
if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
function countAgentChatCalls(messages, runId) {
|
|
647
|
+
if (messages.length === 0) return null;
|
|
648
|
+
let recognised = false;
|
|
649
|
+
let made = 0;
|
|
650
|
+
let failed = 0;
|
|
651
|
+
for (const row of messages) {
|
|
652
|
+
const message = unwrapMessage(row);
|
|
653
|
+
if (!message) continue;
|
|
654
|
+
const role = message.role;
|
|
655
|
+
if (role === "assistant" || role === "user") recognised = true;
|
|
656
|
+
if (role !== "toolResult" && role !== "tool") continue;
|
|
657
|
+
recognised = true;
|
|
658
|
+
const meta = asRecord2(message.__openclaw);
|
|
659
|
+
if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
|
|
660
|
+
if (!isAgentChatToolResult(message)) continue;
|
|
661
|
+
made += 1;
|
|
662
|
+
if (message.isError === true) failed += 1;
|
|
663
|
+
}
|
|
664
|
+
return recognised ? { made, failed } : null;
|
|
665
|
+
}
|
|
666
|
+
async function readAgentChatCalls(runtime, sessionKey, runId) {
|
|
667
|
+
if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
|
|
668
|
+
try {
|
|
669
|
+
const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
|
|
670
|
+
const messages = result?.messages;
|
|
671
|
+
return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
|
|
672
|
+
} catch {
|
|
673
|
+
return null;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
677
|
+
function isAgentChatToolResult(message) {
|
|
678
|
+
const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
|
|
679
|
+
if (toolName.startsWith(TOOL_PREFIX)) return true;
|
|
680
|
+
const tool = asRecord2(asRecord2(message.details)?.tool);
|
|
681
|
+
if (!tool) return false;
|
|
682
|
+
if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
|
|
683
|
+
if (tool.sourceName === MCP_SERVER_NAME) return true;
|
|
684
|
+
const mcp = asRecord2(tool.mcp);
|
|
685
|
+
return mcp?.serverName === MCP_SERVER_NAME;
|
|
686
|
+
}
|
|
687
|
+
function unwrapMessage(row) {
|
|
688
|
+
const record = asRecord2(row);
|
|
689
|
+
if (!record) return null;
|
|
690
|
+
if (typeof record.role === "string") return record;
|
|
691
|
+
const inner = asRecord2(record.message);
|
|
692
|
+
return inner && typeof inner.role === "string" ? inner : null;
|
|
693
|
+
}
|
|
694
|
+
function asRecord2(value) {
|
|
695
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
696
|
+
}
|
|
697
|
+
function nonEmpty(value) {
|
|
698
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
699
|
+
}
|
|
700
|
+
function describe(err) {
|
|
701
|
+
return err instanceof Error ? err.message : String(err);
|
|
702
|
+
}
|
|
703
|
+
function defaultSleep(ms) {
|
|
704
|
+
return new Promise((resolve) => {
|
|
705
|
+
const timer = setTimeout(resolve, ms);
|
|
706
|
+
timer.unref?.();
|
|
707
|
+
});
|
|
708
|
+
}
|
|
604
709
|
var DEFAULT_AGENT_ID = "main";
|
|
605
710
|
var GATE_TEMPERATURE = 0;
|
|
606
711
|
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
607
712
|
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
608
|
-
var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
|
|
609
713
|
var RuntimeUnavailableError = class extends Error {
|
|
610
714
|
constructor(what) {
|
|
611
715
|
super(`OpenClaw plugin runtime unavailable \u2014 ${what} needs setRuntime(...) from defineChannelPluginEntry`);
|
|
@@ -630,16 +734,21 @@ function createRuntimeModelCall(params) {
|
|
|
630
734
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
631
735
|
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
632
736
|
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
633
|
-
return async (prompt) => {
|
|
737
|
+
return async (prompt, options) => {
|
|
634
738
|
const runtime = getRuntime();
|
|
635
739
|
if (!runtime) throw new RuntimeUnavailableError("the gate call");
|
|
740
|
+
const signals = [
|
|
741
|
+
...Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : [],
|
|
742
|
+
...options?.signal ? [options.signal] : []
|
|
743
|
+
];
|
|
744
|
+
const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
636
745
|
const result = await runtime.llm.complete({
|
|
637
746
|
messages: [{ role: "user", content: prompt }],
|
|
638
747
|
maxTokens,
|
|
639
748
|
temperature: GATE_TEMPERATURE,
|
|
640
749
|
...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
|
|
641
750
|
purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
|
|
642
|
-
...
|
|
751
|
+
...signal ? { signal } : {}
|
|
643
752
|
});
|
|
644
753
|
return typeof result?.text === "string" ? result.text : "";
|
|
645
754
|
};
|
|
@@ -669,10 +778,14 @@ function resolveGateAgent(params) {
|
|
|
669
778
|
return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
|
|
670
779
|
}
|
|
671
780
|
function readLiveConfig(fallback, runtime = getPluginRuntime) {
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
if (
|
|
675
|
-
|
|
781
|
+
const config = runtime()?.config;
|
|
782
|
+
for (const read of [config?.current, config?.loadConfig]) {
|
|
783
|
+
if (typeof read !== "function") continue;
|
|
784
|
+
try {
|
|
785
|
+
const loaded = read.call(config);
|
|
786
|
+
if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
|
|
787
|
+
} catch {
|
|
788
|
+
}
|
|
676
789
|
}
|
|
677
790
|
return { cfg: fallback, live: false };
|
|
678
791
|
}
|
|
@@ -700,11 +813,11 @@ function turnReadiness(params) {
|
|
|
700
813
|
}
|
|
701
814
|
function createRuntimeTurnStarter(params = {}) {
|
|
702
815
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
703
|
-
const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
|
|
704
816
|
return async (request) => {
|
|
705
817
|
const runtime = getRuntime();
|
|
706
818
|
if (!runtime) return { ran: false, error: new RuntimeUnavailableError("the agent turn").message };
|
|
707
819
|
let runId;
|
|
820
|
+
let sessionKey = request.sessionKey;
|
|
708
821
|
try {
|
|
709
822
|
const admitted = await runtime.subagent.run({
|
|
710
823
|
sessionKey: request.sessionKey,
|
|
@@ -713,15 +826,46 @@ function createRuntimeTurnStarter(params = {}) {
|
|
|
713
826
|
deliver: false
|
|
714
827
|
});
|
|
715
828
|
runId = admitted.runId;
|
|
829
|
+
const accepted = admitted.sessionKey;
|
|
830
|
+
if (typeof accepted === "string" && accepted.trim().length > 0) sessionKey = accepted.trim();
|
|
716
831
|
} catch (err) {
|
|
717
832
|
return { ran: false, error: err instanceof Error ? err.message : String(err) };
|
|
718
833
|
}
|
|
719
|
-
const done =
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
834
|
+
const done = watchRunUntilEnded({
|
|
835
|
+
runtime: getRuntime,
|
|
836
|
+
runId,
|
|
837
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
838
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {},
|
|
839
|
+
...params.onWaitError ? { onWaitError: (error, attempt, retryInMs) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) } : {},
|
|
840
|
+
...params.now ? { now: params.now } : {},
|
|
841
|
+
...params.sleep ? { sleep: params.sleep } : {}
|
|
842
|
+
}).then(async (watched) => {
|
|
843
|
+
if (!watched.ended) return { ran: true, runId, status: "gone", elapsedMs: watched.elapsedMs };
|
|
844
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
845
|
+
return {
|
|
846
|
+
ran: true,
|
|
847
|
+
runId,
|
|
848
|
+
status: watched.status,
|
|
849
|
+
...watched.error ? { error: watched.error } : {},
|
|
850
|
+
agentchatCalls,
|
|
851
|
+
elapsedMs: watched.elapsedMs
|
|
852
|
+
};
|
|
853
|
+
});
|
|
854
|
+
return { ran: true, runId, sessionKey, done };
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
function createRunWatcher(params = {}) {
|
|
858
|
+
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
859
|
+
return async ({ runId, sessionKey }) => {
|
|
860
|
+
const watched = await watchRunUntilEnded({
|
|
861
|
+
runtime: getRuntime,
|
|
862
|
+
runId,
|
|
863
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
864
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}
|
|
865
|
+
});
|
|
866
|
+
if (!watched.ended) return null;
|
|
867
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
868
|
+
return { ran: true, runId, status: watched.status, ...watched.error ? { error: watched.error } : {}, agentchatCalls, elapsedMs: watched.elapsedMs };
|
|
725
869
|
};
|
|
726
870
|
}
|
|
727
871
|
var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
@@ -810,6 +954,7 @@ function applyIntegrationConfig(cfg, params) {
|
|
|
810
954
|
const mcp = withHostedMcpEntry(next, params.apiBase, params.apiKey);
|
|
811
955
|
next = mcp.cfg;
|
|
812
956
|
if (mcp.outcome === "added") changes.push(`mcp.servers.agentchat \u2192 ${hostedMcpUrl(params.apiBase)} (bearer template on ${API_KEY_ENV})`);
|
|
957
|
+
if (mcp.outcome === "updated") changes.push(`mcp.servers.agentchat names this client (${clientIdentityText()})`);
|
|
813
958
|
const bound = resolveBoundAgentId(next, AGENTCHAT_CHANNEL_ID, params.accountId);
|
|
814
959
|
const ambient = resolveOpenClawDefaultAgentId(next);
|
|
815
960
|
if (bound && bound !== (ambient ?? bound)) {
|
|
@@ -860,7 +1005,7 @@ function restoreIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
860
1005
|
const written = writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
|
|
861
1006
|
return { outcome: "placed", path: written.path };
|
|
862
1007
|
} catch (err) {
|
|
863
|
-
return { outcome: "failed", path: filePath, detail:
|
|
1008
|
+
return { outcome: "failed", path: filePath, detail: describe2(err) };
|
|
864
1009
|
}
|
|
865
1010
|
}
|
|
866
1011
|
function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
@@ -872,7 +1017,7 @@ function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
872
1017
|
const written = writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
|
|
873
1018
|
return { outcome: "updated", path: written.path };
|
|
874
1019
|
} catch (err) {
|
|
875
|
-
return { outcome: "failed", path: agentsAnchorPath(cfg, agentId), detail:
|
|
1020
|
+
return { outcome: "failed", path: agentsAnchorPath(cfg, agentId), detail: describe2(err) };
|
|
876
1021
|
}
|
|
877
1022
|
}
|
|
878
1023
|
function placeIntegration(params) {
|
|
@@ -886,7 +1031,7 @@ function placeIntegration(params) {
|
|
|
886
1031
|
detail: `${API_KEY_ENV} in ${key.path}${key.changed ? ` (a gateway started before this needs a restart, or a config reload, to resolve \${${API_KEY_ENV}})` : ""}`
|
|
887
1032
|
});
|
|
888
1033
|
} catch (err) {
|
|
889
|
-
steps.push({ name: "key", status: "failed", detail: `could not write ${API_KEY_ENV} to the OpenClaw .env: ${
|
|
1034
|
+
steps.push({ name: "key", status: "failed", detail: `could not write ${API_KEY_ENV} to the OpenClaw .env: ${describe2(err)}` });
|
|
890
1035
|
}
|
|
891
1036
|
}
|
|
892
1037
|
const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
|
|
@@ -902,7 +1047,7 @@ function placeIntegration(params) {
|
|
|
902
1047
|
const anchor = writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
|
|
903
1048
|
steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
|
|
904
1049
|
} catch (err) {
|
|
905
|
-
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${
|
|
1050
|
+
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe2(err)}` });
|
|
906
1051
|
}
|
|
907
1052
|
}
|
|
908
1053
|
steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
|
|
@@ -914,6 +1059,8 @@ function describeMcpOutcome(outcome, apiBase) {
|
|
|
914
1059
|
switch (outcome) {
|
|
915
1060
|
case "added":
|
|
916
1061
|
return { name: "mcp", status: "changed", detail: `hosted tools registered as mcp.servers.agentchat \u2192 ${hostedMcpUrl(apiBase)} (bearer template on ${API_KEY_ENV})` };
|
|
1062
|
+
case "updated":
|
|
1063
|
+
return { name: "mcp", status: "changed", detail: `mcp.servers.agentchat now names this client to the hosted tools (${clientIdentityText()})` };
|
|
917
1064
|
case "present":
|
|
918
1065
|
return { name: "mcp", status: "ok", detail: "hosted tools already registered as mcp.servers.agentchat" };
|
|
919
1066
|
case "disabled":
|
|
@@ -955,15 +1102,40 @@ function checkPlacement(params) {
|
|
|
955
1102
|
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)")}` });
|
|
956
1103
|
}
|
|
957
1104
|
checks.push({ name: "manual", ok: true, detail: "manual bundled as the agentchat skill" });
|
|
958
|
-
|
|
959
|
-
checks.push({
|
|
960
|
-
name: "mcp",
|
|
961
|
-
ok: mcpState === "ours" || mcpState === "user_managed",
|
|
962
|
-
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)")}`
|
|
963
|
-
});
|
|
1105
|
+
checks.push(checkMcpEntry(params.cfg, params.apiBase, params.apiKey, remedy));
|
|
964
1106
|
return checks;
|
|
965
1107
|
}
|
|
966
|
-
function
|
|
1108
|
+
function checkMcpEntry(cfg, apiBase, apiKey, remedy) {
|
|
1109
|
+
const unknownClient = "AgentChat treats the agent as an unknown client and lists the webhook-setup tools it does not need";
|
|
1110
|
+
switch (describeMcpEntry(cfg, apiBase, apiKey)) {
|
|
1111
|
+
case "ours": {
|
|
1112
|
+
const identity = describeMcpIdentity(cfg);
|
|
1113
|
+
if (identity === "current") return { name: "mcp", ok: true, detail: "hosted tools registered as mcp.servers.agentchat" };
|
|
1114
|
+
return {
|
|
1115
|
+
name: "mcp",
|
|
1116
|
+
ok: true,
|
|
1117
|
+
notice: true,
|
|
1118
|
+
repair: true,
|
|
1119
|
+
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`
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
case "user_managed": {
|
|
1123
|
+
if (describeMcpIdentity(cfg) === "current") return { name: "mcp", ok: true, detail: "mcp.servers.agentchat is managed by hand" };
|
|
1124
|
+
const identity = clientIdentityHeaders();
|
|
1125
|
+
return {
|
|
1126
|
+
name: "mcp",
|
|
1127
|
+
ok: true,
|
|
1128
|
+
notice: true,
|
|
1129
|
+
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`
|
|
1130
|
+
};
|
|
1131
|
+
}
|
|
1132
|
+
case "disabled":
|
|
1133
|
+
return { name: "mcp", ok: false, detail: "mcp.servers.agentchat is disabled \u2014 the agent has no AgentChat tools" };
|
|
1134
|
+
case "missing":
|
|
1135
|
+
return { name: "mcp", ok: false, repair: true, detail: `mcp.servers.agentchat missing \u2014 ${remedy("run openclaw doctor --fix (or openclaw channels add agentchat)")}` };
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
function describe2(err) {
|
|
967
1139
|
return err instanceof Error ? err.message : String(err);
|
|
968
1140
|
}
|
|
969
1141
|
var PLUGIN_STATE_DIRNAME = "agentchat";
|
|
@@ -974,236 +1146,115 @@ function safeSegment(value) {
|
|
|
974
1146
|
function integrationStateDir(accountId, stateDir = resolveOpenClawStateDir()) {
|
|
975
1147
|
return path2.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
|
|
976
1148
|
}
|
|
977
|
-
|
|
978
|
-
|
|
1149
|
+
var OLD_INVITE_LEDGER_FILE = "invites.json";
|
|
1150
|
+
function removeOldStateFiles(accountId, stateDir) {
|
|
1151
|
+
const dir = integrationStateDir(accountId, stateDir);
|
|
1152
|
+
const removed = [];
|
|
1153
|
+
const ledger = path2.join(dir, OLD_INVITE_LEDGER_FILE);
|
|
1154
|
+
if (tryUnlink(ledger)) removed.push(ledger);
|
|
1155
|
+
const texts = path2.join(dir, "texts.json");
|
|
979
1156
|
try {
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
} catch {
|
|
987
|
-
return null;
|
|
1157
|
+
const entry = JSON.parse(fs.readFileSync(texts, "utf8"));
|
|
1158
|
+
if (entry.version !== 1 || typeof entry.runtime !== "string") {
|
|
1159
|
+
if (tryUnlink(texts)) removed.push(texts);
|
|
1160
|
+
}
|
|
1161
|
+
} catch (err) {
|
|
1162
|
+
if (err?.code !== "ENOENT" && tryUnlink(texts)) removed.push(texts);
|
|
988
1163
|
}
|
|
1164
|
+
return removed;
|
|
989
1165
|
}
|
|
990
|
-
function
|
|
991
|
-
fs.mkdirSync(path2.dirname(file), { recursive: true });
|
|
992
|
-
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
993
|
-
fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
|
|
994
|
-
`, "utf8");
|
|
1166
|
+
function tryUnlink(file) {
|
|
995
1167
|
try {
|
|
996
|
-
fs.
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
} catch {
|
|
1001
|
-
}
|
|
1002
|
-
throw err;
|
|
1168
|
+
fs.unlinkSync(file);
|
|
1169
|
+
return true;
|
|
1170
|
+
} catch {
|
|
1171
|
+
return false;
|
|
1003
1172
|
}
|
|
1004
1173
|
}
|
|
1005
1174
|
|
|
1006
1175
|
// src/integration/texts.ts
|
|
1007
1176
|
var TEXTS_RUNTIME = "openclaw";
|
|
1008
|
-
var TEXTS_REFRESH_MS = 24 * 60 * 6e4;
|
|
1009
|
-
var TEXTS_RETRY_MS = 5 * 6e4;
|
|
1010
|
-
var TEXTS_FETCH_TIMEOUT_MS = 1e4;
|
|
1011
1177
|
var TEXTS_CACHE_FILE = "texts.json";
|
|
1012
|
-
function isTexts(value) {
|
|
1013
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1014
|
-
const t = value;
|
|
1015
|
-
const manual = t.manual;
|
|
1016
|
-
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";
|
|
1017
|
-
}
|
|
1018
1178
|
function textsCachePath(accountId, stateDir) {
|
|
1019
1179
|
return path2.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1020
1180
|
}
|
|
1021
|
-
function readCachedTexts(accountId, stateDir) {
|
|
1022
|
-
const raw = readJsonFile(textsCachePath(accountId, stateDir));
|
|
1023
|
-
if (!raw || typeof raw !== "object") return null;
|
|
1024
|
-
const entry = raw;
|
|
1025
|
-
if (typeof entry.fetched_at !== "string" || !isTexts(entry.texts)) return null;
|
|
1026
|
-
return { fetched_at: entry.fetched_at, texts: entry.texts };
|
|
1027
|
-
}
|
|
1028
|
-
function writeCachedTexts(accountId, texts, fetchedAt, stateDir) {
|
|
1029
|
-
const file = textsCachePath(accountId, stateDir);
|
|
1030
|
-
const entry = { fetched_at: fetchedAt.toISOString(), texts };
|
|
1031
|
-
writeJsonFile(file, entry);
|
|
1032
|
-
return file;
|
|
1033
|
-
}
|
|
1034
1181
|
function spellTextsForOpenClaw(texts) {
|
|
1035
1182
|
return {
|
|
1036
1183
|
...texts,
|
|
1037
1184
|
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1038
1185
|
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1039
1186
|
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
1040
|
-
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
|
|
1187
|
+
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),
|
|
1188
|
+
...typeof texts.gate_call_preamble === "string" ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {},
|
|
1189
|
+
...typeof texts.gate_call_answer_format === "string" ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}
|
|
1041
1190
|
};
|
|
1042
1191
|
}
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1192
|
+
function createTextsCache(params) {
|
|
1193
|
+
return new integration.TextsCache({
|
|
1194
|
+
client: params.client,
|
|
1195
|
+
runtime: TEXTS_RUNTIME,
|
|
1196
|
+
filePath: textsCachePath(params.accountId, params.stateDir),
|
|
1197
|
+
...params.logger ? { onError: (err) => params.logger?.warn({ err: err.message }, "served texts") } : {}
|
|
1198
|
+
});
|
|
1047
1199
|
}
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
const texts = await fetchTexts(params.client, params.timeoutMs);
|
|
1052
|
-
const fetchedAt = new Date(now());
|
|
1053
|
-
try {
|
|
1054
|
-
writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir);
|
|
1055
|
-
} catch (err) {
|
|
1056
|
-
params.log?.warn({ err: describe2(err) }, "texts fetched but the cache could not be written");
|
|
1057
|
-
}
|
|
1058
|
-
return { texts: spellTextsForOpenClaw(texts), source: "server", fetchedAt: fetchedAt.toISOString() };
|
|
1059
|
-
} catch (err) {
|
|
1060
|
-
const cached = readCachedTexts(params.accountId, params.stateDir);
|
|
1061
|
-
if (cached) {
|
|
1062
|
-
params.log?.info({ err: describe2(err), fetchedAt: cached.fetched_at }, "texts: server unreachable \u2014 using the cached copy");
|
|
1063
|
-
return { texts: spellTextsForOpenClaw(cached.texts), source: "cache", fetchedAt: cached.fetched_at };
|
|
1064
|
-
}
|
|
1065
|
-
params.log?.debug({ err: describe2(err) }, "texts: server unreachable and nothing cached");
|
|
1066
|
-
return null;
|
|
1200
|
+
var OpenClawTexts = class {
|
|
1201
|
+
constructor(cache2) {
|
|
1202
|
+
this.cache = cache2;
|
|
1067
1203
|
}
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
function cachedIdentityLine(accountId, stateDir) {
|
|
1074
|
-
const cached = readCachedTexts(accountId, stateDir);
|
|
1075
|
-
return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null;
|
|
1076
|
-
}
|
|
1077
|
-
var TextsStore = class {
|
|
1078
|
-
client;
|
|
1079
|
-
accountId;
|
|
1080
|
-
logger;
|
|
1081
|
-
stateDir;
|
|
1082
|
-
refreshMs;
|
|
1083
|
-
retryMs;
|
|
1084
|
-
fetchTimeoutMs;
|
|
1085
|
-
now;
|
|
1086
|
-
_setTimeout;
|
|
1087
|
-
_clearTimeout;
|
|
1088
|
-
loaded = null;
|
|
1089
|
-
timer = null;
|
|
1090
|
-
inFlight = null;
|
|
1091
|
-
stopped = false;
|
|
1092
|
-
missingAnnounced = false;
|
|
1093
|
-
listeners = /* @__PURE__ */ new Set();
|
|
1094
|
-
loads = 0;
|
|
1095
|
-
serverLoads = 0;
|
|
1096
|
-
constructor(options) {
|
|
1097
|
-
this.client = options.client;
|
|
1098
|
-
this.accountId = options.accountId;
|
|
1099
|
-
this.logger = options.logger.child({ component: "texts", accountId: options.accountId });
|
|
1100
|
-
this.stateDir = options.stateDir;
|
|
1101
|
-
this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
|
|
1102
|
-
this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
|
|
1103
|
-
this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS;
|
|
1104
|
-
this.now = options.now ?? Date.now;
|
|
1105
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
1106
|
-
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
1204
|
+
cache;
|
|
1205
|
+
spelledFrom = null;
|
|
1206
|
+
spelled = null;
|
|
1207
|
+
current() {
|
|
1208
|
+
return this.spell(this.cache.current());
|
|
1107
1209
|
}
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
return this.loaded?.texts ?? null;
|
|
1210
|
+
async ensure() {
|
|
1211
|
+
return this.spell(await this.cache.ensure());
|
|
1111
1212
|
}
|
|
1112
1213
|
get source() {
|
|
1113
|
-
return this.
|
|
1214
|
+
return this.cache.source;
|
|
1114
1215
|
}
|
|
1115
1216
|
get fetchedAt() {
|
|
1116
|
-
return this.
|
|
1217
|
+
return this.cache.fetchedAt;
|
|
1117
1218
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
this.listeners.add(listener);
|
|
1121
|
-
return () => {
|
|
1122
|
-
this.listeners.delete(listener);
|
|
1123
|
-
};
|
|
1219
|
+
get lastError() {
|
|
1220
|
+
return this.cache.lastError;
|
|
1124
1221
|
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
this.
|
|
1130
|
-
this.logger.warn(
|
|
1131
|
-
{ retryMs: this.retryMs },
|
|
1132
|
-
"AgentChat texts unreachable and nothing cached \u2014 starting anyway; turns wait for the first copy, retried until it arrives"
|
|
1133
|
-
);
|
|
1222
|
+
spell(texts) {
|
|
1223
|
+
if (texts === null) return null;
|
|
1224
|
+
if (texts !== this.spelledFrom) {
|
|
1225
|
+
this.spelledFrom = texts;
|
|
1226
|
+
this.spelled = spellTextsForOpenClaw(texts);
|
|
1134
1227
|
}
|
|
1135
|
-
this.
|
|
1136
|
-
return texts;
|
|
1137
|
-
}
|
|
1138
|
-
/** The current copy, or one load attempt now (coalesced with any in flight). */
|
|
1139
|
-
async ensure() {
|
|
1140
|
-
if (this.loaded) return this.loaded.texts;
|
|
1141
|
-
if (this.stopped) return null;
|
|
1142
|
-
return this.load();
|
|
1228
|
+
return this.spelled;
|
|
1143
1229
|
}
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1230
|
+
};
|
|
1231
|
+
async function loadIdentityLine(params) {
|
|
1232
|
+
const cache2 = createTextsCache(params);
|
|
1233
|
+
try {
|
|
1234
|
+
const texts = await cache2.start();
|
|
1235
|
+
return texts ? spellToolsForOpenClaw(texts.identity_line) : null;
|
|
1236
|
+
} catch {
|
|
1237
|
+
return null;
|
|
1238
|
+
} finally {
|
|
1239
|
+
cache2.stop();
|
|
1147
1240
|
}
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1241
|
+
}
|
|
1242
|
+
function cachedIdentityLine(accountId, stateDir) {
|
|
1243
|
+
let raw;
|
|
1244
|
+
try {
|
|
1245
|
+
raw = fs.readFileSync(textsCachePath(accountId, stateDir), "utf8");
|
|
1246
|
+
} catch {
|
|
1247
|
+
return null;
|
|
1155
1248
|
}
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
accountId: this.accountId,
|
|
1163
|
-
stateDir: this.stateDir,
|
|
1164
|
-
now: this.now,
|
|
1165
|
-
log: this.logger,
|
|
1166
|
-
timeoutMs: this.fetchTimeoutMs
|
|
1167
|
-
});
|
|
1168
|
-
if (this.stopped) return next?.texts ?? null;
|
|
1169
|
-
if (next) {
|
|
1170
|
-
const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction;
|
|
1171
|
-
this.loaded = next;
|
|
1172
|
-
if (next.source === "server") {
|
|
1173
|
-
this.serverLoads += 1;
|
|
1174
|
-
this.logger[changed ? "info" : "debug"](
|
|
1175
|
-
{ version: next.texts.version, manual: next.texts.manual.version },
|
|
1176
|
-
"texts fetched from the server"
|
|
1177
|
-
);
|
|
1178
|
-
for (const listener of this.listeners) {
|
|
1179
|
-
try {
|
|
1180
|
-
listener(next.texts, next.source);
|
|
1181
|
-
} catch (err) {
|
|
1182
|
-
this.logger.warn({ err: describe2(err) }, "texts listener threw \u2014 continuing");
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
return next?.texts ?? null;
|
|
1188
|
-
})().finally(() => {
|
|
1189
|
-
this.inFlight = null;
|
|
1190
|
-
});
|
|
1191
|
-
return this.inFlight;
|
|
1192
|
-
}
|
|
1193
|
-
arm() {
|
|
1194
|
-
if (this.stopped) return;
|
|
1195
|
-
if (this.timer !== null) this._clearTimeout(this.timer);
|
|
1196
|
-
const delay = this.loaded === null ? this.retryMs : this.loaded.source === "cache" ? this.retryMs : this.refreshMs;
|
|
1197
|
-
this.timer = this._setTimeout(() => {
|
|
1198
|
-
this.timer = null;
|
|
1199
|
-
void this.load().finally(() => this.arm());
|
|
1200
|
-
}, delay);
|
|
1201
|
-
this.timer.unref?.();
|
|
1249
|
+
try {
|
|
1250
|
+
const entry = JSON.parse(raw);
|
|
1251
|
+
if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null;
|
|
1252
|
+
return spellToolsForOpenClaw(entry.texts.identity_line);
|
|
1253
|
+
} catch {
|
|
1254
|
+
return null;
|
|
1202
1255
|
}
|
|
1203
|
-
};
|
|
1204
|
-
function describe2(err) {
|
|
1205
|
-
return err instanceof Error ? err.message : String(err);
|
|
1206
1256
|
}
|
|
1257
|
+
var isTexts = integration.isTexts;
|
|
1207
1258
|
var cache = /* @__PURE__ */ new Map();
|
|
1208
1259
|
function createSdkClient(params) {
|
|
1209
1260
|
return new AgentChatClient({
|
|
@@ -1787,7 +1838,7 @@ var agentchatSetupWizard = {
|
|
|
1787
1838
|
{
|
|
1788
1839
|
value: "paste",
|
|
1789
1840
|
label: "I already have an API key",
|
|
1790
|
-
hint: "paste
|
|
1841
|
+
hint: "paste ac_\u2026 on the next prompt"
|
|
1791
1842
|
},
|
|
1792
1843
|
{
|
|
1793
1844
|
value: "recover",
|
|
@@ -1858,10 +1909,10 @@ var agentchatSetupWizard = {
|
|
|
1858
1909
|
preferredEnvVar: "AGENTCHAT_API_KEY",
|
|
1859
1910
|
envPrompt: "AGENTCHAT_API_KEY detected in env. Use it?",
|
|
1860
1911
|
keepPrompt: "AgentChat API key already configured. Keep it?",
|
|
1861
|
-
inputPrompt: "Paste your AgentChat API key (
|
|
1912
|
+
inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
|
|
1862
1913
|
helpTitle: "AgentChat API key",
|
|
1863
1914
|
helpLines: [
|
|
1864
|
-
"Format:
|
|
1915
|
+
"Format: ac_ followed by 43 base64url characters. Validated against",
|
|
1865
1916
|
"GET /v1/agents/me during this wizard \u2014 bad keys fail fast instead",
|
|
1866
1917
|
"of flapping reconnects at runtime."
|
|
1867
1918
|
],
|
|
@@ -2009,11 +2060,648 @@ var agentchatChannelConfigSchema = z.object({
|
|
|
2009
2060
|
function parseChannelConfig(input) {
|
|
2010
2061
|
return agentchatChannelConfigSchema.parse(input);
|
|
2011
2062
|
}
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2063
|
+
var TRAY_LIMIT = 50;
|
|
2064
|
+
function createAfterTurnRecorder(options) {
|
|
2065
|
+
const { client, logger } = options;
|
|
2066
|
+
return async (record, end) => {
|
|
2067
|
+
if (end.status === "still_running" || record.kind === "run") return;
|
|
2068
|
+
let fresh;
|
|
2069
|
+
try {
|
|
2070
|
+
fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true });
|
|
2071
|
+
} catch (err) {
|
|
2072
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn tray read failed \u2014 nothing recorded; the server re-wakes the card");
|
|
2073
|
+
fresh = null;
|
|
2074
|
+
}
|
|
2075
|
+
try {
|
|
2076
|
+
if (record.kind === "reply") {
|
|
2077
|
+
if (!record.card) return;
|
|
2078
|
+
const outcome2 = integration.turnOutcome({
|
|
2079
|
+
turn: end,
|
|
2080
|
+
turnStartedAt: record.startedAt,
|
|
2081
|
+
gateCard: record.card,
|
|
2082
|
+
category: record.category ?? null,
|
|
2083
|
+
freshTray: fresh,
|
|
2084
|
+
silentBefore: 0
|
|
2085
|
+
});
|
|
2086
|
+
const recorded2 = await integration.applyOutcome(client, outcome2);
|
|
2087
|
+
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)");
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
if (!record.invite) return;
|
|
2091
|
+
const outcome = integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 });
|
|
2092
|
+
const recorded = await integration.applyInviteOutcome(client, outcome);
|
|
2093
|
+
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)");
|
|
2094
|
+
} catch (err) {
|
|
2095
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn recording failed \u2014 the card stays on the tray; the server re-wakes it");
|
|
2096
|
+
}
|
|
2097
|
+
};
|
|
2098
|
+
}
|
|
2099
|
+
function cardFromStored(stored) {
|
|
2100
|
+
return { preview: null, ...stored };
|
|
2101
|
+
}
|
|
2102
|
+
function describe3(err) {
|
|
2103
|
+
return err instanceof Error ? err.message : String(err);
|
|
2104
|
+
}
|
|
2105
|
+
var TURN_STORE_FILE = "turns.json";
|
|
2106
|
+
var KEEP_ENDED_MS = 6e4;
|
|
2107
|
+
function storedCard(card, anchor) {
|
|
2108
|
+
return {
|
|
2109
|
+
conversation_id: card.conversation_id,
|
|
2110
|
+
...anchor ? { last_message_id: anchor } : {},
|
|
2111
|
+
...card.your_last_message_at !== void 0 ? { your_last_message_at: card.your_last_message_at } : {},
|
|
2112
|
+
...card.you_owe_reply !== void 0 ? { you_owe_reply: card.you_owe_reply } : {},
|
|
2113
|
+
...card.your_last_decision !== void 0 ? { your_last_decision: card.your_last_decision } : {}
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
var TurnStore = class {
|
|
2117
|
+
file;
|
|
2118
|
+
constructor(accountId, stateDir) {
|
|
2119
|
+
this.file = path2.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE);
|
|
2120
|
+
}
|
|
2121
|
+
/** What the last process left. Empty when there is no file or it cannot be read. */
|
|
2122
|
+
load() {
|
|
2123
|
+
let parsed;
|
|
2124
|
+
try {
|
|
2125
|
+
parsed = JSON.parse(fs.readFileSync(this.file, "utf8"));
|
|
2126
|
+
} catch {
|
|
2127
|
+
return [];
|
|
2128
|
+
}
|
|
2129
|
+
const turns = parsed?.turns;
|
|
2130
|
+
if (parsed?.version !== 1 || !Array.isArray(turns)) return [];
|
|
2131
|
+
return turns.filter(isStoredTurn);
|
|
2132
|
+
}
|
|
2133
|
+
/** Replace the file with `turns` (removed when empty). Returns false when the write failed. */
|
|
2134
|
+
write(turns) {
|
|
2135
|
+
try {
|
|
2136
|
+
if (turns.length === 0) {
|
|
2137
|
+
fs.rmSync(this.file, { force: true });
|
|
2138
|
+
return true;
|
|
2139
|
+
}
|
|
2140
|
+
fs.mkdirSync(path2.dirname(this.file), { recursive: true });
|
|
2141
|
+
const body = { version: 1, turns };
|
|
2142
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
2143
|
+
fs.writeFileSync(tmp, `${JSON.stringify(body)}
|
|
2144
|
+
`, { mode: 384 });
|
|
2145
|
+
fs.renameSync(tmp, this.file);
|
|
2146
|
+
return true;
|
|
2147
|
+
} catch {
|
|
2148
|
+
return false;
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
};
|
|
2152
|
+
function isStoredTurn(value) {
|
|
2153
|
+
const turn = value;
|
|
2154
|
+
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");
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
// src/integration/running.ts
|
|
2158
|
+
var TURN_OVERDUE_MS = 30 * 6e4;
|
|
2159
|
+
var OVERDUE_SLACK_MS = 5e3;
|
|
2160
|
+
function isOverdue(elapsedMs) {
|
|
2161
|
+
return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS;
|
|
2162
|
+
}
|
|
2163
|
+
var MAX_HUNG_TURNS = 2;
|
|
2164
|
+
var OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60;
|
|
2165
|
+
var RESTART_HOLD_MS = 3 * 6e4;
|
|
2166
|
+
var STORED_TURN_MAX_AGE_MS = 24 * 60 * 6e4;
|
|
2167
|
+
var RESTART_END_DETAIL = "the gateway restarted during the turn";
|
|
2168
|
+
function trackerKey(kind, id) {
|
|
2169
|
+
return kind === "reply" ? `conversation:${id}` : kind === "invite" ? `invite:${id}` : `run:${id}`;
|
|
2170
|
+
}
|
|
2171
|
+
function trackedTurn(record) {
|
|
2172
|
+
if (record.kind === "reply") return { kind: "reply", conversationId: record.id, anchor: record.anchor };
|
|
2173
|
+
if (record.kind === "invite") return { kind: "invite", inviteId: record.id };
|
|
2174
|
+
return null;
|
|
2175
|
+
}
|
|
2176
|
+
function storedOf(record) {
|
|
2177
|
+
if (record.kind === "run") return null;
|
|
2178
|
+
return {
|
|
2179
|
+
runId: record.runId,
|
|
2180
|
+
kind: record.kind,
|
|
2181
|
+
id: record.id,
|
|
2182
|
+
anchor: record.anchor,
|
|
2183
|
+
sessionKey: record.sessionKey,
|
|
2184
|
+
startedAt: record.startedAt,
|
|
2185
|
+
...record.firstStartedAt !== void 0 ? { firstStartedAt: record.firstStartedAt } : {},
|
|
2186
|
+
...record.category !== void 0 ? { category: record.category } : {},
|
|
2187
|
+
...record.kind === "reply" && record.card ? { card: storedCard(record.card, record.anchor) } : {}
|
|
2188
|
+
};
|
|
2189
|
+
}
|
|
2190
|
+
function recordOf(stored) {
|
|
2191
|
+
return {
|
|
2192
|
+
runId: stored.runId,
|
|
2193
|
+
kind: stored.kind,
|
|
2194
|
+
id: stored.id,
|
|
2195
|
+
anchor: stored.anchor,
|
|
2196
|
+
sessionKey: stored.sessionKey,
|
|
2197
|
+
startedAt: stored.startedAt,
|
|
2198
|
+
firstStartedAt: stored.firstStartedAt ?? stored.startedAt,
|
|
2199
|
+
owner: "previous-process",
|
|
2200
|
+
...stored.category !== void 0 ? { category: stored.category } : {},
|
|
2201
|
+
...stored.kind === "reply" && stored.card ? { card: cardFromStored(stored.card) } : {},
|
|
2202
|
+
...stored.kind === "invite" ? { invite: { invite_id: stored.id } } : {}
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
var AccountTurns = class {
|
|
2206
|
+
/** The kit's tracker for the account, shared by every loop for it. */
|
|
2207
|
+
tracker;
|
|
2208
|
+
entries = /* @__PURE__ */ new Map();
|
|
2209
|
+
/** Turns the last process left in flight, by session key. */
|
|
2210
|
+
adopted = /* @__PURE__ */ new Map();
|
|
2211
|
+
/** Turns OpenClaw is admitting right now. */
|
|
2212
|
+
admitting = /* @__PURE__ */ new Set();
|
|
2213
|
+
/** Ended runs still written to the store (`KEEP_ENDED_MS`). */
|
|
2214
|
+
kept = /* @__PURE__ */ new Map();
|
|
2215
|
+
keptTimer = null;
|
|
2216
|
+
live = null;
|
|
2217
|
+
wiring = {};
|
|
2218
|
+
/** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */
|
|
2219
|
+
lane = 0;
|
|
2220
|
+
now;
|
|
2221
|
+
constructor(options = {}) {
|
|
2222
|
+
this.now = options.now ?? Date.now;
|
|
2223
|
+
this.tracker = new integration.TurnTracker({ now: this.now });
|
|
2224
|
+
this.tracker.onRelease((handle) => {
|
|
2225
|
+
for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true;
|
|
2226
|
+
});
|
|
2227
|
+
}
|
|
2228
|
+
/** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */
|
|
2229
|
+
configure(wiring) {
|
|
2230
|
+
this.wiring = { ...this.wiring, ...wiring };
|
|
2231
|
+
}
|
|
2232
|
+
/** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */
|
|
2233
|
+
setLive(owner, wake, run = (fn) => fn()) {
|
|
2234
|
+
this.live = { owner, wake, run };
|
|
2235
|
+
}
|
|
2236
|
+
clearLive(owner) {
|
|
2237
|
+
if (this.live?.owner === owner) this.live = null;
|
|
2238
|
+
}
|
|
2239
|
+
/** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */
|
|
2240
|
+
admission(kind, id) {
|
|
2241
|
+
const admission = { key: trackerKey(kind, id), released: false };
|
|
2242
|
+
this.admitting.add(admission);
|
|
2243
|
+
return admission;
|
|
2244
|
+
}
|
|
2245
|
+
/** OpenClaw refused the turn: nothing to watch. */
|
|
2246
|
+
admitted(admission) {
|
|
2247
|
+
this.admitting.delete(admission);
|
|
2248
|
+
}
|
|
2249
|
+
/**
|
|
2250
|
+
* A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting
|
|
2251
|
+
* on it when it is handed off or released. `admission`: a turn whose kit
|
|
2252
|
+
* hold was released during admission starts out let go of.
|
|
2253
|
+
*/
|
|
2254
|
+
started(record, options = {}) {
|
|
2255
|
+
const releasedMeanwhile = options.admission?.released === true;
|
|
2256
|
+
if (options.admission) this.admitting.delete(options.admission);
|
|
2257
|
+
this.entries.set(record.runId, {
|
|
2258
|
+
record,
|
|
2259
|
+
state: releasedMeanwhile ? "released" : "kit",
|
|
2260
|
+
handle: null,
|
|
2261
|
+
since: 0,
|
|
2262
|
+
...options.letGo ? { letGo: options.letGo } : {}
|
|
2263
|
+
});
|
|
2264
|
+
this.persist();
|
|
2265
|
+
}
|
|
2266
|
+
run(runId) {
|
|
2267
|
+
return this.entries.get(runId)?.record;
|
|
2268
|
+
}
|
|
2269
|
+
/** Where the run stands (`null`: not a run of this account, or ended). */
|
|
2270
|
+
stateOf(runId) {
|
|
2271
|
+
return this.entries.get(runId)?.state ?? null;
|
|
2272
|
+
}
|
|
2273
|
+
/** Every run OpenClaw has not reported ended that still holds something, oldest first. */
|
|
2274
|
+
runningRuns() {
|
|
2275
|
+
return [...this.entries.values()].filter((entry) => entry.state !== "released").map((entry) => entry.record).sort((a, b) => a.startedAt - b.startedAt);
|
|
2276
|
+
}
|
|
2277
|
+
hungRuns() {
|
|
2278
|
+
return [...this.entries.values()].filter((entry) => entry.state === "hung").map((entry) => entry.record);
|
|
2279
|
+
}
|
|
2280
|
+
get hungCount() {
|
|
2281
|
+
let count = 0;
|
|
2282
|
+
for (const entry of this.entries.values()) if (entry.state === "hung") count += 1;
|
|
2283
|
+
return count;
|
|
2284
|
+
}
|
|
2285
|
+
/** The handed-off gate-off run still going, if any: no new run starts while it lives. */
|
|
2286
|
+
hungSingleRun() {
|
|
2287
|
+
for (const entry of this.entries.values()) if (entry.state === "hung" && entry.record.kind === "run") return entry.record;
|
|
2288
|
+
return null;
|
|
2289
|
+
}
|
|
2290
|
+
/** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */
|
|
2291
|
+
restartHolds() {
|
|
2292
|
+
const holds = [...this.adopted.values()].map((a) => ({
|
|
2293
|
+
record: a.record,
|
|
2294
|
+
until: a.until,
|
|
2295
|
+
watching: null
|
|
2296
|
+
}));
|
|
2297
|
+
for (const entry of this.entries.values()) if (entry.state === "watch") holds.push({ record: entry.record, until: null, watching: entry.record.runId });
|
|
2298
|
+
return holds;
|
|
2299
|
+
}
|
|
2300
|
+
/** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */
|
|
2301
|
+
get laneGeneration() {
|
|
2302
|
+
return this.lane;
|
|
2303
|
+
}
|
|
2304
|
+
/**
|
|
2305
|
+
* OpenClaw reported the run ended (`end`: what it did, when known). A turn
|
|
2306
|
+
* held here (handed off, or continued after a restart) gets the after-turn
|
|
2307
|
+
* rule, then its hold drops and the live loop is woken. A turn the kit
|
|
2308
|
+
* still holds is the kit's to record; the live loop is woken once the card
|
|
2309
|
+
* is free, only when an earlier loop started it. A run let go of records
|
|
2310
|
+
* nothing.
|
|
2311
|
+
*/
|
|
2312
|
+
async ended(runId, end) {
|
|
2313
|
+
const entry = this.entries.get(runId);
|
|
2314
|
+
if (!entry) return;
|
|
2315
|
+
this.entries.delete(runId);
|
|
2316
|
+
if (entry.state !== "released") this.keep(entry.record);
|
|
2317
|
+
else this.persist();
|
|
2318
|
+
if (entry.state === "hung" || entry.state === "watch") {
|
|
2319
|
+
try {
|
|
2320
|
+
if (end && this.wiring.recorder && entry.record.kind !== "run") await this.wiring.recorder(entry.record, end);
|
|
2321
|
+
} finally {
|
|
2322
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2323
|
+
this.live?.wake();
|
|
2324
|
+
}
|
|
2325
|
+
return;
|
|
2326
|
+
}
|
|
2327
|
+
if (entry.state === "released" || entry.record.kind === "run") return;
|
|
2328
|
+
if (!this.live || this.live.owner === entry.record.owner) return;
|
|
2329
|
+
this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id));
|
|
2330
|
+
}
|
|
2331
|
+
/**
|
|
2332
|
+
* Hand a long run off, once, by run id: release the kit's slot for it (its
|
|
2333
|
+
* loop records nothing for it and may start other turns) and hold the
|
|
2334
|
+
* conversation here until the run ends. A gate-off run: the cycle waiting
|
|
2335
|
+
* on it is let go of. A continued run is already held here: it becomes
|
|
2336
|
+
* hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was
|
|
2337
|
+
* handed off now; null when it was already handed off or let go of.
|
|
2338
|
+
*/
|
|
2339
|
+
handOff(runId) {
|
|
2340
|
+
const entry = this.entries.get(runId);
|
|
2341
|
+
if (!entry || entry.state !== "kit" && entry.state !== "watch") return null;
|
|
2342
|
+
const record = entry.record;
|
|
2343
|
+
entry.since = this.now();
|
|
2344
|
+
if (entry.state === "watch") {
|
|
2345
|
+
entry.state = "hung";
|
|
2346
|
+
this.live?.wake();
|
|
2347
|
+
return record;
|
|
2348
|
+
}
|
|
2349
|
+
this.lane += 1;
|
|
2350
|
+
entry.state = "hung";
|
|
2351
|
+
const turn = trackedTurn(record);
|
|
2352
|
+
if (turn === null) {
|
|
2353
|
+
entry.letGo?.();
|
|
2354
|
+
} else {
|
|
2355
|
+
this.tracker.release(trackerKey(record.kind, record.id));
|
|
2356
|
+
entry.handle = this.tracker.begin(turn);
|
|
2357
|
+
if (!entry.handle) entry.state = "released";
|
|
2358
|
+
}
|
|
2359
|
+
this.live?.wake();
|
|
2360
|
+
return entry.state === "hung" ? record : null;
|
|
2361
|
+
}
|
|
2362
|
+
/**
|
|
2363
|
+
* An operator lets go of a conversation's (or invite's) turn: a hung hold,
|
|
2364
|
+
* a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn
|
|
2365
|
+
* still running. Its run may still be live and answer: a second reply is
|
|
2366
|
+
* then possible, which is why a turn under 30 minutes (most likely still
|
|
2367
|
+
* working) is refused without `force`. A gate-off run always needs
|
|
2368
|
+
* `force`: it reads the whole tray, so a new run would answer the same
|
|
2369
|
+
* cards while it may still be going.
|
|
2370
|
+
*/
|
|
2371
|
+
release(id, options = {}) {
|
|
2372
|
+
const live = this.live;
|
|
2373
|
+
return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true);
|
|
2374
|
+
}
|
|
2375
|
+
releaseNow(id, force) {
|
|
2376
|
+
const matches = (record) => record.id === id || record.runId === id;
|
|
2377
|
+
for (const entry of this.entries.values()) {
|
|
2378
|
+
if (entry.state !== "hung" || !matches(entry.record)) continue;
|
|
2379
|
+
if (entry.record.kind === "run" && !force) return this.refuseSingleRun(entry.record);
|
|
2380
|
+
entry.state = "released";
|
|
2381
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2382
|
+
entry.handle = null;
|
|
2383
|
+
this.persist();
|
|
2384
|
+
this.live?.wake();
|
|
2385
|
+
return { released: true, what: "hung", key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId };
|
|
2386
|
+
}
|
|
2387
|
+
for (const [sessionKey, adopted] of this.adopted) {
|
|
2388
|
+
if (adopted.record.id !== id) continue;
|
|
2389
|
+
this.finishAdopted(sessionKey);
|
|
2390
|
+
return { released: true, what: "restart", key: trackerKey(adopted.record.kind, adopted.record.id), runId: null };
|
|
2391
|
+
}
|
|
2392
|
+
for (const entry of this.entries.values()) {
|
|
2393
|
+
if (entry.state !== "kit" && entry.state !== "watch" || !matches(entry.record)) continue;
|
|
2394
|
+
const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force);
|
|
2395
|
+
if (refused) return refused;
|
|
2396
|
+
const key = trackerKey(entry.record.kind, entry.record.id);
|
|
2397
|
+
if (entry.state === "watch") {
|
|
2398
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2399
|
+
entry.handle = null;
|
|
2400
|
+
} else {
|
|
2401
|
+
this.lane += 1;
|
|
2402
|
+
if (entry.record.kind === "run") entry.letGo?.();
|
|
2403
|
+
else this.tracker.release(key);
|
|
2404
|
+
}
|
|
2405
|
+
entry.state = "released";
|
|
2406
|
+
this.persist();
|
|
2407
|
+
this.live?.wake();
|
|
2408
|
+
return { released: true, what: "running", key, runId: entry.record.runId };
|
|
2409
|
+
}
|
|
2410
|
+
for (const held of this.tracker.running()) {
|
|
2411
|
+
const heldId = held.kind === "reply" ? held.conversationId : held.inviteId;
|
|
2412
|
+
if (heldId !== id) continue;
|
|
2413
|
+
const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force);
|
|
2414
|
+
if (refused) return refused;
|
|
2415
|
+
this.lane += 1;
|
|
2416
|
+
const key = trackerKey(held.kind, heldId);
|
|
2417
|
+
if (this.tracker.release(key)) {
|
|
2418
|
+
this.live?.wake();
|
|
2419
|
+
return { released: true, what: "running", key, runId: null };
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
return { released: false, reason: `no turn holds ${id}` };
|
|
2423
|
+
}
|
|
2424
|
+
refuseYoung(kind, id, startedAt, force) {
|
|
2425
|
+
const age = this.now() - startedAt;
|
|
2426
|
+
if (force || age >= TURN_OVERDUE_MS) return null;
|
|
2427
|
+
return {
|
|
2428
|
+
released: false,
|
|
2429
|
+
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`
|
|
2430
|
+
};
|
|
2431
|
+
}
|
|
2432
|
+
refuseSingleRun(record) {
|
|
2433
|
+
return {
|
|
2434
|
+
released: false,
|
|
2435
|
+
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`
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
/**
|
|
2439
|
+
* Adopt the turns the last process left in flight (the store). Each one's
|
|
2440
|
+
* conversation (or invite) is held at once — before the loop's first gate —
|
|
2441
|
+
* for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended
|
|
2442
|
+
* run did now and again when the hold expires. A run OpenClaw starts in the
|
|
2443
|
+
* turn's session meanwhile (`observeRun`) takes the hold over. A turn first
|
|
2444
|
+
* started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what
|
|
2445
|
+
* was adopted.
|
|
2446
|
+
*/
|
|
2447
|
+
adopt(stored = this.wiring.store?.load() ?? []) {
|
|
2448
|
+
const adopted = [];
|
|
2449
|
+
const now = this.now();
|
|
2450
|
+
for (const turn of stored) {
|
|
2451
|
+
if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue;
|
|
2452
|
+
const first = turn.firstStartedAt ?? turn.startedAt;
|
|
2453
|
+
if (now - first > STORED_TURN_MAX_AGE_MS) {
|
|
2454
|
+
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");
|
|
2455
|
+
continue;
|
|
2456
|
+
}
|
|
2457
|
+
const record = recordOf(turn);
|
|
2458
|
+
const tracked = trackedTurn(record);
|
|
2459
|
+
const handle = tracked ? this.tracker.begin(tracked) : null;
|
|
2460
|
+
if (!handle) continue;
|
|
2461
|
+
const entry = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null };
|
|
2462
|
+
this.adopted.set(turn.sessionKey, entry);
|
|
2463
|
+
entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS);
|
|
2464
|
+
entry.timer.unref?.();
|
|
2465
|
+
adopted.push(record);
|
|
2466
|
+
void this.recordRestartEnded(entry);
|
|
2467
|
+
}
|
|
2468
|
+
this.persist();
|
|
2469
|
+
return adopted;
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* A run started in some session (the `model_call_started` hook). One in
|
|
2473
|
+
* the session of a turn adopted after a restart is OpenClaw continuing
|
|
2474
|
+
* that turn: it takes the hold over as a turn of its own (`watch`), handed
|
|
2475
|
+
* off past `TURN_OVERDUE_MS` like any other.
|
|
2476
|
+
*/
|
|
2477
|
+
observeRun(runId, sessionKey) {
|
|
2478
|
+
if (!sessionKey || this.entries.has(runId)) return;
|
|
2479
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2480
|
+
if (!adopted) return;
|
|
2481
|
+
this.adopted.delete(sessionKey);
|
|
2482
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2483
|
+
const record = { ...adopted.record, runId, startedAt: this.now(), owner: "restart" };
|
|
2484
|
+
this.entries.set(runId, { record, state: "watch", handle: adopted.handle, since: 0 });
|
|
2485
|
+
this.persist();
|
|
2486
|
+
this.wiring.logger?.info(
|
|
2487
|
+
{ runId, sessionKey, [record.kind === "reply" ? "conversationId" : "inviteId"]: record.id },
|
|
2488
|
+
"OpenClaw continued a turn session after the restart \u2014 its conversation stays held until that run ends"
|
|
2489
|
+
);
|
|
2490
|
+
void this.watchContinued(record);
|
|
2491
|
+
}
|
|
2492
|
+
async watchContinued(record) {
|
|
2493
|
+
let end = null;
|
|
2494
|
+
try {
|
|
2495
|
+
end = this.wiring.watch ? await this.wiring.watch(record) : null;
|
|
2496
|
+
} catch {
|
|
2497
|
+
end = null;
|
|
2498
|
+
}
|
|
2499
|
+
if (end === null) return;
|
|
2500
|
+
await this.ended(record.runId, end);
|
|
2501
|
+
}
|
|
2502
|
+
async recordRestartEnded(adopted) {
|
|
2503
|
+
const { record } = adopted;
|
|
2504
|
+
let calls = null;
|
|
2505
|
+
try {
|
|
2506
|
+
calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null;
|
|
2507
|
+
} catch {
|
|
2508
|
+
calls = null;
|
|
2509
|
+
}
|
|
2510
|
+
adopted.end = { status: "failed", agentchatCalls: calls, detail: RESTART_END_DETAIL };
|
|
2511
|
+
if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return;
|
|
2512
|
+
await this.wiring.recorder(record, adopted.end);
|
|
2513
|
+
}
|
|
2514
|
+
/**
|
|
2515
|
+
* The hold expired with nothing continuing the turn: the after-turn rule
|
|
2516
|
+
* once more — the resumed main session may have answered the card
|
|
2517
|
+
* meanwhile — then the conversation is free.
|
|
2518
|
+
*/
|
|
2519
|
+
expireAdopted(sessionKey, adopted) {
|
|
2520
|
+
if (this.adopted.get(sessionKey) !== adopted) return;
|
|
2521
|
+
void (async () => {
|
|
2522
|
+
try {
|
|
2523
|
+
if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: "failed", agentchatCalls: null, detail: RESTART_END_DETAIL });
|
|
2524
|
+
} catch {
|
|
2525
|
+
}
|
|
2526
|
+
if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey);
|
|
2527
|
+
})();
|
|
2528
|
+
}
|
|
2529
|
+
finishAdopted(sessionKey) {
|
|
2530
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2531
|
+
if (!adopted) return;
|
|
2532
|
+
this.adopted.delete(sessionKey);
|
|
2533
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2534
|
+
this.tracker.end(adopted.handle);
|
|
2535
|
+
this.persist();
|
|
2536
|
+
this.live?.wake();
|
|
2537
|
+
}
|
|
2538
|
+
/** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */
|
|
2539
|
+
keep(record) {
|
|
2540
|
+
const turn = storedOf(record);
|
|
2541
|
+
if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() });
|
|
2542
|
+
this.persist();
|
|
2543
|
+
if (!this.keptTimer) this.schedulePrune();
|
|
2544
|
+
}
|
|
2545
|
+
/** The next prune at the oldest kept entry's expiry. */
|
|
2546
|
+
schedulePrune() {
|
|
2547
|
+
let oldest = Infinity;
|
|
2548
|
+
for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt);
|
|
2549
|
+
if (oldest === Infinity) return;
|
|
2550
|
+
this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()));
|
|
2551
|
+
this.keptTimer.unref?.();
|
|
2552
|
+
}
|
|
2553
|
+
pruneKept() {
|
|
2554
|
+
this.keptTimer = null;
|
|
2555
|
+
const cutoff = this.now() - KEEP_ENDED_MS;
|
|
2556
|
+
for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId);
|
|
2557
|
+
this.persist();
|
|
2558
|
+
this.schedulePrune();
|
|
2559
|
+
}
|
|
2560
|
+
persist() {
|
|
2561
|
+
const store = this.wiring.store;
|
|
2562
|
+
if (!store) return;
|
|
2563
|
+
const turns = /* @__PURE__ */ new Map();
|
|
2564
|
+
for (const entry of this.entries.values()) {
|
|
2565
|
+
if (entry.state === "released") continue;
|
|
2566
|
+
const turn = storedOf(entry.record);
|
|
2567
|
+
if (turn) turns.set(turn.runId, turn);
|
|
2568
|
+
}
|
|
2569
|
+
for (const [runId, kept] of this.kept) turns.set(runId, kept.turn);
|
|
2570
|
+
for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored);
|
|
2571
|
+
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)");
|
|
2572
|
+
}
|
|
2573
|
+
wakeWhenFree(key, attempts = 300) {
|
|
2574
|
+
const held = key.startsWith("conversation:") ? this.tracker.conversationRunning(key.slice("conversation:".length)) : this.tracker.inviteRunning(key.slice("invite:".length));
|
|
2575
|
+
if (!held || attempts <= 0) {
|
|
2576
|
+
this.live?.wake();
|
|
2577
|
+
return;
|
|
2578
|
+
}
|
|
2579
|
+
const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100);
|
|
2580
|
+
timer.unref?.();
|
|
2581
|
+
}
|
|
2582
|
+
};
|
|
2583
|
+
var accounts = /* @__PURE__ */ new Map();
|
|
2584
|
+
function accountTurns(accountId) {
|
|
2585
|
+
let turns = accounts.get(accountId);
|
|
2586
|
+
if (!turns) {
|
|
2587
|
+
turns = new AccountTurns();
|
|
2588
|
+
accounts.set(accountId, turns);
|
|
2589
|
+
}
|
|
2590
|
+
return turns;
|
|
2591
|
+
}
|
|
2592
|
+
function findAccountTurns(accountId) {
|
|
2593
|
+
return accounts.get(accountId);
|
|
2594
|
+
}
|
|
2595
|
+
function trackerFor(accountId) {
|
|
2596
|
+
return accountTurns(accountId).tracker;
|
|
2597
|
+
}
|
|
2598
|
+
function observeRunStarted(runId, sessionKey) {
|
|
2599
|
+
if (typeof runId !== "string" || runId.length === 0 || typeof sessionKey !== "string" || sessionKey.length === 0) return;
|
|
2600
|
+
for (const turns of accounts.values()) turns.observeRun(runId, sessionKey);
|
|
2601
|
+
}
|
|
2602
|
+
function runDeadline(cfg) {
|
|
2603
|
+
const value = cfg?.agents?.defaults?.timeoutSeconds;
|
|
2604
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true };
|
|
2605
|
+
return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false };
|
|
2606
|
+
}
|
|
2607
|
+
function whatOf(kind, id) {
|
|
2608
|
+
return kind === "reply" ? `conversation ${id}` : kind === "invite" ? `invite ${id}` : `the gate-off run ${id}`;
|
|
2609
|
+
}
|
|
2610
|
+
function deadlineText(cfg) {
|
|
2611
|
+
const deadline = runDeadline(cfg);
|
|
2612
|
+
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)"}`;
|
|
2613
|
+
}
|
|
2614
|
+
function overdueTurnLine(turn, cfg) {
|
|
2615
|
+
const minutes = Math.round(turn.elapsedMs / 6e4);
|
|
2616
|
+
if (turn.kind === "run") {
|
|
2617
|
+
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)}`;
|
|
2618
|
+
}
|
|
2619
|
+
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`;
|
|
2620
|
+
}
|
|
2621
|
+
function overdueTurnLines(runs, cfg, now = Date.now()) {
|
|
2622
|
+
return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg));
|
|
2623
|
+
}
|
|
2624
|
+
function restartHoldLines(turns, now = Date.now()) {
|
|
2625
|
+
return turns.restartHolds().map(
|
|
2626
|
+
({ 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`
|
|
2627
|
+
);
|
|
2628
|
+
}
|
|
2629
|
+
function hungTurnsReason(turns, cfg, now = Date.now()) {
|
|
2630
|
+
const single = turns.hungSingleRun();
|
|
2631
|
+
if (single) {
|
|
2632
|
+
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)`;
|
|
2633
|
+
}
|
|
2634
|
+
if (turns.hungCount < MAX_HUNG_TURNS) return null;
|
|
2635
|
+
const held = turns.hungRuns().map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 6e4)} min`).join(", ");
|
|
2636
|
+
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`;
|
|
2637
|
+
}
|
|
2638
|
+
|
|
2639
|
+
// src/binding/release.ts
|
|
2640
|
+
var RELEASE_METHOD = "agentchat.release";
|
|
2641
|
+
function releaseTurnFor(params) {
|
|
2642
|
+
const id = typeof params.id === "string" ? params.id.trim() : "";
|
|
2643
|
+
if (!id) return { ok: false, error: "a conversation (or invite) id is required" };
|
|
2644
|
+
const accountId = typeof params.accountId === "string" && params.accountId.trim() ? params.accountId.trim() : "default";
|
|
2645
|
+
const turns = findAccountTurns(accountId);
|
|
2646
|
+
if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account "${accountId}" has no turns in this gateway` } };
|
|
2647
|
+
return { ok: true, result: turns.release(id, { force: params.force === true }) };
|
|
2648
|
+
}
|
|
2649
|
+
function registerReleaseGatewayMethod(api) {
|
|
2650
|
+
api.registerGatewayMethod(
|
|
2651
|
+
RELEASE_METHOD,
|
|
2652
|
+
({ params, respond }) => {
|
|
2653
|
+
const outcome = releaseTurnFor(params);
|
|
2654
|
+
if (!outcome.ok) {
|
|
2655
|
+
respond(false, void 0, { code: "INVALID_REQUEST", message: outcome.error });
|
|
2656
|
+
return;
|
|
2657
|
+
}
|
|
2658
|
+
respond(true, outcome.result);
|
|
2659
|
+
},
|
|
2660
|
+
{ scope: "operator.admin" }
|
|
2661
|
+
);
|
|
2662
|
+
}
|
|
2663
|
+
function registerReleaseCli(api) {
|
|
2664
|
+
api.registerCli(
|
|
2665
|
+
({ program }) => {
|
|
2666
|
+
const root = program.command(AGENTCHAT_CHANNEL_ID).description("The AgentChat integration");
|
|
2667
|
+
root.command("release <id>").description(
|
|
2668
|
+
`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.`
|
|
2669
|
+
).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) => {
|
|
2670
|
+
const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime');
|
|
2671
|
+
const result = await callGatewayFromCli(
|
|
2672
|
+
RELEASE_METHOD,
|
|
2673
|
+
{ ...opts.url ? { url: opts.url } : {}, ...opts.token ? { token: opts.token } : {}, ...opts.json ? { json: true } : {} },
|
|
2674
|
+
{ id, accountId: opts.account ?? "default", ...opts.force ? { force: true } : {} }
|
|
2675
|
+
);
|
|
2676
|
+
process.stdout.write(opts.json ? `${JSON.stringify(result)}
|
|
2677
|
+
` : `${releaseLine(id, result)}
|
|
2678
|
+
`);
|
|
2679
|
+
});
|
|
2680
|
+
},
|
|
2681
|
+
{
|
|
2682
|
+
commands: [AGENTCHAT_CHANNEL_ID],
|
|
2683
|
+
descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: "The AgentChat integration (release a hung turn)", hasSubcommands: true }]
|
|
2684
|
+
}
|
|
2685
|
+
);
|
|
2686
|
+
}
|
|
2687
|
+
function releaseLine(id, result) {
|
|
2688
|
+
if (!result?.released) return `nothing released: ${result?.reason ?? "unknown"}`;
|
|
2689
|
+
if (result.what === "restart") return `released ${id} (held after a gateway restart) \u2014 it may be gated again now`;
|
|
2690
|
+
const what = result.what === "hung" ? "a hung turn" : "a running turn";
|
|
2691
|
+
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`;
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
// src/binding/run-observer.ts
|
|
2695
|
+
function registerRunObserver(api) {
|
|
2696
|
+
api.on("model_call_started", (event, ctx) => {
|
|
2697
|
+
observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey);
|
|
2698
|
+
});
|
|
2699
|
+
}
|
|
2700
|
+
function createLogger(options) {
|
|
2701
|
+
if (options.delegate) {
|
|
2702
|
+
return options.delegate;
|
|
2703
|
+
}
|
|
2704
|
+
const pinoLogger = pino({
|
|
2017
2705
|
level: options.level,
|
|
2018
2706
|
base: { plugin: "@agentchatme/openclaw" },
|
|
2019
2707
|
redact: {
|
|
@@ -2107,85 +2795,12 @@ function createNoopMetrics() {
|
|
|
2107
2795
|
incWake: () => void 0
|
|
2108
2796
|
};
|
|
2109
2797
|
}
|
|
2110
|
-
function groupInviteFromRecord(record) {
|
|
2111
|
-
if (!record || typeof record !== "object" || Array.isArray(record)) return null;
|
|
2112
|
-
const row = record;
|
|
2113
|
-
const inviteId = str(row.id);
|
|
2114
|
-
const groupId = str(row.group_id);
|
|
2115
|
-
if (!inviteId || !groupId) return null;
|
|
2116
|
-
return {
|
|
2117
|
-
inviteId,
|
|
2118
|
-
groupId,
|
|
2119
|
-
groupName: str(row.group_name) ?? "",
|
|
2120
|
-
inviterHandle: (str(row.inviter_handle) ?? "").replace(/^@/, "")
|
|
2121
|
-
};
|
|
2122
|
-
}
|
|
2123
|
-
function str(value) {
|
|
2124
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2125
|
-
}
|
|
2126
|
-
var INVITE_LEDGER_FILE = "invites.json";
|
|
2127
|
-
var INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 6e4;
|
|
2128
|
-
function inviteLedgerPath(accountId, stateDir) {
|
|
2129
|
-
return path2.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE);
|
|
2130
|
-
}
|
|
2131
|
-
var InviteLedger = class {
|
|
2132
|
-
file;
|
|
2133
|
-
now;
|
|
2134
|
-
maxAgeMs;
|
|
2135
|
-
onWriteError;
|
|
2136
|
-
offered;
|
|
2137
|
-
constructor(options) {
|
|
2138
|
-
this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir);
|
|
2139
|
-
this.now = options.now ?? Date.now;
|
|
2140
|
-
this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS;
|
|
2141
|
-
this.onWriteError = options.onWriteError;
|
|
2142
|
-
this.offered = this.read();
|
|
2143
|
-
}
|
|
2144
|
-
get path() {
|
|
2145
|
-
return this.file;
|
|
2146
|
-
}
|
|
2147
|
-
get size() {
|
|
2148
|
-
return this.offered.size;
|
|
2149
|
-
}
|
|
2150
|
-
/** True when a turn for this invite was started before (in this process or an earlier one). */
|
|
2151
|
-
isOffered(inviteId) {
|
|
2152
|
-
return this.offered.has(inviteId);
|
|
2153
|
-
}
|
|
2154
|
-
/** Record that a turn for this invite was admitted. Persists at once. */
|
|
2155
|
-
markOffered(inviteId) {
|
|
2156
|
-
this.offered.set(inviteId, new Date(this.now()).toISOString());
|
|
2157
|
-
this.prune();
|
|
2158
|
-
try {
|
|
2159
|
-
writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) });
|
|
2160
|
-
} catch (err) {
|
|
2161
|
-
this.onWriteError?.(err);
|
|
2162
|
-
}
|
|
2163
|
-
}
|
|
2164
|
-
read() {
|
|
2165
|
-
const raw = readJsonFile(this.file);
|
|
2166
|
-
const out = /* @__PURE__ */ new Map();
|
|
2167
|
-
if (!raw || typeof raw !== "object") return out;
|
|
2168
|
-
const offered = raw.offered;
|
|
2169
|
-
if (!offered || typeof offered !== "object" || Array.isArray(offered)) return out;
|
|
2170
|
-
for (const [id, at] of Object.entries(offered)) {
|
|
2171
|
-
if (typeof at === "string" && id.length > 0) out.set(id, at);
|
|
2172
|
-
}
|
|
2173
|
-
this.offered = out;
|
|
2174
|
-
this.prune();
|
|
2175
|
-
return this.offered;
|
|
2176
|
-
}
|
|
2177
|
-
prune() {
|
|
2178
|
-
const cutoff = this.now() - this.maxAgeMs;
|
|
2179
|
-
for (const [id, at] of this.offered) {
|
|
2180
|
-
const t = Date.parse(at);
|
|
2181
|
-
if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id);
|
|
2182
|
-
}
|
|
2183
|
-
}
|
|
2184
|
-
};
|
|
2185
2798
|
|
|
2186
2799
|
// src/integration/socket.ts
|
|
2187
2800
|
function wakeSourceOf(reason) {
|
|
2188
|
-
|
|
2801
|
+
if (reason === "reminder") return "reminder";
|
|
2802
|
+
if (reason === "unanswered") return "unanswered";
|
|
2803
|
+
return "other";
|
|
2189
2804
|
}
|
|
2190
2805
|
function realtimeOptionsFor(config, extra = {}) {
|
|
2191
2806
|
return {
|
|
@@ -2193,6 +2808,10 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2193
2808
|
baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
|
|
2194
2809
|
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
2195
2810
|
ackOnReceipt: true,
|
|
2811
|
+
// `rewake`: the server re-wakes this socket while cards stay unanswered
|
|
2812
|
+
// (contract v1, D3) — the integration keeps no retry ladder of its own.
|
|
2813
|
+
// `heartbeat` is offered by default (the idle watchdog's proof of life).
|
|
2814
|
+
capabilities: { rewake: true },
|
|
2196
2815
|
reconnect: true,
|
|
2197
2816
|
reconnectInterval: config.reconnect.initialBackoffMs,
|
|
2198
2817
|
maxReconnectInterval: config.reconnect.maxBackoffMs,
|
|
@@ -2201,169 +2820,118 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2201
2820
|
};
|
|
2202
2821
|
}
|
|
2203
2822
|
var IntegrationSocket = class {
|
|
2204
|
-
|
|
2823
|
+
/** The SDK client: handed to the receive loop, which connects and disconnects it. */
|
|
2824
|
+
realtime;
|
|
2205
2825
|
logger;
|
|
2206
2826
|
handlers;
|
|
2207
2827
|
metrics;
|
|
2208
|
-
client;
|
|
2209
|
-
createRealtime;
|
|
2210
|
-
webSocket;
|
|
2211
2828
|
now;
|
|
2212
|
-
|
|
2213
|
-
realtime = null;
|
|
2214
|
-
/** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
|
|
2829
|
+
/** The SDK's state as last reported through its `state` event. */
|
|
2215
2830
|
state = "idle";
|
|
2216
2831
|
connectedAt = null;
|
|
2832
|
+
bound = false;
|
|
2217
2833
|
stopping = false;
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
wakes = 0;
|
|
2221
|
-
invites = 0;
|
|
2834
|
+
unbind = [];
|
|
2835
|
+
wakeFrames = 0;
|
|
2222
2836
|
disconnects = 0;
|
|
2223
2837
|
constructor(options) {
|
|
2224
|
-
this.config = options.config;
|
|
2225
2838
|
this.logger = options.logger.child({ component: "socket" });
|
|
2226
2839
|
this.handlers = options.handlers ?? {};
|
|
2227
2840
|
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2228
|
-
this.client = options.client;
|
|
2229
|
-
this.createRealtime = options.createRealtime ?? ((opts) => new RealtimeClient(opts));
|
|
2230
|
-
this.webSocket = options.webSocket;
|
|
2231
2841
|
this.now = options.now ?? Date.now;
|
|
2232
|
-
|
|
2842
|
+
const create = options.createRealtime ?? ((opts) => new RealtimeClient(opts));
|
|
2843
|
+
this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }));
|
|
2233
2844
|
this.metrics.setConnectionState(this.state);
|
|
2234
2845
|
}
|
|
2235
|
-
/**
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2846
|
+
/** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */
|
|
2847
|
+
bind() {
|
|
2848
|
+
if (this.bound || this.stopping) return;
|
|
2849
|
+
this.bound = true;
|
|
2850
|
+
const realtime = this.realtime;
|
|
2851
|
+
this.unbind.push(
|
|
2852
|
+
realtime.on("state", (next, prev) => this.onState(next, prev)),
|
|
2853
|
+
realtime.onConnect(() => {
|
|
2854
|
+
const at = this.now();
|
|
2855
|
+
this.connectedAt = at;
|
|
2856
|
+
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2857
|
+
this.metrics.incWake({ source: "connect" });
|
|
2858
|
+
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2859
|
+
}),
|
|
2860
|
+
realtime.onDisconnect((info) => {
|
|
2861
|
+
if (this.stopping) return;
|
|
2862
|
+
this.disconnects += 1;
|
|
2863
|
+
this.connectedAt = null;
|
|
2864
|
+
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2865
|
+
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2866
|
+
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2867
|
+
}),
|
|
2868
|
+
realtime.on("blocked", (info) => {
|
|
2869
|
+
if (this.stopping) return;
|
|
2870
|
+
this.metrics.incError({ errorClass: "auth" });
|
|
2871
|
+
this.logger.warn(
|
|
2872
|
+
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2873
|
+
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2874
|
+
);
|
|
2875
|
+
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2876
|
+
}),
|
|
2877
|
+
realtime.onError((error) => {
|
|
2878
|
+
if (this.stopping) return;
|
|
2879
|
+
if (realtime.state === "blocked") {
|
|
2880
|
+
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2881
|
+
return;
|
|
2882
|
+
}
|
|
2883
|
+
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2884
|
+
this.logger.debug({ err: error.message }, "socket error");
|
|
2885
|
+
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2886
|
+
}),
|
|
2887
|
+
// The loop turns a wake frame into a cycle; here it is only labelled
|
|
2888
|
+
// by its reason for the log line and the metric.
|
|
2889
|
+
realtime.on("wake", (frame) => {
|
|
2890
|
+
this.wakeFrames += 1;
|
|
2891
|
+
const payload = frame.payload ?? {};
|
|
2892
|
+
const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : void 0;
|
|
2893
|
+
this.metrics.incWake({ source: wakeSourceOf(payload.reason) });
|
|
2894
|
+
this.logger.info(
|
|
2895
|
+
{
|
|
2896
|
+
reason: payload.reason,
|
|
2897
|
+
step: payload.step,
|
|
2898
|
+
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2899
|
+
...conversations !== void 0 ? { conversations } : {}
|
|
2900
|
+
},
|
|
2901
|
+
"wake \u2014 server wake frame"
|
|
2902
|
+
);
|
|
2903
|
+
})
|
|
2904
|
+
);
|
|
2250
2905
|
}
|
|
2251
|
-
/**
|
|
2252
|
-
|
|
2906
|
+
/** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */
|
|
2907
|
+
stopped() {
|
|
2253
2908
|
this.stopping = true;
|
|
2254
|
-
const realtime = this.realtime;
|
|
2255
|
-
this.realtime = null;
|
|
2256
2909
|
this.connectedAt = null;
|
|
2257
|
-
|
|
2910
|
+
for (const off of this.unbind.splice(0)) {
|
|
2258
2911
|
try {
|
|
2259
|
-
|
|
2260
|
-
} catch
|
|
2261
|
-
this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
|
|
2912
|
+
off();
|
|
2913
|
+
} catch {
|
|
2262
2914
|
}
|
|
2263
2915
|
}
|
|
2264
2916
|
if (this.state !== "stopped") this.onState("stopped", this.state);
|
|
2265
2917
|
}
|
|
2266
2918
|
getHealth() {
|
|
2267
|
-
return {
|
|
2268
|
-
state: this.state,
|
|
2269
|
-
connectedAt: this.connectedAt,
|
|
2270
|
-
counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects }
|
|
2271
|
-
};
|
|
2272
|
-
}
|
|
2273
|
-
// ─── Internals ─────────────────────────────────────────────────────
|
|
2274
|
-
bind(realtime) {
|
|
2275
|
-
realtime.on("state", (next, prev) => this.onState(next, prev));
|
|
2276
|
-
realtime.onConnect(() => {
|
|
2277
|
-
const at = this.now();
|
|
2278
|
-
this.connectedAt = at;
|
|
2279
|
-
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2280
|
-
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2281
|
-
this.wake("connect", {});
|
|
2282
|
-
});
|
|
2283
|
-
realtime.onDisconnect((info) => {
|
|
2284
|
-
if (this.stopping) return;
|
|
2285
|
-
this.disconnects += 1;
|
|
2286
|
-
this.connectedAt = null;
|
|
2287
|
-
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2288
|
-
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2289
|
-
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2290
|
-
});
|
|
2291
|
-
realtime.on("blocked", (info) => {
|
|
2292
|
-
if (this.stopping) return;
|
|
2293
|
-
this.metrics.incError({ errorClass: "auth" });
|
|
2294
|
-
this.logger.warn(
|
|
2295
|
-
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2296
|
-
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2297
|
-
);
|
|
2298
|
-
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2299
|
-
});
|
|
2300
|
-
realtime.onError((error) => {
|
|
2301
|
-
if (this.stopping) return;
|
|
2302
|
-
if (realtime.state === "blocked") {
|
|
2303
|
-
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2304
|
-
return;
|
|
2305
|
-
}
|
|
2306
|
-
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2307
|
-
this.logger.debug({ err: error.message }, "socket error");
|
|
2308
|
-
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2309
|
-
});
|
|
2310
|
-
realtime.on("message.new", (message) => this.onMessageNew(message));
|
|
2311
|
-
realtime.on("wake", (frame) => this.onWakeFrame(frame));
|
|
2312
|
-
realtime.on("group.invite.received", (message) => this.onInvite(message));
|
|
2313
|
-
}
|
|
2314
|
-
onMessageNew(message) {
|
|
2315
|
-
this.frames += 1;
|
|
2316
|
-
const payload = message.payload ?? {};
|
|
2317
|
-
const senderRaw = payload.sender ?? payload.from ?? "";
|
|
2318
|
-
const sender = typeof senderRaw === "string" ? senderRaw.replace(/^@/, "").toLowerCase() : "";
|
|
2319
|
-
const detail = {
|
|
2320
|
-
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2321
|
-
...typeof payload.id === "string" ? { messageId: payload.id } : {},
|
|
2322
|
-
...sender ? { from: sender } : {}
|
|
2323
|
-
};
|
|
2324
|
-
if (this.selfHandle && sender === this.selfHandle) {
|
|
2325
|
-
this.selfFiltered += 1;
|
|
2326
|
-
this.logger.debug(detail, "own echo \u2014 not a wake");
|
|
2327
|
-
return;
|
|
2328
|
-
}
|
|
2329
|
-
this.logger.debug(detail, "wake \u2014 message.new");
|
|
2330
|
-
this.wake("message", detail);
|
|
2331
|
-
}
|
|
2332
|
-
onWakeFrame(frame) {
|
|
2333
|
-
this.frames += 1;
|
|
2334
|
-
const reason = frame.payload?.reason;
|
|
2335
|
-
const detail = { conversationId: frame.payload.conversation_id };
|
|
2336
|
-
this.logger.info({ ...detail, reason, step: frame.payload.step }, "wake \u2014 server wake frame");
|
|
2337
|
-
this.wake(wakeSourceOf(reason), detail);
|
|
2338
|
-
}
|
|
2339
|
-
onInvite(message) {
|
|
2340
|
-
this.frames += 1;
|
|
2341
|
-
const invite = groupInviteFromRecord(message.payload);
|
|
2342
|
-
if (!invite) {
|
|
2343
|
-
this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, "group.invite.received without ids \u2014 dropped");
|
|
2344
|
-
return;
|
|
2345
|
-
}
|
|
2346
|
-
this.invites += 1;
|
|
2347
|
-
this.guard("onGroupInvite", () => this.handlers.onGroupInvite?.(invite));
|
|
2348
|
-
}
|
|
2349
|
-
wake(source, detail) {
|
|
2350
|
-
this.wakes += 1;
|
|
2351
|
-
this.metrics.incWake({ source });
|
|
2352
|
-
this.guard("onWake", () => this.handlers.onWake?.(source, detail));
|
|
2919
|
+
return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } };
|
|
2353
2920
|
}
|
|
2354
2921
|
/** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
|
|
2355
2922
|
onState(next, prev) {
|
|
2923
|
+
if (this.state === next) return;
|
|
2356
2924
|
this.state = next;
|
|
2357
2925
|
this.metrics.setConnectionState(next);
|
|
2358
2926
|
this.logger.debug({ from: prev, to: next }, "socket state");
|
|
2359
2927
|
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2360
2928
|
}
|
|
2361
|
-
/** A failing handler never takes the socket down
|
|
2929
|
+
/** A failing handler never takes the socket down. */
|
|
2362
2930
|
guard(name, fn) {
|
|
2363
2931
|
try {
|
|
2364
2932
|
fn();
|
|
2365
2933
|
} catch (err) {
|
|
2366
|
-
this.logger.error({ err:
|
|
2934
|
+
this.logger.error({ err: describe4(err), handler: name }, "handler threw \u2014 continuing");
|
|
2367
2935
|
}
|
|
2368
2936
|
}
|
|
2369
2937
|
};
|
|
@@ -2374,7 +2942,7 @@ function classifyRealtimeError(error) {
|
|
|
2374
2942
|
if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
|
|
2375
2943
|
return "other";
|
|
2376
2944
|
}
|
|
2377
|
-
function
|
|
2945
|
+
function describe4(err) {
|
|
2378
2946
|
return err instanceof Error ? err.message : String(err);
|
|
2379
2947
|
}
|
|
2380
2948
|
|
|
@@ -2404,8 +2972,6 @@ function registerIntegration(params) {
|
|
|
2404
2972
|
}
|
|
2405
2973
|
let built = null;
|
|
2406
2974
|
const handlers = {
|
|
2407
|
-
onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
|
|
2408
|
-
onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
|
|
2409
2975
|
onConnected: (at) => built?.handlers.onConnected?.(at),
|
|
2410
2976
|
onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
|
|
2411
2977
|
onBlocked: (info) => built?.handlers.onBlocked?.(info),
|
|
@@ -2417,19 +2983,20 @@ function registerIntegration(params) {
|
|
|
2417
2983
|
built = params.build(socket);
|
|
2418
2984
|
const entry = {
|
|
2419
2985
|
socket,
|
|
2420
|
-
|
|
2986
|
+
loop: built.loop,
|
|
2421
2987
|
texts: built.texts ?? null,
|
|
2988
|
+
textsCache: built.textsCache ?? null,
|
|
2422
2989
|
metrics: params.socketOptions?.metrics ?? null,
|
|
2423
2990
|
config: params.config,
|
|
2424
2991
|
logger: params.logger
|
|
2425
2992
|
};
|
|
2426
2993
|
registry.set(params.accountId, entry);
|
|
2994
|
+
socket.bind();
|
|
2427
2995
|
try {
|
|
2428
|
-
await
|
|
2996
|
+
await built.loop?.loop.start();
|
|
2429
2997
|
} catch (err) {
|
|
2430
2998
|
registry.delete(params.accountId);
|
|
2431
|
-
|
|
2432
|
-
built.texts?.stop();
|
|
2999
|
+
await stopEntry(entry);
|
|
2433
3000
|
throw err;
|
|
2434
3001
|
}
|
|
2435
3002
|
return entry;
|
|
@@ -2444,591 +3011,272 @@ function unregisterIntegration(accountId) {
|
|
|
2444
3011
|
});
|
|
2445
3012
|
}
|
|
2446
3013
|
async function stopEntry(entry) {
|
|
2447
|
-
entry.invoker?.stop();
|
|
2448
|
-
entry.texts?.stop();
|
|
2449
3014
|
try {
|
|
2450
|
-
await entry.
|
|
3015
|
+
await entry.loop?.stop();
|
|
2451
3016
|
} catch (err) {
|
|
2452
|
-
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "
|
|
3017
|
+
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "receive loop stop threw during unregister");
|
|
2453
3018
|
}
|
|
3019
|
+
if (!entry.loop) {
|
|
3020
|
+
try {
|
|
3021
|
+
entry.socket.realtime.disconnect();
|
|
3022
|
+
} catch {
|
|
3023
|
+
}
|
|
3024
|
+
}
|
|
3025
|
+
entry.socket.stopped();
|
|
3026
|
+
entry.textsCache?.stop();
|
|
2454
3027
|
}
|
|
2455
3028
|
function getIntegration(accountId) {
|
|
2456
3029
|
return registry.get(accountId);
|
|
2457
3030
|
}
|
|
3031
|
+
function listActiveAccounts() {
|
|
3032
|
+
return [...registry.keys()];
|
|
3033
|
+
}
|
|
2458
3034
|
|
|
2459
|
-
// src/integration/
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
timer = null;
|
|
2471
|
-
burstStartedAt = null;
|
|
2472
|
-
delayed = null;
|
|
2473
|
-
delayedDeadline = null;
|
|
2474
|
-
stopped = false;
|
|
2475
|
-
wakes = 0;
|
|
2476
|
-
absorbed = 0;
|
|
2477
|
-
fires = 0;
|
|
2478
|
-
constructor(options) {
|
|
2479
|
-
const debounce = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
|
|
2480
|
-
if (!(debounce >= 0)) throw new RangeError("debounceMs must be >= 0");
|
|
2481
|
-
const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS;
|
|
2482
|
-
if (!(maxWindow >= debounce)) throw new RangeError("maxWindowMs must be >= debounceMs");
|
|
2483
|
-
this.onFire = options.onFire;
|
|
2484
|
-
this.onDelayedWake = options.onDelayedWake;
|
|
2485
|
-
this.debounceMs = debounce;
|
|
2486
|
-
this.maxWindowMs = maxWindow;
|
|
2487
|
-
this.now = options.now ?? Date.now;
|
|
2488
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
2489
|
-
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
2490
|
-
}
|
|
2491
|
-
/** True while a debounce timer is armed. */
|
|
2492
|
-
get armed() {
|
|
2493
|
-
return this.timer !== null;
|
|
2494
|
-
}
|
|
2495
|
-
/** True while a retry wake is scheduled and has not fired. */
|
|
2496
|
-
get delayedPending() {
|
|
2497
|
-
return this.delayed !== null;
|
|
2498
|
-
}
|
|
2499
|
-
/**
|
|
2500
|
-
* A wake. The first one of a burst arms the window; every later one is
|
|
2501
|
-
* absorbed and restarts it (trailing edge), never past the burst's cap.
|
|
2502
|
-
*/
|
|
2503
|
-
wake() {
|
|
2504
|
-
if (this.stopped) return;
|
|
2505
|
-
this.wakes += 1;
|
|
2506
|
-
const now = this.now();
|
|
2507
|
-
if (this.timer === null) {
|
|
2508
|
-
this.burstStartedAt = now;
|
|
2509
|
-
this.timer = this._setTimeout(() => this.fire(), this.debounceMs);
|
|
2510
|
-
return;
|
|
2511
|
-
}
|
|
2512
|
-
this.absorbed += 1;
|
|
2513
|
-
const capAt = (this.burstStartedAt ?? now) + this.maxWindowMs;
|
|
2514
|
-
const delay = Math.max(0, Math.min(this.debounceMs, capAt - now));
|
|
2515
|
-
this._clearTimeout(this.timer);
|
|
2516
|
-
this.timer = this._setTimeout(() => this.fire(), delay);
|
|
2517
|
-
}
|
|
2518
|
-
/** A delayed wake (retry ladder). The sooner pending deadline is kept. */
|
|
2519
|
-
wakeAfter(delayMs) {
|
|
2520
|
-
if (this.stopped) return;
|
|
2521
|
-
const delay = Math.max(0, delayMs);
|
|
2522
|
-
const deadline = this.now() + delay;
|
|
2523
|
-
if (this.delayed !== null) {
|
|
2524
|
-
if (this.delayedDeadline !== null && this.delayedDeadline <= deadline) {
|
|
2525
|
-
return;
|
|
2526
|
-
}
|
|
2527
|
-
this._clearTimeout(this.delayed);
|
|
2528
|
-
}
|
|
2529
|
-
this.delayedDeadline = deadline;
|
|
2530
|
-
this.delayed = this._setTimeout(() => {
|
|
2531
|
-
this.delayed = null;
|
|
2532
|
-
this.delayedDeadline = null;
|
|
2533
|
-
if (this.stopped) return;
|
|
2534
|
-
try {
|
|
2535
|
-
this.onDelayedWake?.();
|
|
2536
|
-
} catch {
|
|
2537
|
-
}
|
|
2538
|
-
this.wake();
|
|
2539
|
-
}, delay);
|
|
2540
|
-
}
|
|
2541
|
-
/** Cancel everything; later wakes are ignored. */
|
|
2542
|
-
stop() {
|
|
2543
|
-
this.stopped = true;
|
|
2544
|
-
if (this.timer !== null) {
|
|
2545
|
-
this._clearTimeout(this.timer);
|
|
2546
|
-
this.timer = null;
|
|
2547
|
-
this.burstStartedAt = null;
|
|
2548
|
-
}
|
|
2549
|
-
if (this.delayed !== null) {
|
|
2550
|
-
this._clearTimeout(this.delayed);
|
|
2551
|
-
this.delayed = null;
|
|
2552
|
-
this.delayedDeadline = null;
|
|
2553
|
-
}
|
|
2554
|
-
}
|
|
2555
|
-
fire() {
|
|
2556
|
-
this.timer = null;
|
|
2557
|
-
this.burstStartedAt = null;
|
|
2558
|
-
if (this.stopped) return;
|
|
2559
|
-
this.fires += 1;
|
|
2560
|
-
try {
|
|
2561
|
-
this.onFire();
|
|
2562
|
-
} catch {
|
|
3035
|
+
// src/integration/turns.ts
|
|
3036
|
+
function createLoopTurnStarter(options) {
|
|
3037
|
+
const now = options.now ?? Date.now;
|
|
3038
|
+
return async (request) => {
|
|
3039
|
+
const id = request.kind === "reply" ? request.conversationId : request.invite.invite_id;
|
|
3040
|
+
const sessionKey = request.kind === "reply" ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now());
|
|
3041
|
+
const watch = options.turns.admission(request.kind, id);
|
|
3042
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
3043
|
+
if (!admission.ran) {
|
|
3044
|
+
options.turns.admitted(watch);
|
|
3045
|
+
return { started: false, error: admission.error };
|
|
2563
3046
|
}
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
readiness;
|
|
2580
|
-
gateEnabled;
|
|
2581
|
-
ladder;
|
|
2582
|
-
now;
|
|
2583
|
-
coalescer;
|
|
2584
|
-
cycleDue = false;
|
|
2585
|
-
running = null;
|
|
2586
|
-
stopped = false;
|
|
2587
|
-
pendingInvites = [];
|
|
2588
|
-
invitesDirty = false;
|
|
2589
|
-
retryRung = 0;
|
|
2590
|
-
turnsInFlight = 0;
|
|
2591
|
-
/**
|
|
2592
|
-
* Conversations whose reply turn is running. Their verdict is recorded
|
|
2593
|
-
* only when the turn completes, so the card stays on the tray meanwhile
|
|
2594
|
-
* and every wake in between would re-gate it and queue a second turn.
|
|
2595
|
-
* Such cards are left out of the cycle; once the turn ends the tray is
|
|
2596
|
-
* read again if any were.
|
|
2597
|
-
*/
|
|
2598
|
-
replyTurnsInFlight = /* @__PURE__ */ new Set();
|
|
2599
|
-
skippedWhileInFlight = false;
|
|
2600
|
-
/** The reason the tools were last found unavailable; logged when it changes, not per wake. */
|
|
2601
|
-
unreadyReason = null;
|
|
2602
|
-
cycles = 0;
|
|
2603
|
-
turns = 0;
|
|
2604
|
-
inviteTurns = 0;
|
|
2605
|
-
constructor(options) {
|
|
2606
|
-
this.accountId = options.accountId;
|
|
2607
|
-
this.agentId = options.agentId;
|
|
2608
|
-
this.client = options.client;
|
|
2609
|
-
this.callModel = options.callModel;
|
|
2610
|
-
this.startTurn = options.startTurn;
|
|
2611
|
-
this.texts = options.texts;
|
|
2612
|
-
this.invites = options.invites;
|
|
2613
|
-
this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
2614
|
-
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2615
|
-
this.readiness = options.readiness ?? (() => ({ ready: true }));
|
|
2616
|
-
this.gateEnabled = options.gateEnabled ?? true;
|
|
2617
|
-
this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
|
|
2618
|
-
this.now = options.now ?? Date.now;
|
|
2619
|
-
this.coalescer = new WakeCoalescer({
|
|
2620
|
-
onFire: () => this.onWakeFired(),
|
|
2621
|
-
onDelayedWake: () => {
|
|
2622
|
-
this.logger.debug({ source: "retry" }, "wake");
|
|
2623
|
-
this.metrics.incWake({ source: "retry" });
|
|
2624
|
-
},
|
|
2625
|
-
debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,
|
|
2626
|
-
now: this.now,
|
|
2627
|
-
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
2628
|
-
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
|
|
2629
|
-
});
|
|
2630
|
-
}
|
|
2631
|
-
// ─── wakes ──────────────────────────────────────────────────────────
|
|
2632
|
-
/** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
|
|
2633
|
-
wake(source) {
|
|
2634
|
-
if (this.stopped) return;
|
|
2635
|
-
this.logger.debug({ source }, "wake");
|
|
2636
|
-
this.coalescer.wake();
|
|
2637
|
-
}
|
|
2638
|
-
/**
|
|
2639
|
-
* The second wake kind. An invite already offered (this process or an
|
|
2640
|
-
* earlier one, per the ledger) or already pending is ignored, so an
|
|
2641
|
-
* invite seen live and again on a connect-time catch-up is decided once.
|
|
2642
|
-
* Returns true when newly queued.
|
|
2643
|
-
*/
|
|
2644
|
-
groupInvite(invite, source) {
|
|
2645
|
-
if (this.stopped) return false;
|
|
2646
|
-
if (this.invites.isOffered(invite.inviteId)) return false;
|
|
2647
|
-
if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false;
|
|
2648
|
-
this.logger.info(
|
|
2649
|
-
{ groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },
|
|
2650
|
-
"group invite \u2014 queuing one invite turn"
|
|
3047
|
+
options.turns.started({
|
|
3048
|
+
runId: admission.runId,
|
|
3049
|
+
kind: request.kind,
|
|
3050
|
+
id,
|
|
3051
|
+
anchor: request.kind === "reply" ? request.anchor : null,
|
|
3052
|
+
sessionKey: admission.sessionKey,
|
|
3053
|
+
startedAt: now(),
|
|
3054
|
+
owner: options.owner,
|
|
3055
|
+
// What the after-turn rule compares when the turn ends outside the
|
|
3056
|
+
// kit's watch (handed off, or after a restart).
|
|
3057
|
+
...request.kind === "reply" ? { card: request.card, category: request.category } : { invite: request.invite }
|
|
3058
|
+
}, { admission: watch });
|
|
3059
|
+
options.logger.info(
|
|
3060
|
+
{ kind: request.kind, sessionKey, runId: admission.runId, ...request.kind === "reply" ? { conversationId: id } : { inviteId: id } },
|
|
3061
|
+
request.kind === "reply" ? "turn start" : "group-invite turn start"
|
|
2651
3062
|
);
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
}
|
|
2657
|
-
/** Cancel timers; a cycle in flight finishes on its own. */
|
|
2658
|
-
stop() {
|
|
2659
|
-
this.stopped = true;
|
|
2660
|
-
this.coalescer.stop();
|
|
2661
|
-
}
|
|
2662
|
-
/** The promise of the work currently running, for tests and for graceful stops. */
|
|
2663
|
-
settled() {
|
|
2664
|
-
return this.running ?? Promise.resolve();
|
|
2665
|
-
}
|
|
2666
|
-
counters() {
|
|
2667
|
-
return {
|
|
2668
|
-
cycles: this.cycles,
|
|
2669
|
-
turns: this.turns,
|
|
2670
|
-
inviteTurns: this.inviteTurns,
|
|
2671
|
-
turnsInFlight: this.turnsInFlight,
|
|
2672
|
-
wakes: this.coalescer.wakes,
|
|
2673
|
-
absorbed: this.coalescer.absorbed,
|
|
2674
|
-
retryRung: this.retryRung,
|
|
2675
|
-
pendingInvites: this.pendingInvites.length
|
|
2676
|
-
};
|
|
2677
|
-
}
|
|
2678
|
-
// ─── worker ─────────────────────────────────────────────────────────
|
|
2679
|
-
onWakeFired() {
|
|
2680
|
-
this.cycleDue = true;
|
|
2681
|
-
if (this.pendingInvites.length > 0) this.invitesDirty = true;
|
|
2682
|
-
this.schedule();
|
|
2683
|
-
}
|
|
2684
|
-
/** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
|
|
2685
|
-
schedule() {
|
|
2686
|
-
if (this.running) return;
|
|
2687
|
-
this.running = this.drain().finally(() => {
|
|
2688
|
-
this.running = null;
|
|
2689
|
-
if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule();
|
|
2690
|
-
});
|
|
2691
|
-
}
|
|
2692
|
-
async drain() {
|
|
2693
|
-
while (!this.stopped) {
|
|
2694
|
-
if (this.invitesDirty) {
|
|
2695
|
-
this.invitesDirty = false;
|
|
2696
|
-
await this.runInviteTurns();
|
|
2697
|
-
continue;
|
|
2698
|
-
}
|
|
2699
|
-
if (this.cycleDue) {
|
|
2700
|
-
this.cycleDue = false;
|
|
2701
|
-
try {
|
|
2702
|
-
await this.runCycle();
|
|
2703
|
-
} catch (err) {
|
|
2704
|
-
this.logger.error({ err: describe4(err), ...this.retry() }, "cycle failed with an unhandled error \u2014 re-waking later");
|
|
2705
|
-
}
|
|
2706
|
-
continue;
|
|
3063
|
+
const done = admission.done.then((outcome) => {
|
|
3064
|
+
if (outcome.status === "gone") {
|
|
3065
|
+
options.logger.warn({ sessionKey, runId: outcome.runId }, "turn end not confirmed: the plugin runtime is gone \u2014 its card stays held");
|
|
3066
|
+
return { status: "still_running", detail: "the plugin runtime is gone" };
|
|
2707
3067
|
}
|
|
2708
|
-
|
|
3068
|
+
const end = turnEndOf(outcome);
|
|
3069
|
+
void options.turns.ended(admission.runId, end);
|
|
3070
|
+
options.logger[outcome.status === "ok" ? "info" : "warn"](
|
|
3071
|
+
{
|
|
3072
|
+
sessionKey,
|
|
3073
|
+
runId: outcome.runId,
|
|
3074
|
+
status: outcome.status,
|
|
3075
|
+
...outcome.error ? { error: outcome.error } : {},
|
|
3076
|
+
...outcome.elapsedMs !== void 0 ? { elapsedMs: outcome.elapsedMs } : {},
|
|
3077
|
+
agentchatCalls: outcome.agentchatCalls ?? null
|
|
3078
|
+
},
|
|
3079
|
+
request.kind === "reply" ? "turn ended (final text discarded; the send is a hosted-tool call)" : "group-invite turn ended"
|
|
3080
|
+
);
|
|
3081
|
+
return end;
|
|
3082
|
+
});
|
|
3083
|
+
return { started: true, done };
|
|
3084
|
+
};
|
|
3085
|
+
}
|
|
3086
|
+
function turnEndOf(outcome) {
|
|
3087
|
+
const agentchatCalls = outcome.agentchatCalls ?? null;
|
|
3088
|
+
if (outcome.status === "ok" && !outcome.error) return { status: "completed", agentchatCalls };
|
|
3089
|
+
return { status: "failed", agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? "unknown"}` };
|
|
3090
|
+
}
|
|
3091
|
+
|
|
3092
|
+
// src/integration/loop.ts
|
|
3093
|
+
var generation = 0;
|
|
3094
|
+
function createIntegrationLoop(options) {
|
|
3095
|
+
const logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
3096
|
+
const metrics = options.metrics ?? createNoopMetrics();
|
|
3097
|
+
const now = options.now ?? Date.now;
|
|
3098
|
+
generation += 1;
|
|
3099
|
+
const owner = `${options.accountId}#${generation}`;
|
|
3100
|
+
const gateEnabled = options.gateEnabled ?? true;
|
|
3101
|
+
let unreadyReason = null;
|
|
3102
|
+
const readiness = options.readiness ? () => {
|
|
3103
|
+
const ready = options.readiness();
|
|
3104
|
+
if (ready.ready) {
|
|
3105
|
+
if (unreadyReason !== null) logger.info({}, "turns can start again \u2014 gating resumes");
|
|
3106
|
+
unreadyReason = null;
|
|
3107
|
+
return ready;
|
|
2709
3108
|
}
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
}
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
}
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
return { ...this.result("tools_unavailable", cards.length, truncated, started, readiness.reason), skippedInFlight };
|
|
2748
|
-
}
|
|
2749
|
-
if (this.unreadyReason !== null) {
|
|
2750
|
-
this.unreadyReason = null;
|
|
2751
|
-
this.logger.info({}, "AgentChat tools available to turns again");
|
|
2752
|
-
}
|
|
2753
|
-
let result;
|
|
2754
|
-
if (!this.gateEnabled) {
|
|
2755
|
-
result = await this.runUngated(cards.length, texts, truncated, started);
|
|
2756
|
-
} else {
|
|
2757
|
-
const trayToGate = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray;
|
|
2758
|
-
result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight);
|
|
2759
|
-
}
|
|
2760
|
-
if (skippedInFlight > 0) result = { ...result, skippedInFlight };
|
|
2761
|
-
if (truncated && result.outcome !== "fail_closed") {
|
|
2762
|
-
this.logger.info({}, "tray truncated \u2014 waking again for the rest");
|
|
2763
|
-
this.coalescer.wake();
|
|
2764
|
-
}
|
|
2765
|
-
return result;
|
|
2766
|
-
}
|
|
2767
|
-
/** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
|
|
2768
|
-
async runUngated(cards, texts, truncated, started) {
|
|
2769
|
-
this.logger.info({ cards }, "gate off \u2014 starting one turn with the served wake instruction");
|
|
2770
|
-
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2771
|
-
this.logger.info({ sessionKey }, "turn start");
|
|
2772
|
-
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2773
|
-
if (!admission.ran) {
|
|
2774
|
-
this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, "turn not started \u2014 re-waking later");
|
|
2775
|
-
} else {
|
|
2776
|
-
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
|
|
2777
|
-
this.retryRung = 0;
|
|
3109
|
+
if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, "not gating \u2014 no turn can start now; the cards wait on the tray");
|
|
3110
|
+
unreadyReason = ready.reason;
|
|
3111
|
+
return ready;
|
|
3112
|
+
} : void 0;
|
|
3113
|
+
const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now });
|
|
3114
|
+
const loop = new integration.ReceiveLoop({
|
|
3115
|
+
client: options.client,
|
|
3116
|
+
texts: options.texts,
|
|
3117
|
+
mode: gateEnabled ? "gateCall" : "singleRun",
|
|
3118
|
+
...gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) },
|
|
3119
|
+
socket: options.socket,
|
|
3120
|
+
...options.handle ? { handle: options.handle } : {},
|
|
3121
|
+
toolNamer: OPENCLAW_TOOL_NAMER,
|
|
3122
|
+
// One account's turns run on one OpenClaw lane anyway; one slot keeps
|
|
3123
|
+
// the rest held out of the gate (no second model call decides them).
|
|
3124
|
+
maxConcurrentTurns: 1,
|
|
3125
|
+
tracker: options.turns.tracker,
|
|
3126
|
+
...readiness ? { readiness } : {},
|
|
3127
|
+
...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {},
|
|
3128
|
+
...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
|
|
3129
|
+
...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
|
|
3130
|
+
now,
|
|
3131
|
+
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
3132
|
+
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {},
|
|
3133
|
+
onEvent: (event) => logEvent(event, logger, metrics)
|
|
3134
|
+
});
|
|
3135
|
+
const inLoopContext = AsyncLocalStorage.snapshot();
|
|
3136
|
+
options.turns.setLive(
|
|
3137
|
+
owner,
|
|
3138
|
+
() => inLoopContext(() => loop.wake()),
|
|
3139
|
+
(fn) => inLoopContext(fn)
|
|
3140
|
+
);
|
|
3141
|
+
return {
|
|
3142
|
+
loop,
|
|
3143
|
+
async stop() {
|
|
3144
|
+
options.turns.clearLive(owner);
|
|
3145
|
+
await loop.stop();
|
|
2778
3146
|
}
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
const latencyMs = this.now() - started;
|
|
2788
|
-
const counts = { reply: 0, dismiss: 0, defer: 0 };
|
|
2789
|
-
for (const verdict of decided.verdicts) counts[verdict.decision] += 1;
|
|
2790
|
-
if (decided.outcome === "fail_closed") {
|
|
2791
|
-
this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, "gate failed closed \u2014 nothing recorded, no turn started");
|
|
2792
|
-
return { ...this.result("fail_closed", cards, truncated, started, decided.failure), undecided: cards, latencyMs };
|
|
2793
|
-
}
|
|
2794
|
-
if (decided.outcome === "empty") {
|
|
2795
|
-
this.retryRung = 0;
|
|
2796
|
-
return this.result("empty", cards, truncated, started);
|
|
2797
|
-
}
|
|
2798
|
-
let turnsStarted = 0;
|
|
2799
|
-
let turnsRefused = 0;
|
|
2800
|
-
const recordFailures = decided.recordFailures.length;
|
|
2801
|
-
const recorded = decided.recorded;
|
|
2802
|
-
for (const entry of decided.reply) {
|
|
2803
|
-
if (this.replyTurnsInFlight.has(entry.conversationId)) {
|
|
2804
|
-
this.skippedWhileInFlight = true;
|
|
2805
|
-
continue;
|
|
2806
|
-
}
|
|
2807
|
-
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2808
|
-
this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
|
|
2809
|
-
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
|
|
2810
|
-
if (!admission.ran) {
|
|
2811
|
-
turnsRefused += 1;
|
|
2812
|
-
this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, "turn not started \u2014 reply not recorded; the conversation stays unread");
|
|
2813
|
-
continue;
|
|
2814
|
-
}
|
|
2815
|
-
turnsStarted += 1;
|
|
2816
|
-
this.replyTurnsInFlight.add(entry.conversationId);
|
|
2817
|
-
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)", entry);
|
|
2818
|
-
}
|
|
2819
|
-
const summary = {
|
|
2820
|
-
cards,
|
|
2821
|
-
reply: counts.reply,
|
|
2822
|
-
dismiss: counts.dismiss,
|
|
2823
|
-
defer: counts.defer,
|
|
2824
|
-
undecided: decided.undecided.length,
|
|
2825
|
-
recorded,
|
|
2826
|
-
recordFailures,
|
|
2827
|
-
turnsStarted,
|
|
2828
|
-
turnsRefused,
|
|
2829
|
-
skippedInFlight,
|
|
2830
|
-
latencyMs
|
|
2831
|
-
};
|
|
2832
|
-
if (turnsRefused > 0) {
|
|
2833
|
-
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 some turns were refused; re-waking later");
|
|
2834
|
-
} else if (recordFailures > 0 || decided.undecided.length > 0) {
|
|
2835
|
-
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 cards left on the tray; re-waking later");
|
|
2836
|
-
} else {
|
|
2837
|
-
this.retryRung = 0;
|
|
2838
|
-
this.logger.info(summary, "gate");
|
|
3147
|
+
};
|
|
3148
|
+
}
|
|
3149
|
+
function singleRunStarter(options, owner, logger, now) {
|
|
3150
|
+
return async (request) => {
|
|
3151
|
+
const hung = options.turns.hungSingleRun();
|
|
3152
|
+
if (hung) {
|
|
3153
|
+
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)");
|
|
3154
|
+
return { status: "not_started", detail: `the gate-off run ${hung.runId} is still going` };
|
|
2839
3155
|
}
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
return {
|
|
2844
|
-
|
|
2845
|
-
cards,
|
|
2846
|
-
reply: 0,
|
|
2847
|
-
dismiss: 0,
|
|
2848
|
-
defer: 0,
|
|
2849
|
-
undecided: 0,
|
|
2850
|
-
recorded: 0,
|
|
2851
|
-
recordFailures: 0,
|
|
2852
|
-
turnsStarted: 0,
|
|
2853
|
-
turnsRefused: 0,
|
|
2854
|
-
skippedInFlight: 0,
|
|
2855
|
-
truncated,
|
|
2856
|
-
latencyMs: this.now() - started,
|
|
2857
|
-
failure
|
|
3156
|
+
const sessionKey = wakeSessionKey(options.agentId, now());
|
|
3157
|
+
logger.info({ sessionKey, cards: request.cards, invites: request.invites }, "gate off \u2014 one run with the served wake instruction");
|
|
3158
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
3159
|
+
if (!admission.ran) return { status: "not_started", detail: admission.error };
|
|
3160
|
+
let letGo = () => {
|
|
2858
3161
|
};
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
3162
|
+
const handedOff = new Promise((resolve) => {
|
|
3163
|
+
letGo = () => resolve("let_go");
|
|
3164
|
+
});
|
|
3165
|
+
const { runId } = admission;
|
|
3166
|
+
options.turns.started({ runId, kind: "run", id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo });
|
|
3167
|
+
const ended = admission.done.then((outcome) => {
|
|
3168
|
+
if (outcome.status !== "gone") void options.turns.ended(runId);
|
|
3169
|
+
logger[outcome.status === "ok" ? "info" : "warn"]({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, "gate off \u2014 run ended");
|
|
3170
|
+
return outcome;
|
|
3171
|
+
});
|
|
3172
|
+
const first = await Promise.race([ended, handedOff]);
|
|
3173
|
+
if (first === "let_go") {
|
|
3174
|
+
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`)");
|
|
3175
|
+
return { status: "failed", detail: "the run was handed off while still going" };
|
|
2867
3176
|
}
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
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
|
-
this.replyTurnEnded(reply.conversationId);
|
|
3177
|
+
return first.status === "ok" && !first.error ? { status: "completed" } : { status: "failed", detail: first.error ?? `run ended: ${first.status ?? "unknown"}` };
|
|
3178
|
+
};
|
|
3179
|
+
}
|
|
3180
|
+
function logEvent(event, logger, metrics) {
|
|
3181
|
+
switch (event.type) {
|
|
3182
|
+
case "wake":
|
|
3183
|
+
if (event.source === "message") metrics.incWake({ source: "message" });
|
|
3184
|
+
else if (event.source === "invite") metrics.incWake({ source: "invite" });
|
|
3185
|
+
logger.debug({ source: event.source, ...event.conversationId ? { conversationId: event.conversationId } : {} }, "wake");
|
|
3186
|
+
return;
|
|
3187
|
+
case "echo":
|
|
3188
|
+
logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
|
|
3189
|
+
return;
|
|
3190
|
+
case "cycle": {
|
|
3191
|
+
const s = event.summary;
|
|
3192
|
+
const fields = {
|
|
3193
|
+
outcome: s.outcome,
|
|
3194
|
+
cards: s.cards,
|
|
3195
|
+
invites: s.invites,
|
|
3196
|
+
reply: s.reply,
|
|
3197
|
+
dismiss: s.dismiss,
|
|
3198
|
+
defer: s.defer,
|
|
3199
|
+
undecided: s.undecided,
|
|
3200
|
+
recordFailures: s.recordFailures,
|
|
3201
|
+
turnsStarted: s.turnsStarted,
|
|
3202
|
+
turnsRefused: s.turnsRefused,
|
|
3203
|
+
heldByTurns: s.heldByTurns,
|
|
3204
|
+
...s.truncated ? { truncated: true } : {},
|
|
3205
|
+
...s.failure ? { failure: s.failure } : {}
|
|
3206
|
+
};
|
|
3207
|
+
switch (s.outcome) {
|
|
3208
|
+
case "empty":
|
|
3209
|
+
logger.info({}, "tray empty \u2014 nothing to decide");
|
|
3210
|
+
return;
|
|
3211
|
+
case "nothing_owed":
|
|
3212
|
+
logger.info(fields, "nothing new to decide (muted cards, or cards a running turn holds)");
|
|
3213
|
+
return;
|
|
3214
|
+
case "fail_closed":
|
|
3215
|
+
logger.warn(fields, "gate failed closed \u2014 nothing recorded, no turn started; the server re-wakes");
|
|
3216
|
+
return;
|
|
3217
|
+
case "tray_failed":
|
|
3218
|
+
logger.warn(fields, "tray read failed \u2014 the cards stay on the tray; the server re-wakes");
|
|
3219
|
+
return;
|
|
3220
|
+
case "texts_missing":
|
|
3221
|
+
logger.warn(fields, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
3222
|
+
return;
|
|
3223
|
+
case "tools_unavailable":
|
|
3224
|
+
logger.debug(fields, "not gating \u2014 no turn can start now");
|
|
3225
|
+
return;
|
|
3226
|
+
case "abandoned":
|
|
3227
|
+
logger.warn(fields, "cycle abandoned \u2014 it ran past its deadline; nothing more is done for it, the next wake starts a new one");
|
|
3228
|
+
return;
|
|
3229
|
+
default: {
|
|
3230
|
+
const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0;
|
|
3231
|
+
logger[incomplete ? "warn" : "info"](fields, incomplete ? "gate \u2014 some cards were left on the tray; the server re-wakes" : "gate");
|
|
3232
|
+
return;
|
|
2925
3233
|
}
|
|
2926
3234
|
}
|
|
2927
|
-
);
|
|
2928
|
-
}
|
|
2929
|
-
/** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
|
|
2930
|
-
replyTurnEnded(conversationId) {
|
|
2931
|
-
this.replyTurnsInFlight.delete(conversationId);
|
|
2932
|
-
if (this.skippedWhileInFlight && !this.stopped) {
|
|
2933
|
-
this.skippedWhileInFlight = false;
|
|
2934
|
-
this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
|
|
2935
|
-
this.coalescer.wake();
|
|
2936
3235
|
}
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
async decidedInTurn(reply) {
|
|
2949
|
-
let tray;
|
|
2950
|
-
try {
|
|
2951
|
-
tray = await this.client.inbox.tray({ waitMs: 0, limit: POST_TURN_TRAY_LIMIT });
|
|
2952
|
-
} catch (err) {
|
|
2953
|
-
this.logger.info({ conversationId: reply.conversationId, err: describe4(err) }, "tray re-read after the turn failed \u2014 recording reply");
|
|
2954
|
-
return false;
|
|
2955
|
-
}
|
|
2956
|
-
const card = gate.cardsOf(tray).find((c) => c.conversation_id === reply.conversationId);
|
|
2957
|
-
if (!card) return tray.truncated !== true;
|
|
2958
|
-
return lastDecisionAt(card) !== lastDecisionAt(reply.card);
|
|
2959
|
-
}
|
|
2960
|
-
/** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
|
|
2961
|
-
async recordReply(sessionKey, reply) {
|
|
2962
|
-
try {
|
|
2963
|
-
await reply.record();
|
|
2964
|
-
this.logger.info({ sessionKey, conversationId: reply.conversationId }, "reply verdict recorded \u2014 turn completed");
|
|
2965
|
-
} catch (err) {
|
|
2966
|
-
this.logger.warn(
|
|
2967
|
-
{ sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
|
|
2968
|
-
"reply verdict not recorded after the turn completed \u2014 the conversation stays unread; the next wake gates it again"
|
|
3236
|
+
case "turn_started":
|
|
3237
|
+
return;
|
|
3238
|
+
// the turn starter logs it with the OpenClaw session and run
|
|
3239
|
+
case "turn_refused":
|
|
3240
|
+
logger.warn({ kind: event.kind, id: event.id, error: event.error }, "turn not started \u2014 nothing recorded; the card stays on the tray");
|
|
3241
|
+
return;
|
|
3242
|
+
case "turn_outcome": {
|
|
3243
|
+
const o = event.outcome;
|
|
3244
|
+
logger.info(
|
|
3245
|
+
{ conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...o.action !== "none" ? { through: o.throughMessageId } : {} },
|
|
3246
|
+
event.recorded ? `${o.action === "record_reply" ? "reply" : "dismiss"} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`
|
|
2969
3247
|
);
|
|
3248
|
+
return;
|
|
2970
3249
|
}
|
|
3250
|
+
case "invite_outcome":
|
|
3251
|
+
logger.info(
|
|
3252
|
+
{ inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },
|
|
3253
|
+
event.recorded ? "invite dismissed after a second silent turn (left pending)" : `nothing recorded for the invite (${event.outcome.reason})`
|
|
3254
|
+
);
|
|
3255
|
+
return;
|
|
3256
|
+
case "run":
|
|
3257
|
+
return;
|
|
3258
|
+
// single-run mode logs the run itself
|
|
3259
|
+
case "error":
|
|
3260
|
+
logger.debug({ err: event.error.message }, "receive loop notice");
|
|
3261
|
+
return;
|
|
2971
3262
|
}
|
|
2972
|
-
/**
|
|
2973
|
-
* Every pending invite gets one attempt. An invite leaves the pending list
|
|
2974
|
-
* only once its turn was admitted (and is then remembered in the ledger);
|
|
2975
|
-
* a refused one stays there for the next wake. Invites that arrive while
|
|
2976
|
-
* this runs are appended and get their pass on the next drain.
|
|
2977
|
-
*/
|
|
2978
|
-
async runInviteTurns() {
|
|
2979
|
-
const batch = [...this.pendingInvites];
|
|
2980
|
-
if (batch.length > 0) {
|
|
2981
|
-
const readiness = this.readiness();
|
|
2982
|
-
if (!readiness.ready) {
|
|
2983
|
-
const changed = this.unreadyReason !== readiness.reason;
|
|
2984
|
-
this.unreadyReason = readiness.reason;
|
|
2985
|
-
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");
|
|
2986
|
-
return;
|
|
2987
|
-
}
|
|
2988
|
-
}
|
|
2989
|
-
let texts = null;
|
|
2990
|
-
let refused = 0;
|
|
2991
|
-
let waitingForTexts = 0;
|
|
2992
|
-
for (const invite of batch) {
|
|
2993
|
-
if (this.stopped) return;
|
|
2994
|
-
texts ??= await this.texts.ensure();
|
|
2995
|
-
if (!texts) {
|
|
2996
|
-
waitingForTexts = batch.length;
|
|
2997
|
-
break;
|
|
2998
|
-
}
|
|
2999
|
-
const sessionKey = inviteSessionKey(this.agentId, invite.inviteId);
|
|
3000
|
-
this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, "group-invite turn start");
|
|
3001
|
-
let admission;
|
|
3002
|
-
try {
|
|
3003
|
-
admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
3004
|
-
} catch (err) {
|
|
3005
|
-
admission = { ran: false, error: describe4(err) };
|
|
3006
|
-
}
|
|
3007
|
-
if (!admission.ran) {
|
|
3008
|
-
refused += 1;
|
|
3009
|
-
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");
|
|
3010
|
-
continue;
|
|
3011
|
-
}
|
|
3012
|
-
this.inviteTurns += 1;
|
|
3013
|
-
this.invites.markOffered(invite.inviteId);
|
|
3014
|
-
this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId);
|
|
3015
|
-
this.admitted(sessionKey, admission, "group-invite turn complete");
|
|
3016
|
-
}
|
|
3017
|
-
if (this.stopped) return;
|
|
3018
|
-
if (waitingForTexts > 0) {
|
|
3019
|
-
this.logger.warn({ pending: waitingForTexts, ...this.retry() }, "served texts not available \u2014 invite turns wait; re-waking later");
|
|
3020
|
-
} else if (refused > 0) {
|
|
3021
|
-
this.logger.warn({ pending: refused, ...this.retry() }, "invite turns refused \u2014 re-waking later");
|
|
3022
|
-
}
|
|
3023
|
-
}
|
|
3024
|
-
};
|
|
3025
|
-
var POST_TURN_TRAY_LIMIT = 50;
|
|
3026
|
-
function lastDecisionAt(card) {
|
|
3027
|
-
const at = card.your_last_decision?.at;
|
|
3028
|
-
return typeof at === "string" && at.length > 0 ? at : null;
|
|
3029
3263
|
}
|
|
3030
|
-
|
|
3031
|
-
|
|
3264
|
+
var TROUBLE_OUTCOMES = /* @__PURE__ */ new Set(["fail_closed", "tools_unavailable", "texts_missing", "abandoned"]);
|
|
3265
|
+
var CYCLE_TROUBLE_RUN = 3;
|
|
3266
|
+
var TROUBLE_MEANING = {
|
|
3267
|
+
fail_closed: "the gate call failed (model unreachable, too slow, or nothing usable)",
|
|
3268
|
+
tools_unavailable: "no turn could have the hosted tools",
|
|
3269
|
+
texts_missing: "the served texts are not available",
|
|
3270
|
+
abandoned: "the cycle ran past its deadline and was abandoned"
|
|
3271
|
+
};
|
|
3272
|
+
function cycleTroubleLine(recentCycles) {
|
|
3273
|
+
let run = 0;
|
|
3274
|
+
for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i].outcome); i -= 1) run += 1;
|
|
3275
|
+
if (run < CYCLE_TROUBLE_RUN) return null;
|
|
3276
|
+
const last = recentCycles[recentCycles.length - 1];
|
|
3277
|
+
const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))];
|
|
3278
|
+
const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join("; ");
|
|
3279
|
+
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`;
|
|
3032
3280
|
}
|
|
3033
3281
|
function adaptLog(log) {
|
|
3034
3282
|
if (!log) return void 0;
|
|
@@ -3061,6 +3309,32 @@ async function waitUntilAbort(signal, onAbort) {
|
|
|
3061
3309
|
}
|
|
3062
3310
|
await onAbort();
|
|
3063
3311
|
}
|
|
3312
|
+
var mcpUpdateWarned = /* @__PURE__ */ new Set();
|
|
3313
|
+
async function updateHostedMcpEntry(ctx, apiBase, apiKey, runtime = getPluginRuntime) {
|
|
3314
|
+
const prefix = `[agentchat:${ctx.accountId}]`;
|
|
3315
|
+
const warnOnce = (line) => {
|
|
3316
|
+
if (mcpUpdateWarned.has(ctx.accountId)) return;
|
|
3317
|
+
mcpUpdateWarned.add(ctx.accountId);
|
|
3318
|
+
ctx.log?.warn?.(`${prefix} ${line}`);
|
|
3319
|
+
};
|
|
3320
|
+
try {
|
|
3321
|
+
const { cfg: liveCfg } = readLiveConfig(ctx.cfg, runtime);
|
|
3322
|
+
const config = runtime()?.config;
|
|
3323
|
+
const result = await refreshHostedMcpEntry({ liveCfg, config, apiBase, apiKey });
|
|
3324
|
+
if (result.outcome === "updated") {
|
|
3325
|
+
mcpUpdateWarned.delete(ctx.accountId);
|
|
3326
|
+
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`);
|
|
3327
|
+
} else if (result.outcome === "unsupported") {
|
|
3328
|
+
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\``);
|
|
3329
|
+
} else if (result.outcome === "failed") {
|
|
3330
|
+
warnOnce(
|
|
3331
|
+
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\``
|
|
3332
|
+
);
|
|
3333
|
+
}
|
|
3334
|
+
} catch (err) {
|
|
3335
|
+
warnOnce(`mcp.servers.agentchat check failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
3336
|
+
}
|
|
3337
|
+
}
|
|
3064
3338
|
var agentchatGatewayAdapter = {
|
|
3065
3339
|
async startAccount(ctx) {
|
|
3066
3340
|
const account = ctx.account;
|
|
@@ -3075,6 +3349,7 @@ var agentchatGatewayAdapter = {
|
|
|
3075
3349
|
const config = account.config;
|
|
3076
3350
|
const logger = adaptLog(ctx.log) ?? createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys });
|
|
3077
3351
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, "starting"));
|
|
3352
|
+
void updateHostedMcpEntry(ctx, config.apiBase, config.apiKey);
|
|
3078
3353
|
const wakeMode = readWakeModeFromEnv();
|
|
3079
3354
|
if (wakeMode.mode === "off") {
|
|
3080
3355
|
ctx.log?.info?.(
|
|
@@ -3086,7 +3361,7 @@ var agentchatGatewayAdapter = {
|
|
|
3086
3361
|
}
|
|
3087
3362
|
if (readLegacyReplyGateFailOpenFromEnv()) {
|
|
3088
3363
|
ctx.log?.warn?.(
|
|
3089
|
-
`[agentchat:${ctx.accountId}] ${LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured \u2014 a gate that cannot run fails closed (nothing recorded, no turn)
|
|
3364
|
+
`[agentchat:${ctx.accountId}] ${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`
|
|
3090
3365
|
);
|
|
3091
3366
|
}
|
|
3092
3367
|
const refusal = multiAccountRefusal(ctx.cfg);
|
|
@@ -3108,20 +3383,57 @@ var agentchatGatewayAdapter = {
|
|
|
3108
3383
|
}
|
|
3109
3384
|
const client = getClient({ accountId: ctx.accountId, config });
|
|
3110
3385
|
const gateTimeoutMs = readReplyGateTimeoutMsFromEnv();
|
|
3111
|
-
const
|
|
3386
|
+
const overdueWarned = /* @__PURE__ */ new Map();
|
|
3387
|
+
const turns = accountTurns(ctx.accountId);
|
|
3388
|
+
const reportOverdue = (runId, kind, id, elapsedMs, handed) => {
|
|
3389
|
+
const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS);
|
|
3390
|
+
if (!handed && overdueWarned.get(runId) === mark) return;
|
|
3391
|
+
overdueWarned.set(runId, mark);
|
|
3392
|
+
ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`);
|
|
3393
|
+
};
|
|
3394
|
+
const onStillRunning = ({ runId, sessionKey, elapsedMs }) => {
|
|
3395
|
+
const run = turns.run(runId);
|
|
3396
|
+
if (turns.stateOf(runId) === "released") {
|
|
3397
|
+
logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4) }, "released turn still running in OpenClaw \u2014 it holds nothing");
|
|
3398
|
+
return;
|
|
3399
|
+
}
|
|
3400
|
+
logger.info(
|
|
3401
|
+
{ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4), ...run ? { [run.kind === "reply" ? "conversationId" : run.kind === "invite" ? "inviteId" : "run"]: run.id } : {} },
|
|
3402
|
+
"turn still running \u2014 its conversation stays in flight until OpenClaw reports the run ended"
|
|
3403
|
+
);
|
|
3404
|
+
if (!run || !isOverdue(elapsedMs)) return;
|
|
3405
|
+
const handed = turns.handOff(runId) !== null;
|
|
3406
|
+
reportOverdue(runId, run.kind, run.id, elapsedMs, handed);
|
|
3407
|
+
};
|
|
3408
|
+
const watchRun = createRunWatcher({ onStillRunning });
|
|
3409
|
+
turns.configure({
|
|
3410
|
+
recorder: createAfterTurnRecorder({ client, logger }),
|
|
3411
|
+
store: new TurnStore(ctx.accountId),
|
|
3412
|
+
watch: async (record) => {
|
|
3413
|
+
const outcome = await watchRun(record);
|
|
3414
|
+
return outcome ? turnEndOf(outcome) : null;
|
|
3415
|
+
},
|
|
3416
|
+
readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),
|
|
3417
|
+
logger
|
|
3418
|
+
});
|
|
3419
|
+
turns.adopt();
|
|
3420
|
+
for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`);
|
|
3421
|
+
for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, "removed a file an earlier release kept (no longer used)");
|
|
3422
|
+
const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger });
|
|
3423
|
+
const texts = new OpenClawTexts(textsCache);
|
|
3424
|
+
const first = await textsCache.start();
|
|
3425
|
+
if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, "served texts in hand");
|
|
3426
|
+
else logger.warn({ err: textsCache.lastError }, "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 nothing is gated until the first copy arrives");
|
|
3112
3427
|
const handle = config.agentHandle;
|
|
3113
3428
|
if (handle) {
|
|
3114
|
-
|
|
3115
|
-
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
|
|
3429
|
+
const refresh = (copy) => {
|
|
3430
|
+
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(copy).identity_line);
|
|
3116
3431
|
if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
|
|
3117
3432
|
else if (refreshed.outcome === "failed") ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? "unknown error"}`);
|
|
3118
|
-
}
|
|
3433
|
+
};
|
|
3434
|
+
if (first) refresh(first);
|
|
3435
|
+
textsCache.onChange((copy) => refresh(copy));
|
|
3119
3436
|
}
|
|
3120
|
-
await texts.start();
|
|
3121
|
-
const invites = new InviteLedger({
|
|
3122
|
-
accountId: ctx.accountId,
|
|
3123
|
-
onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
|
|
3124
|
-
});
|
|
3125
3437
|
const metrics = createInMemoryMetrics();
|
|
3126
3438
|
await registerIntegration({
|
|
3127
3439
|
accountId: ctx.accountId,
|
|
@@ -3129,33 +3441,44 @@ var agentchatGatewayAdapter = {
|
|
|
3129
3441
|
logger,
|
|
3130
3442
|
socketOptions: { client, metrics },
|
|
3131
3443
|
build: (socket) => {
|
|
3132
|
-
const
|
|
3444
|
+
const loop = createIntegrationLoop({
|
|
3133
3445
|
accountId: ctx.accountId,
|
|
3134
3446
|
agentId,
|
|
3135
3447
|
client,
|
|
3448
|
+
texts,
|
|
3449
|
+
socket: socket.realtime,
|
|
3450
|
+
handle: config.agentHandle,
|
|
3136
3451
|
callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
|
|
3137
|
-
|
|
3452
|
+
// A turn holds its conversation until OpenClaw confirms its run
|
|
3453
|
+
// ended; a wait that elapses is asked again (`integration/run.ts`).
|
|
3454
|
+
startRun: createRuntimeTurnStarter({
|
|
3455
|
+
onStillRunning,
|
|
3456
|
+
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")
|
|
3457
|
+
}),
|
|
3138
3458
|
// Gating waits until a turn can have the hosted tools (the MCP
|
|
3139
3459
|
// entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
|
|
3140
3460
|
// its key in this process): a connect wake on a cold gateway
|
|
3141
3461
|
// otherwise spends a gate call and runs a turn that cannot look.
|
|
3142
3462
|
readiness: () => {
|
|
3143
3463
|
const live = readLiveConfig(ctx.cfg);
|
|
3464
|
+
const hung = hungTurnsReason(turns, live.cfg);
|
|
3465
|
+
if (hung) return { ready: false, reason: hung };
|
|
3144
3466
|
return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
|
|
3145
3467
|
},
|
|
3146
|
-
|
|
3147
|
-
|
|
3468
|
+
// The account's runs outlive this loop: a config change restarts
|
|
3469
|
+
// the account while its runs go on in OpenClaw, so every loop for
|
|
3470
|
+
// the account shares the same turns (and the kit tracker in them).
|
|
3471
|
+
turns,
|
|
3148
3472
|
logger,
|
|
3149
3473
|
metrics,
|
|
3150
3474
|
gateEnabled: readReplyGateEnabledFromEnv()
|
|
3151
3475
|
});
|
|
3152
3476
|
let blocked = false;
|
|
3153
3477
|
return {
|
|
3154
|
-
|
|
3478
|
+
loop,
|
|
3155
3479
|
texts,
|
|
3480
|
+
textsCache,
|
|
3156
3481
|
handlers: {
|
|
3157
|
-
onWake: (source) => invoker.wake(source),
|
|
3158
|
-
onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
|
|
3159
3482
|
onConnected: (at) => {
|
|
3160
3483
|
if (blocked) {
|
|
3161
3484
|
blocked = false;
|
|
@@ -3163,7 +3486,6 @@ var agentchatGatewayAdapter = {
|
|
|
3163
3486
|
}
|
|
3164
3487
|
ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
|
|
3165
3488
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: "linked", lastConnectedAt: at }, "ready"));
|
|
3166
|
-
void catchUpInvites(ctx.accountId, client, invoker, logger);
|
|
3167
3489
|
},
|
|
3168
3490
|
onBlocked: (info) => {
|
|
3169
3491
|
const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
|
|
@@ -3219,23 +3541,6 @@ var agentchatGatewayAdapter = {
|
|
|
3219
3541
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
|
|
3220
3542
|
}
|
|
3221
3543
|
};
|
|
3222
|
-
async function catchUpInvites(accountId, client, invoker, logger) {
|
|
3223
|
-
try {
|
|
3224
|
-
const invites = await client.listGroupInvites();
|
|
3225
|
-
if (!Array.isArray(invites)) return;
|
|
3226
|
-
let surfaced = 0;
|
|
3227
|
-
for (const row of invites) {
|
|
3228
|
-
const invite = groupInviteFromRecord(row);
|
|
3229
|
-
if (invite && invoker.groupInvite(invite, "catch-up")) surfaced += 1;
|
|
3230
|
-
}
|
|
3231
|
-
if (surfaced > 0) logger.info({ accountId, surfaced }, "pending group invites surfaced on connect");
|
|
3232
|
-
} catch (err) {
|
|
3233
|
-
logger.warn(
|
|
3234
|
-
{ accountId, err: err instanceof Error ? err.message : String(err) },
|
|
3235
|
-
"pending-invite catch-up failed \u2014 live invite frames are unaffected and the agent can still list invites with the hosted tools"
|
|
3236
|
-
);
|
|
3237
|
-
}
|
|
3238
|
-
}
|
|
3239
3544
|
var PROBE_MIN_MS = 1e3;
|
|
3240
3545
|
var PROBE_MAX_MS = 1e4;
|
|
3241
3546
|
function formatCounts(counts) {
|
|
@@ -3277,15 +3582,27 @@ var agentchatStatusAdapter = {
|
|
|
3277
3582
|
const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
|
|
3278
3583
|
const live = getIntegration(account.accountId);
|
|
3279
3584
|
const health = live?.socket.getHealth();
|
|
3280
|
-
const
|
|
3281
|
-
const
|
|
3585
|
+
const loopStatus = live?.loop?.loop.status();
|
|
3586
|
+
const counters = loopStatus ? {
|
|
3587
|
+
wakes: loopStatus.coalescer.wakes,
|
|
3588
|
+
cycles: loopStatus.coalescer.cycles,
|
|
3589
|
+
turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted
|
|
3590
|
+
} : void 0;
|
|
3591
|
+
const turnsHere = live ? findAccountTurns(account.accountId) ?? null : null;
|
|
3592
|
+
const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null;
|
|
3593
|
+
const overdue = turnsHere ? [...hungReason ? [hungReason] : [], ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : [];
|
|
3594
|
+
const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null;
|
|
3595
|
+
const servedFrom = live?.texts?.source;
|
|
3596
|
+
const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
|
|
3282
3597
|
const socketCounters = live?.metrics?.snapshot?.();
|
|
3283
|
-
const
|
|
3598
|
+
const integration6 = {
|
|
3284
3599
|
mode: readWakeModeFromEnv().mode,
|
|
3285
3600
|
...health ? { state: health.state } : {},
|
|
3286
3601
|
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
3287
3602
|
...textsSource ? { texts: textsSource } : {},
|
|
3288
|
-
...socketCounters ? { socket: socketCounters } : {}
|
|
3603
|
+
...socketCounters ? { socket: socketCounters } : {},
|
|
3604
|
+
...overdue.length > 0 ? { overdue } : {},
|
|
3605
|
+
...trouble ? { trouble } : {}
|
|
3289
3606
|
};
|
|
3290
3607
|
const refusal = multiAccountRefusal(cfg);
|
|
3291
3608
|
return {
|
|
@@ -3295,7 +3612,7 @@ var agentchatStatusAdapter = {
|
|
|
3295
3612
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3296
3613
|
mcp,
|
|
3297
3614
|
placement,
|
|
3298
|
-
integration,
|
|
3615
|
+
integration: integration6,
|
|
3299
3616
|
...refusal ? { refusal } : {},
|
|
3300
3617
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3301
3618
|
};
|
|
@@ -3316,7 +3633,7 @@ var agentchatStatusAdapter = {
|
|
|
3316
3633
|
}
|
|
3317
3634
|
if (probe.mcp) lines.push({ text: probe.mcp.detail, tone: probe.mcp.ok ? "success" : "error" });
|
|
3318
3635
|
for (const check of probe.placement ?? []) {
|
|
3319
|
-
lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? "muted" : "warn" });
|
|
3636
|
+
lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok && !check.notice ? "muted" : "warn" });
|
|
3320
3637
|
}
|
|
3321
3638
|
if (probe.refusal) lines.push({ text: `integration not started \u2014 ${probe.refusal}`, tone: "error" });
|
|
3322
3639
|
if (probe.integration) {
|
|
@@ -3333,6 +3650,8 @@ var agentchatStatusAdapter = {
|
|
|
3333
3650
|
tone: "muted"
|
|
3334
3651
|
});
|
|
3335
3652
|
}
|
|
3653
|
+
if (d.trouble) lines.push({ text: d.trouble, tone: "warn" });
|
|
3654
|
+
for (const line of d.overdue ?? []) lines.push({ text: line, tone: "warn" });
|
|
3336
3655
|
if (d.texts === "missing") {
|
|
3337
3656
|
lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
|
|
3338
3657
|
} else if (d.texts === "cache") {
|
|
@@ -3364,8 +3683,8 @@ var agentchatDoctorAdapter = {
|
|
|
3364
3683
|
const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
|
|
3365
3684
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
3366
3685
|
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
|
|
3367
|
-
if (check.ok) continue;
|
|
3368
|
-
const fix = check.name === "mcp" ? ` (${doctorFixCommand} adds it)` : "";
|
|
3686
|
+
if (check.ok && !check.notice) continue;
|
|
3687
|
+
const fix = check.name === "mcp" && check.repair && !check.ok ? ` (${doctorFixCommand} adds it)` : "";
|
|
3369
3688
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`);
|
|
3370
3689
|
}
|
|
3371
3690
|
const bound = resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId);
|
|
@@ -3376,6 +3695,18 @@ var agentchatDoctorAdapter = {
|
|
|
3376
3695
|
);
|
|
3377
3696
|
}
|
|
3378
3697
|
}
|
|
3698
|
+
for (const accountId of listActiveAccounts()) {
|
|
3699
|
+
const status = getIntegration(accountId)?.loop?.loop.status();
|
|
3700
|
+
if (!status) continue;
|
|
3701
|
+
const turns = findAccountTurns(accountId);
|
|
3702
|
+
if (turns) {
|
|
3703
|
+
const hung = hungTurnsReason(turns, cfg);
|
|
3704
|
+
if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`);
|
|
3705
|
+
for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`);
|
|
3706
|
+
}
|
|
3707
|
+
const trouble = cycleTroubleLine(status.recentCycles ?? []);
|
|
3708
|
+
if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`);
|
|
3709
|
+
}
|
|
3379
3710
|
return warnings;
|
|
3380
3711
|
},
|
|
3381
3712
|
async repairConfig({ cfg }) {
|
|
@@ -3422,6 +3753,7 @@ var agentchatDoctorAdapter = {
|
|
|
3422
3753
|
const result = withHostedMcpEntry(next, apiBase, apiKey);
|
|
3423
3754
|
next = result.cfg;
|
|
3424
3755
|
if (result.outcome === "added") changes.push(`added mcp.servers.agentchat \u2192 ${apiBase}/mcp (bearer template on AGENTCHAT_API_KEY)`);
|
|
3756
|
+
if (result.outcome === "updated") changes.push(`updated mcp.servers.agentchat to name this client (${clientIdentityText()})`);
|
|
3425
3757
|
}
|
|
3426
3758
|
return { config: next, changes, ...warnings.length > 0 ? { warnings } : {} };
|
|
3427
3759
|
}
|
|
@@ -3448,9 +3780,9 @@ function resolveAgentchatAccount(cfg, accountId) {
|
|
|
3448
3780
|
var uiHints = {
|
|
3449
3781
|
apiKey: {
|
|
3450
3782
|
label: "AgentChat API key",
|
|
3451
|
-
placeholder: "
|
|
3783
|
+
placeholder: "ac_\u2026",
|
|
3452
3784
|
sensitive: true,
|
|
3453
|
-
help: "The setup wizard registers you via email OTP and mints a key, recovers a lost key (handle + email OTP), or accepts an existing
|
|
3785
|
+
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."
|
|
3454
3786
|
},
|
|
3455
3787
|
apiBase: {
|
|
3456
3788
|
label: "API base URL",
|
|
@@ -3661,8 +3993,14 @@ var agentchatPlugin = {
|
|
|
3661
3993
|
threads: false,
|
|
3662
3994
|
nativeCommands: false
|
|
3663
3995
|
},
|
|
3996
|
+
// OpenClaw matches a reload prefix as `path === prefix` or `path` starting
|
|
3997
|
+
// with `prefix.` (src/gateway/config-reload-plan.ts), so the prefix carries
|
|
3998
|
+
// no trailing dot: `channels.agentchat.` matched nothing, and every
|
|
3999
|
+
// channels.agentchat change restarted the gateway (2026.6.x–2026.8.x) or
|
|
4000
|
+
// reloaded the plugin (2026.11.x). With this one OpenClaw restarts just the
|
|
4001
|
+
// channel, after a running turn has ended.
|
|
3664
4002
|
reload: {
|
|
3665
|
-
configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}
|
|
4003
|
+
configPrefixes: [`channels.${AGENTCHAT_CHANNEL_ID}`]
|
|
3666
4004
|
},
|
|
3667
4005
|
configSchema: buildChannelConfigSchema(agentchatChannelConfigSchema, { uiHints }),
|
|
3668
4006
|
setupWizard: agentchatSetupWizard,
|
|
@@ -3670,9 +4008,9 @@ var agentchatPlugin = {
|
|
|
3670
4008
|
listAccountIds(cfg) {
|
|
3671
4009
|
const section = readChannelSection(cfg);
|
|
3672
4010
|
if (!section) return [];
|
|
3673
|
-
const { accounts } = section;
|
|
3674
|
-
if (
|
|
3675
|
-
const ids = Object.keys(
|
|
4011
|
+
const { accounts: accounts2 } = section;
|
|
4012
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
4013
|
+
const ids = Object.keys(accounts2);
|
|
3676
4014
|
if (ids.length > 0) return ids;
|
|
3677
4015
|
}
|
|
3678
4016
|
const hasFlatFields = typeof section.apiKey === "string" || typeof section.apiBase === "string" || typeof section.agentHandle === "string";
|
|
@@ -3712,9 +4050,9 @@ var agentchatPlugin = {
|
|
|
3712
4050
|
hasConfiguredState({ cfg }) {
|
|
3713
4051
|
const section = readChannelSection(cfg);
|
|
3714
4052
|
if (!section) return false;
|
|
3715
|
-
const { accounts } = section;
|
|
3716
|
-
if (
|
|
3717
|
-
for (const entry of Object.values(
|
|
4053
|
+
const { accounts: accounts2 } = section;
|
|
4054
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
4055
|
+
for (const entry of Object.values(accounts2)) {
|
|
3718
4056
|
if (entry && typeof entry === "object") {
|
|
3719
4057
|
const candidate = entry.apiKey;
|
|
3720
4058
|
if (isApiKeyPresent(candidate)) return true;
|
|
@@ -3758,7 +4096,15 @@ var agentchatChannelEntry = defineChannelPluginEntry({
|
|
|
3758
4096
|
// (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
|
|
3759
4097
|
// The integration reads `runtime.llm.complete` (the gate on the agent's own
|
|
3760
4098
|
// model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
|
|
3761
|
-
setRuntime: (runtime) => setPluginRuntime(runtime)
|
|
4099
|
+
setRuntime: (runtime) => setPluginRuntime(runtime),
|
|
4100
|
+
// `openclaw agentchat release <conversation_id>`: the CLI half is
|
|
4101
|
+
// registered for every CLI (parse-time metadata), the gateway half only
|
|
4102
|
+
// where the integration runs.
|
|
4103
|
+
registerCliMetadata: (api) => registerReleaseCli(api),
|
|
4104
|
+
registerFull: (api) => {
|
|
4105
|
+
registerReleaseGatewayMethod(api);
|
|
4106
|
+
registerRunObserver(api);
|
|
4107
|
+
}
|
|
3762
4108
|
});
|
|
3763
4109
|
var agentchatSetupEntry = defineSetupPluginEntry(agentchatPlugin);
|
|
3764
4110
|
|
|
@@ -3772,6 +4118,6 @@ function hasAgentChatConfiguredState(config) {
|
|
|
3772
4118
|
return true;
|
|
3773
4119
|
}
|
|
3774
4120
|
|
|
3775
|
-
export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError,
|
|
4121
|
+
export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, IntegrationSocket, MAX_HUNG_TURNS, MCP_SERVER_NAME, OPENCLAW_TOOL_NAMER, OpenClawTexts, accountTurns, agentchatChannelEntry, agentchatPlugin, agentchatSetupEntry, agentchatPlugin as agentchatSetupPlugin, assertApiKeyValid, createInMemoryMetrics, createIntegrationLoop, createLoopTurnStarter, createMetrics, createNoopMetrics, createTextsCache, agentchatChannelEntry as default, hasAgentChatConfiguredState, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, loadIdentityLine, mcpToolName, parseChannelConfig, probeHostedMcp, realtimeOptionsFor, recoverAgentStart, recoverAgentVerify, registerAgentStart, registerAgentVerify, spellTextsForOpenClaw, spellToolsForOpenClaw, trackerFor, turnEndOf, validateApiKey };
|
|
3776
4122
|
//# sourceMappingURL=index.js.map
|
|
3777
4123
|
//# sourceMappingURL=index.js.map
|