@agentchatme/openclaw 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -1
- package/README.md +35 -26
- package/RUNBOOK.md +49 -17
- package/SECURITY.md +6 -2
- package/dist/binding/agents-anchor.cjs +10 -43
- package/dist/binding/agents-anchor.cjs.map +1 -1
- package/dist/binding/agents-anchor.d.cts +14 -11
- package/dist/binding/agents-anchor.d.ts +14 -11
- package/dist/binding/agents-anchor.js +10 -43
- package/dist/binding/agents-anchor.js.map +1 -1
- package/dist/index.cjs +1569 -1337
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +668 -190
- package/dist/index.d.ts +668 -190
- package/dist/index.js +1568 -1337
- package/dist/index.js.map +1 -1
- package/dist/setup-entry-C9aFZx3n.d.cts +378 -0
- package/dist/setup-entry-C9aFZx3n.d.ts +378 -0
- package/dist/setup-entry.cjs +1557 -1329
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +1 -1
- package/dist/setup-entry.d.ts +1 -1
- package/dist/setup-entry.js +1564 -1336
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +3 -3
- package/skills/agentchat/SKILL.md +75 -79
- package/dist/setup-entry-Dh6dRH2F.d.cts +0 -754
- package/dist/setup-entry-Dh6dRH2F.d.ts +0 -754
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.0";
|
|
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 (recording it yourself with ${DECIDE_TOOL} is idempotent) \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,7 +387,6 @@ 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
|
}
|
|
@@ -521,67 +455,24 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
|
521
455
|
return { cfg: { ...cfg, mcp }, removed: true };
|
|
522
456
|
}
|
|
523
457
|
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;
|
|
458
|
+
const result = await integration.probeHostedTools({
|
|
459
|
+
apiBase: params.apiBase ?? DEFAULT_API_BASE2,
|
|
460
|
+
apiKey: params.apiKey,
|
|
461
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
462
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
463
|
+
...params.fetch ? { fetch: params.fetch } : {}
|
|
464
|
+
});
|
|
465
|
+
const missing = result.missing ?? [];
|
|
466
|
+
return {
|
|
467
|
+
ok: result.ok,
|
|
468
|
+
...result.status !== void 0 ? { status: result.status } : {},
|
|
469
|
+
...result.serverName ? { serverName: result.serverName } : {},
|
|
470
|
+
...result.serverVersion ? { serverVersion: result.serverVersion } : {},
|
|
471
|
+
...result.protocolVersion ? { protocolVersion: result.protocolVersion } : {},
|
|
472
|
+
...result.tools ? { tools: result.tools } : {},
|
|
473
|
+
...missing.length > 0 ? { missing } : {},
|
|
474
|
+
...result.error ? { error: result.error } : !result.ok && missing.length > 0 ? { error: `the server lists no ${missing.join(", ")} for this key` } : {}
|
|
475
|
+
};
|
|
585
476
|
}
|
|
586
477
|
|
|
587
478
|
// src/integration/runtime-holder.ts
|
|
@@ -601,11 +492,137 @@ function setPluginRuntime(runtime) {
|
|
|
601
492
|
function getPluginRuntime() {
|
|
602
493
|
return current;
|
|
603
494
|
}
|
|
495
|
+
|
|
496
|
+
// src/integration/run.ts
|
|
497
|
+
var DEFAULT_RUN_WAIT_CHUNK_MS = 5 * 6e4;
|
|
498
|
+
var RUN_WAIT_RETRY_MS = [1e3, 5e3, 15e3, 3e4, 6e4];
|
|
499
|
+
var MIN_WAIT_SPACING_MS = 1e3;
|
|
500
|
+
var TRANSCRIPT_READ_LIMIT = 200;
|
|
501
|
+
var METADATA_KEYS = ["endedAt", "stopReason", "livenessState", "pendingError", "timeoutPhase", "startedAt", "providerStarted"];
|
|
502
|
+
function runEndOf(wait, timing) {
|
|
503
|
+
const status = wait?.status;
|
|
504
|
+
const error = nonEmpty(wait?.error);
|
|
505
|
+
if (status === "ok") return { ended: true, status: "ok" };
|
|
506
|
+
if (status === "error") {
|
|
507
|
+
if (error && error.trim().toLowerCase() === "completed") return { ended: true, status: "ok" };
|
|
508
|
+
return { ended: true, status: "error", ...error ? { error } : {} };
|
|
509
|
+
}
|
|
510
|
+
if (status !== "timeout") {
|
|
511
|
+
return { ended: false };
|
|
512
|
+
}
|
|
513
|
+
const ended = { ended: true, status: "timeout", ...error ? { error } : {} };
|
|
514
|
+
const hasMetadata = wait !== null && wait !== void 0 && METADATA_KEYS.some((key) => key in wait);
|
|
515
|
+
if (!hasMetadata) {
|
|
516
|
+
return timing.elapsedMs < timing.requestedMs / 2 ? ended : { ended: false };
|
|
517
|
+
}
|
|
518
|
+
if (wait.pendingError === true) return { ended: false };
|
|
519
|
+
if (typeof wait.endedAt === "number" || nonEmpty(wait.stopReason) || nonEmpty(wait.livenessState)) return ended;
|
|
520
|
+
if (isHardTimeout(wait)) return ended;
|
|
521
|
+
return error ? ended : { ended: false };
|
|
522
|
+
}
|
|
523
|
+
var HARD_TIMEOUT_PHASES = /* @__PURE__ */ new Set(["preflight", "provider", "tool_execution", "post_turn"]);
|
|
524
|
+
function isHardTimeout(wait) {
|
|
525
|
+
const phase = typeof wait.timeoutPhase === "string" ? wait.timeoutPhase.trim() : "";
|
|
526
|
+
if (HARD_TIMEOUT_PHASES.has(phase)) return true;
|
|
527
|
+
return wait.status === "timeout" && wait.providerStarted === true && nonEmpty(wait.stopReason) !== "restart";
|
|
528
|
+
}
|
|
529
|
+
async function watchRunUntilEnded(options) {
|
|
530
|
+
const chunkMs = options.chunkMs ?? DEFAULT_RUN_WAIT_CHUNK_MS;
|
|
531
|
+
const retryMs = options.retryMs ?? RUN_WAIT_RETRY_MS;
|
|
532
|
+
const now = options.now ?? Date.now;
|
|
533
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
534
|
+
const started = now();
|
|
535
|
+
let failures = 0;
|
|
536
|
+
for (; ; ) {
|
|
537
|
+
const runtime = options.runtime();
|
|
538
|
+
if (!runtime) return { ended: false, reason: "gone", elapsedMs: now() - started };
|
|
539
|
+
const waitStarted = now();
|
|
540
|
+
let observation;
|
|
541
|
+
try {
|
|
542
|
+
observation = await runtime.subagent.waitForRun({ runId: options.runId, timeoutMs: chunkMs });
|
|
543
|
+
} catch (err) {
|
|
544
|
+
const message = describe(err);
|
|
545
|
+
const delay = retryMs[Math.min(failures, retryMs.length - 1)] ?? 6e4;
|
|
546
|
+
failures += 1;
|
|
547
|
+
options.onWaitError?.(message, failures, delay);
|
|
548
|
+
await sleep(delay);
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
failures = 0;
|
|
552
|
+
const elapsedMs = now() - waitStarted;
|
|
553
|
+
const end = runEndOf(observation, { requestedMs: chunkMs, elapsedMs });
|
|
554
|
+
if (end.ended) return { ...end, elapsedMs: now() - started };
|
|
555
|
+
options.onStillRunning?.(now() - started);
|
|
556
|
+
if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
function countAgentChatCalls(messages, runId) {
|
|
560
|
+
if (messages.length === 0) return null;
|
|
561
|
+
let recognised = false;
|
|
562
|
+
let made = 0;
|
|
563
|
+
let failed = 0;
|
|
564
|
+
for (const row of messages) {
|
|
565
|
+
const message = unwrapMessage(row);
|
|
566
|
+
if (!message) continue;
|
|
567
|
+
const role = message.role;
|
|
568
|
+
if (role === "assistant" || role === "user") recognised = true;
|
|
569
|
+
if (role !== "toolResult" && role !== "tool") continue;
|
|
570
|
+
recognised = true;
|
|
571
|
+
const meta = asRecord2(message.__openclaw);
|
|
572
|
+
if (runId && typeof meta?.runId === "string" && meta.runId !== runId) continue;
|
|
573
|
+
if (!isAgentChatToolResult(message)) continue;
|
|
574
|
+
made += 1;
|
|
575
|
+
if (message.isError === true) failed += 1;
|
|
576
|
+
}
|
|
577
|
+
return recognised ? { made, failed } : null;
|
|
578
|
+
}
|
|
579
|
+
async function readAgentChatCalls(runtime, sessionKey, runId) {
|
|
580
|
+
if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
|
|
581
|
+
try {
|
|
582
|
+
const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
|
|
583
|
+
const messages = result?.messages;
|
|
584
|
+
return Array.isArray(messages) ? countAgentChatCalls(messages, runId) : null;
|
|
585
|
+
} catch {
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
590
|
+
function isAgentChatToolResult(message) {
|
|
591
|
+
const toolName = typeof message.toolName === "string" ? message.toolName : typeof message.name === "string" ? message.name : "";
|
|
592
|
+
if (toolName.startsWith(TOOL_PREFIX)) return true;
|
|
593
|
+
const tool = asRecord2(asRecord2(message.details)?.tool);
|
|
594
|
+
if (!tool) return false;
|
|
595
|
+
if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
|
|
596
|
+
if (tool.sourceName === MCP_SERVER_NAME) return true;
|
|
597
|
+
const mcp = asRecord2(tool.mcp);
|
|
598
|
+
return mcp?.serverName === MCP_SERVER_NAME;
|
|
599
|
+
}
|
|
600
|
+
function unwrapMessage(row) {
|
|
601
|
+
const record = asRecord2(row);
|
|
602
|
+
if (!record) return null;
|
|
603
|
+
if (typeof record.role === "string") return record;
|
|
604
|
+
const inner = asRecord2(record.message);
|
|
605
|
+
return inner && typeof inner.role === "string" ? inner : null;
|
|
606
|
+
}
|
|
607
|
+
function asRecord2(value) {
|
|
608
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
609
|
+
}
|
|
610
|
+
function nonEmpty(value) {
|
|
611
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
612
|
+
}
|
|
613
|
+
function describe(err) {
|
|
614
|
+
return err instanceof Error ? err.message : String(err);
|
|
615
|
+
}
|
|
616
|
+
function defaultSleep(ms) {
|
|
617
|
+
return new Promise((resolve) => {
|
|
618
|
+
const timer = setTimeout(resolve, ms);
|
|
619
|
+
timer.unref?.();
|
|
620
|
+
});
|
|
621
|
+
}
|
|
604
622
|
var DEFAULT_AGENT_ID = "main";
|
|
605
623
|
var GATE_TEMPERATURE = 0;
|
|
606
624
|
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
607
625
|
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
608
|
-
var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
|
|
609
626
|
var RuntimeUnavailableError = class extends Error {
|
|
610
627
|
constructor(what) {
|
|
611
628
|
super(`OpenClaw plugin runtime unavailable \u2014 ${what} needs setRuntime(...) from defineChannelPluginEntry`);
|
|
@@ -630,16 +647,21 @@ function createRuntimeModelCall(params) {
|
|
|
630
647
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
631
648
|
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
632
649
|
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
633
|
-
return async (prompt) => {
|
|
650
|
+
return async (prompt, options) => {
|
|
634
651
|
const runtime = getRuntime();
|
|
635
652
|
if (!runtime) throw new RuntimeUnavailableError("the gate call");
|
|
653
|
+
const signals = [
|
|
654
|
+
...Number.isFinite(timeoutMs) && timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : [],
|
|
655
|
+
...options?.signal ? [options.signal] : []
|
|
656
|
+
];
|
|
657
|
+
const signal = signals.length === 0 ? void 0 : signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
636
658
|
const result = await runtime.llm.complete({
|
|
637
659
|
messages: [{ role: "user", content: prompt }],
|
|
638
660
|
maxTokens,
|
|
639
661
|
temperature: GATE_TEMPERATURE,
|
|
640
662
|
...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
|
|
641
663
|
purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
|
|
642
|
-
...
|
|
664
|
+
...signal ? { signal } : {}
|
|
643
665
|
});
|
|
644
666
|
return typeof result?.text === "string" ? result.text : "";
|
|
645
667
|
};
|
|
@@ -669,10 +691,14 @@ function resolveGateAgent(params) {
|
|
|
669
691
|
return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
|
|
670
692
|
}
|
|
671
693
|
function readLiveConfig(fallback, runtime = getPluginRuntime) {
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
if (
|
|
675
|
-
|
|
694
|
+
const config = runtime()?.config;
|
|
695
|
+
for (const read of [config?.current, config?.loadConfig]) {
|
|
696
|
+
if (typeof read !== "function") continue;
|
|
697
|
+
try {
|
|
698
|
+
const loaded = read.call(config);
|
|
699
|
+
if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
|
|
700
|
+
} catch {
|
|
701
|
+
}
|
|
676
702
|
}
|
|
677
703
|
return { cfg: fallback, live: false };
|
|
678
704
|
}
|
|
@@ -700,11 +726,11 @@ function turnReadiness(params) {
|
|
|
700
726
|
}
|
|
701
727
|
function createRuntimeTurnStarter(params = {}) {
|
|
702
728
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
703
|
-
const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
|
|
704
729
|
return async (request) => {
|
|
705
730
|
const runtime = getRuntime();
|
|
706
731
|
if (!runtime) return { ran: false, error: new RuntimeUnavailableError("the agent turn").message };
|
|
707
732
|
let runId;
|
|
733
|
+
let sessionKey = request.sessionKey;
|
|
708
734
|
try {
|
|
709
735
|
const admitted = await runtime.subagent.run({
|
|
710
736
|
sessionKey: request.sessionKey,
|
|
@@ -713,15 +739,46 @@ function createRuntimeTurnStarter(params = {}) {
|
|
|
713
739
|
deliver: false
|
|
714
740
|
});
|
|
715
741
|
runId = admitted.runId;
|
|
742
|
+
const accepted = admitted.sessionKey;
|
|
743
|
+
if (typeof accepted === "string" && accepted.trim().length > 0) sessionKey = accepted.trim();
|
|
716
744
|
} catch (err) {
|
|
717
745
|
return { ran: false, error: err instanceof Error ? err.message : String(err) };
|
|
718
746
|
}
|
|
719
|
-
const done =
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
747
|
+
const done = watchRunUntilEnded({
|
|
748
|
+
runtime: getRuntime,
|
|
749
|
+
runId,
|
|
750
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
751
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {},
|
|
752
|
+
...params.onWaitError ? { onWaitError: (error, attempt, retryInMs) => params.onWaitError?.({ runId, sessionKey, error, attempt, retryInMs }) } : {},
|
|
753
|
+
...params.now ? { now: params.now } : {},
|
|
754
|
+
...params.sleep ? { sleep: params.sleep } : {}
|
|
755
|
+
}).then(async (watched) => {
|
|
756
|
+
if (!watched.ended) return { ran: true, runId, status: "gone", elapsedMs: watched.elapsedMs };
|
|
757
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
758
|
+
return {
|
|
759
|
+
ran: true,
|
|
760
|
+
runId,
|
|
761
|
+
status: watched.status,
|
|
762
|
+
...watched.error ? { error: watched.error } : {},
|
|
763
|
+
agentchatCalls,
|
|
764
|
+
elapsedMs: watched.elapsedMs
|
|
765
|
+
};
|
|
766
|
+
});
|
|
767
|
+
return { ran: true, runId, sessionKey, done };
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
function createRunWatcher(params = {}) {
|
|
771
|
+
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
772
|
+
return async ({ runId, sessionKey }) => {
|
|
773
|
+
const watched = await watchRunUntilEnded({
|
|
774
|
+
runtime: getRuntime,
|
|
775
|
+
runId,
|
|
776
|
+
...params.waitChunkMs !== void 0 ? { chunkMs: params.waitChunkMs } : {},
|
|
777
|
+
...params.onStillRunning ? { onStillRunning: (elapsedMs) => params.onStillRunning?.({ runId, sessionKey, elapsedMs }) } : {}
|
|
778
|
+
});
|
|
779
|
+
if (!watched.ended) return null;
|
|
780
|
+
const agentchatCalls = await readAgentChatCalls(getRuntime(), sessionKey, runId);
|
|
781
|
+
return { ran: true, runId, status: watched.status, ...watched.error ? { error: watched.error } : {}, agentchatCalls, elapsedMs: watched.elapsedMs };
|
|
725
782
|
};
|
|
726
783
|
}
|
|
727
784
|
var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
@@ -860,7 +917,7 @@ function restoreIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
860
917
|
const written = writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
|
|
861
918
|
return { outcome: "placed", path: written.path };
|
|
862
919
|
} catch (err) {
|
|
863
|
-
return { outcome: "failed", path: filePath, detail:
|
|
920
|
+
return { outcome: "failed", path: filePath, detail: describe2(err) };
|
|
864
921
|
}
|
|
865
922
|
}
|
|
866
923
|
function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
@@ -872,7 +929,7 @@ function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
|
872
929
|
const written = writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
|
|
873
930
|
return { outcome: "updated", path: written.path };
|
|
874
931
|
} catch (err) {
|
|
875
|
-
return { outcome: "failed", path: agentsAnchorPath(cfg, agentId), detail:
|
|
932
|
+
return { outcome: "failed", path: agentsAnchorPath(cfg, agentId), detail: describe2(err) };
|
|
876
933
|
}
|
|
877
934
|
}
|
|
878
935
|
function placeIntegration(params) {
|
|
@@ -886,7 +943,7 @@ function placeIntegration(params) {
|
|
|
886
943
|
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
944
|
});
|
|
888
945
|
} catch (err) {
|
|
889
|
-
steps.push({ name: "key", status: "failed", detail: `could not write ${API_KEY_ENV} to the OpenClaw .env: ${
|
|
946
|
+
steps.push({ name: "key", status: "failed", detail: `could not write ${API_KEY_ENV} to the OpenClaw .env: ${describe2(err)}` });
|
|
890
947
|
}
|
|
891
948
|
}
|
|
892
949
|
const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
|
|
@@ -902,7 +959,7 @@ function placeIntegration(params) {
|
|
|
902
959
|
const anchor = writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
|
|
903
960
|
steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
|
|
904
961
|
} catch (err) {
|
|
905
|
-
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${
|
|
962
|
+
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe2(err)}` });
|
|
906
963
|
}
|
|
907
964
|
}
|
|
908
965
|
steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
|
|
@@ -963,7 +1020,7 @@ function checkPlacement(params) {
|
|
|
963
1020
|
});
|
|
964
1021
|
return checks;
|
|
965
1022
|
}
|
|
966
|
-
function
|
|
1023
|
+
function describe2(err) {
|
|
967
1024
|
return err instanceof Error ? err.message : String(err);
|
|
968
1025
|
}
|
|
969
1026
|
var PLUGIN_STATE_DIRNAME = "agentchat";
|
|
@@ -974,236 +1031,115 @@ function safeSegment(value) {
|
|
|
974
1031
|
function integrationStateDir(accountId, stateDir = resolveOpenClawStateDir()) {
|
|
975
1032
|
return path2.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
|
|
976
1033
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
1034
|
+
var OLD_INVITE_LEDGER_FILE = "invites.json";
|
|
1035
|
+
function removeOldStateFiles(accountId, stateDir) {
|
|
1036
|
+
const dir = integrationStateDir(accountId, stateDir);
|
|
1037
|
+
const removed = [];
|
|
1038
|
+
const ledger = path2.join(dir, OLD_INVITE_LEDGER_FILE);
|
|
1039
|
+
if (tryUnlink(ledger)) removed.push(ledger);
|
|
1040
|
+
const texts = path2.join(dir, "texts.json");
|
|
984
1041
|
try {
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1042
|
+
const entry = JSON.parse(fs.readFileSync(texts, "utf8"));
|
|
1043
|
+
if (entry.version !== 1 || typeof entry.runtime !== "string") {
|
|
1044
|
+
if (tryUnlink(texts)) removed.push(texts);
|
|
1045
|
+
}
|
|
1046
|
+
} catch (err) {
|
|
1047
|
+
if (err?.code !== "ENOENT" && tryUnlink(texts)) removed.push(texts);
|
|
988
1048
|
}
|
|
1049
|
+
return removed;
|
|
989
1050
|
}
|
|
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");
|
|
1051
|
+
function tryUnlink(file) {
|
|
995
1052
|
try {
|
|
996
|
-
fs.
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
} catch {
|
|
1001
|
-
}
|
|
1002
|
-
throw err;
|
|
1053
|
+
fs.unlinkSync(file);
|
|
1054
|
+
return true;
|
|
1055
|
+
} catch {
|
|
1056
|
+
return false;
|
|
1003
1057
|
}
|
|
1004
1058
|
}
|
|
1005
1059
|
|
|
1006
1060
|
// src/integration/texts.ts
|
|
1007
1061
|
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
1062
|
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
1063
|
function textsCachePath(accountId, stateDir) {
|
|
1019
1064
|
return path2.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1020
1065
|
}
|
|
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
1066
|
function spellTextsForOpenClaw(texts) {
|
|
1035
1067
|
return {
|
|
1036
1068
|
...texts,
|
|
1037
1069
|
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1038
1070
|
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1039
1071
|
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
1040
|
-
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
|
|
1072
|
+
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template),
|
|
1073
|
+
...typeof texts.gate_call_preamble === "string" ? { gate_call_preamble: spellToolsForOpenClaw(texts.gate_call_preamble) } : {},
|
|
1074
|
+
...typeof texts.gate_call_answer_format === "string" ? { gate_call_answer_format: spellToolsForOpenClaw(texts.gate_call_answer_format) } : {}
|
|
1041
1075
|
};
|
|
1042
1076
|
}
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1077
|
+
function createTextsCache(params) {
|
|
1078
|
+
return new integration.TextsCache({
|
|
1079
|
+
client: params.client,
|
|
1080
|
+
runtime: TEXTS_RUNTIME,
|
|
1081
|
+
filePath: textsCachePath(params.accountId, params.stateDir),
|
|
1082
|
+
...params.logger ? { onError: (err) => params.logger?.warn({ err: err.message }, "served texts") } : {}
|
|
1083
|
+
});
|
|
1047
1084
|
}
|
|
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;
|
|
1085
|
+
var OpenClawTexts = class {
|
|
1086
|
+
constructor(cache2) {
|
|
1087
|
+
this.cache = cache2;
|
|
1067
1088
|
}
|
|
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));
|
|
1089
|
+
cache;
|
|
1090
|
+
spelledFrom = null;
|
|
1091
|
+
spelled = null;
|
|
1092
|
+
current() {
|
|
1093
|
+
return this.spell(this.cache.current());
|
|
1107
1094
|
}
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
return this.loaded?.texts ?? null;
|
|
1095
|
+
async ensure() {
|
|
1096
|
+
return this.spell(await this.cache.ensure());
|
|
1111
1097
|
}
|
|
1112
1098
|
get source() {
|
|
1113
|
-
return this.
|
|
1099
|
+
return this.cache.source;
|
|
1114
1100
|
}
|
|
1115
1101
|
get fetchedAt() {
|
|
1116
|
-
return this.
|
|
1102
|
+
return this.cache.fetchedAt;
|
|
1117
1103
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
this.listeners.add(listener);
|
|
1121
|
-
return () => {
|
|
1122
|
-
this.listeners.delete(listener);
|
|
1123
|
-
};
|
|
1104
|
+
get lastError() {
|
|
1105
|
+
return this.cache.lastError;
|
|
1124
1106
|
}
|
|
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
|
-
);
|
|
1107
|
+
spell(texts) {
|
|
1108
|
+
if (texts === null) return null;
|
|
1109
|
+
if (texts !== this.spelledFrom) {
|
|
1110
|
+
this.spelledFrom = texts;
|
|
1111
|
+
this.spelled = spellTextsForOpenClaw(texts);
|
|
1134
1112
|
}
|
|
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();
|
|
1113
|
+
return this.spelled;
|
|
1143
1114
|
}
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1115
|
+
};
|
|
1116
|
+
async function loadIdentityLine(params) {
|
|
1117
|
+
const cache2 = createTextsCache(params);
|
|
1118
|
+
try {
|
|
1119
|
+
const texts = await cache2.start();
|
|
1120
|
+
return texts ? spellToolsForOpenClaw(texts.identity_line) : null;
|
|
1121
|
+
} catch {
|
|
1122
|
+
return null;
|
|
1123
|
+
} finally {
|
|
1124
|
+
cache2.stop();
|
|
1147
1125
|
}
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1126
|
+
}
|
|
1127
|
+
function cachedIdentityLine(accountId, stateDir) {
|
|
1128
|
+
let raw;
|
|
1129
|
+
try {
|
|
1130
|
+
raw = fs.readFileSync(textsCachePath(accountId, stateDir), "utf8");
|
|
1131
|
+
} catch {
|
|
1132
|
+
return null;
|
|
1155
1133
|
}
|
|
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?.();
|
|
1134
|
+
try {
|
|
1135
|
+
const entry = JSON.parse(raw);
|
|
1136
|
+
if (entry.runtime !== TEXTS_RUNTIME || !isTexts(entry.texts)) return null;
|
|
1137
|
+
return spellToolsForOpenClaw(entry.texts.identity_line);
|
|
1138
|
+
} catch {
|
|
1139
|
+
return null;
|
|
1202
1140
|
}
|
|
1203
|
-
};
|
|
1204
|
-
function describe2(err) {
|
|
1205
|
-
return err instanceof Error ? err.message : String(err);
|
|
1206
1141
|
}
|
|
1142
|
+
var isTexts = integration.isTexts;
|
|
1207
1143
|
var cache = /* @__PURE__ */ new Map();
|
|
1208
1144
|
function createSdkClient(params) {
|
|
1209
1145
|
return new AgentChatClient({
|
|
@@ -2009,40 +1945,677 @@ var agentchatChannelConfigSchema = z.object({
|
|
|
2009
1945
|
function parseChannelConfig(input) {
|
|
2010
1946
|
return agentchatChannelConfigSchema.parse(input);
|
|
2011
1947
|
}
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
1948
|
+
var TRAY_LIMIT = 50;
|
|
1949
|
+
function createAfterTurnRecorder(options) {
|
|
1950
|
+
const { client, logger } = options;
|
|
1951
|
+
return async (record, end) => {
|
|
1952
|
+
if (end.status === "still_running" || record.kind === "run") return;
|
|
1953
|
+
let fresh;
|
|
1954
|
+
try {
|
|
1955
|
+
fresh = await client.inbox.tray({ waitMs: 0, limit: TRAY_LIMIT, includeInvites: true });
|
|
1956
|
+
} catch (err) {
|
|
1957
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn tray read failed \u2014 nothing recorded; the server re-wakes the card");
|
|
1958
|
+
fresh = null;
|
|
1959
|
+
}
|
|
1960
|
+
try {
|
|
1961
|
+
if (record.kind === "reply") {
|
|
1962
|
+
if (!record.card) return;
|
|
1963
|
+
const outcome2 = integration.turnOutcome({
|
|
1964
|
+
turn: end,
|
|
1965
|
+
turnStartedAt: record.startedAt,
|
|
1966
|
+
gateCard: record.card,
|
|
1967
|
+
category: record.category ?? null,
|
|
1968
|
+
freshTray: fresh,
|
|
1969
|
+
silentBefore: 0
|
|
1970
|
+
});
|
|
1971
|
+
const recorded2 = await integration.applyOutcome(client, outcome2);
|
|
1972
|
+
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)");
|
|
1973
|
+
return;
|
|
1974
|
+
}
|
|
1975
|
+
if (!record.invite) return;
|
|
1976
|
+
const outcome = integration.inviteOutcome({ turn: end, invite: record.invite, freshTray: fresh, silentBefore: 0 });
|
|
1977
|
+
const recorded = await integration.applyInviteOutcome(client, outcome);
|
|
1978
|
+
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)");
|
|
1979
|
+
} catch (err) {
|
|
1980
|
+
logger.warn({ runId: record.runId, err: describe3(err) }, "after-turn recording failed \u2014 the card stays on the tray; the server re-wakes it");
|
|
2033
1981
|
}
|
|
2034
|
-
}
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
}
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
function cardFromStored(stored) {
|
|
1985
|
+
return { preview: null, ...stored };
|
|
1986
|
+
}
|
|
1987
|
+
function describe3(err) {
|
|
1988
|
+
return err instanceof Error ? err.message : String(err);
|
|
1989
|
+
}
|
|
1990
|
+
var TURN_STORE_FILE = "turns.json";
|
|
1991
|
+
var KEEP_ENDED_MS = 6e4;
|
|
1992
|
+
function storedCard(card, anchor) {
|
|
1993
|
+
return {
|
|
1994
|
+
conversation_id: card.conversation_id,
|
|
1995
|
+
...anchor ? { last_message_id: anchor } : {},
|
|
1996
|
+
...card.your_last_message_at !== void 0 ? { your_last_message_at: card.your_last_message_at } : {},
|
|
1997
|
+
...card.you_owe_reply !== void 0 ? { you_owe_reply: card.you_owe_reply } : {},
|
|
1998
|
+
...card.your_last_decision !== void 0 ? { your_last_decision: card.your_last_decision } : {}
|
|
1999
|
+
};
|
|
2000
|
+
}
|
|
2001
|
+
var TurnStore = class {
|
|
2002
|
+
file;
|
|
2003
|
+
constructor(accountId, stateDir) {
|
|
2004
|
+
this.file = path2.join(integrationStateDir(accountId, stateDir), TURN_STORE_FILE);
|
|
2005
|
+
}
|
|
2006
|
+
/** What the last process left. Empty when there is no file or it cannot be read. */
|
|
2007
|
+
load() {
|
|
2008
|
+
let parsed;
|
|
2009
|
+
try {
|
|
2010
|
+
parsed = JSON.parse(fs.readFileSync(this.file, "utf8"));
|
|
2011
|
+
} catch {
|
|
2012
|
+
return [];
|
|
2013
|
+
}
|
|
2014
|
+
const turns = parsed?.turns;
|
|
2015
|
+
if (parsed?.version !== 1 || !Array.isArray(turns)) return [];
|
|
2016
|
+
return turns.filter(isStoredTurn);
|
|
2017
|
+
}
|
|
2018
|
+
/** Replace the file with `turns` (removed when empty). Returns false when the write failed. */
|
|
2019
|
+
write(turns) {
|
|
2020
|
+
try {
|
|
2021
|
+
if (turns.length === 0) {
|
|
2022
|
+
fs.rmSync(this.file, { force: true });
|
|
2023
|
+
return true;
|
|
2024
|
+
}
|
|
2025
|
+
fs.mkdirSync(path2.dirname(this.file), { recursive: true });
|
|
2026
|
+
const body = { version: 1, turns };
|
|
2027
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
2028
|
+
fs.writeFileSync(tmp, `${JSON.stringify(body)}
|
|
2029
|
+
`, { mode: 384 });
|
|
2030
|
+
fs.renameSync(tmp, this.file);
|
|
2031
|
+
return true;
|
|
2032
|
+
} catch {
|
|
2033
|
+
return false;
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
};
|
|
2037
|
+
function isStoredTurn(value) {
|
|
2038
|
+
const turn = value;
|
|
2039
|
+
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");
|
|
2040
|
+
}
|
|
2041
|
+
|
|
2042
|
+
// src/integration/running.ts
|
|
2043
|
+
var TURN_OVERDUE_MS = 30 * 6e4;
|
|
2044
|
+
var OVERDUE_SLACK_MS = 5e3;
|
|
2045
|
+
function isOverdue(elapsedMs) {
|
|
2046
|
+
return elapsedMs + OVERDUE_SLACK_MS >= TURN_OVERDUE_MS;
|
|
2047
|
+
}
|
|
2048
|
+
var MAX_HUNG_TURNS = 2;
|
|
2049
|
+
var OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS = 2880 * 60;
|
|
2050
|
+
var RESTART_HOLD_MS = 3 * 6e4;
|
|
2051
|
+
var STORED_TURN_MAX_AGE_MS = 24 * 60 * 6e4;
|
|
2052
|
+
var RESTART_END_DETAIL = "the gateway restarted during the turn";
|
|
2053
|
+
function trackerKey(kind, id) {
|
|
2054
|
+
return kind === "reply" ? `conversation:${id}` : kind === "invite" ? `invite:${id}` : `run:${id}`;
|
|
2055
|
+
}
|
|
2056
|
+
function trackedTurn(record) {
|
|
2057
|
+
if (record.kind === "reply") return { kind: "reply", conversationId: record.id, anchor: record.anchor };
|
|
2058
|
+
if (record.kind === "invite") return { kind: "invite", inviteId: record.id };
|
|
2059
|
+
return null;
|
|
2060
|
+
}
|
|
2061
|
+
function storedOf(record) {
|
|
2062
|
+
if (record.kind === "run") return null;
|
|
2063
|
+
return {
|
|
2064
|
+
runId: record.runId,
|
|
2065
|
+
kind: record.kind,
|
|
2066
|
+
id: record.id,
|
|
2067
|
+
anchor: record.anchor,
|
|
2068
|
+
sessionKey: record.sessionKey,
|
|
2069
|
+
startedAt: record.startedAt,
|
|
2070
|
+
...record.firstStartedAt !== void 0 ? { firstStartedAt: record.firstStartedAt } : {},
|
|
2071
|
+
...record.category !== void 0 ? { category: record.category } : {},
|
|
2072
|
+
...record.kind === "reply" && record.card ? { card: storedCard(record.card, record.anchor) } : {}
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
function recordOf(stored) {
|
|
2076
|
+
return {
|
|
2077
|
+
runId: stored.runId,
|
|
2078
|
+
kind: stored.kind,
|
|
2079
|
+
id: stored.id,
|
|
2080
|
+
anchor: stored.anchor,
|
|
2081
|
+
sessionKey: stored.sessionKey,
|
|
2082
|
+
startedAt: stored.startedAt,
|
|
2083
|
+
firstStartedAt: stored.firstStartedAt ?? stored.startedAt,
|
|
2084
|
+
owner: "previous-process",
|
|
2085
|
+
...stored.category !== void 0 ? { category: stored.category } : {},
|
|
2086
|
+
...stored.kind === "reply" && stored.card ? { card: cardFromStored(stored.card) } : {},
|
|
2087
|
+
...stored.kind === "invite" ? { invite: { invite_id: stored.id } } : {}
|
|
2088
|
+
};
|
|
2089
|
+
}
|
|
2090
|
+
var AccountTurns = class {
|
|
2091
|
+
/** The kit's tracker for the account, shared by every loop for it. */
|
|
2092
|
+
tracker;
|
|
2093
|
+
entries = /* @__PURE__ */ new Map();
|
|
2094
|
+
/** Turns the last process left in flight, by session key. */
|
|
2095
|
+
adopted = /* @__PURE__ */ new Map();
|
|
2096
|
+
/** Turns OpenClaw is admitting right now. */
|
|
2097
|
+
admitting = /* @__PURE__ */ new Set();
|
|
2098
|
+
/** Ended runs still written to the store (`KEEP_ENDED_MS`). */
|
|
2099
|
+
kept = /* @__PURE__ */ new Map();
|
|
2100
|
+
keptTimer = null;
|
|
2101
|
+
live = null;
|
|
2102
|
+
wiring = {};
|
|
2103
|
+
/** Which OpenClaw lane new turns go to; moves on at every hand-off (a hung run blocks its lane). */
|
|
2104
|
+
lane = 0;
|
|
2105
|
+
now;
|
|
2106
|
+
constructor(options = {}) {
|
|
2107
|
+
this.now = options.now ?? Date.now;
|
|
2108
|
+
this.tracker = new integration.TurnTracker({ now: this.now });
|
|
2109
|
+
this.tracker.onRelease((handle) => {
|
|
2110
|
+
for (const admission of this.admitting) if (admission.key === handle.key) admission.released = true;
|
|
2111
|
+
});
|
|
2112
|
+
}
|
|
2113
|
+
/** The account's after-turn recorder, store and run watcher (each account start; the latest wins). */
|
|
2114
|
+
configure(wiring) {
|
|
2115
|
+
this.wiring = { ...this.wiring, ...wiring };
|
|
2116
|
+
}
|
|
2117
|
+
/** The loop now receiving for the account; a held run that ends wakes it. `run` = the loop's own async context (default: as called). */
|
|
2118
|
+
setLive(owner, wake, run = (fn) => fn()) {
|
|
2119
|
+
this.live = { owner, wake, run };
|
|
2120
|
+
}
|
|
2121
|
+
clearLive(owner) {
|
|
2122
|
+
if (this.live?.owner === owner) this.live = null;
|
|
2123
|
+
}
|
|
2124
|
+
/** A turn is about to be admitted by OpenClaw: watch whether its kit hold is released meanwhile. */
|
|
2125
|
+
admission(kind, id) {
|
|
2126
|
+
const admission = { key: trackerKey(kind, id), released: false };
|
|
2127
|
+
this.admitting.add(admission);
|
|
2128
|
+
return admission;
|
|
2129
|
+
}
|
|
2130
|
+
/** OpenClaw refused the turn: nothing to watch. */
|
|
2131
|
+
admitted(admission) {
|
|
2132
|
+
this.admitting.delete(admission);
|
|
2133
|
+
}
|
|
2134
|
+
/**
|
|
2135
|
+
* A run OpenClaw admitted. `letGo` (gate-off runs): ends the cycle waiting
|
|
2136
|
+
* on it when it is handed off or released. `admission`: a turn whose kit
|
|
2137
|
+
* hold was released during admission starts out let go of.
|
|
2138
|
+
*/
|
|
2139
|
+
started(record, options = {}) {
|
|
2140
|
+
const releasedMeanwhile = options.admission?.released === true;
|
|
2141
|
+
if (options.admission) this.admitting.delete(options.admission);
|
|
2142
|
+
this.entries.set(record.runId, {
|
|
2143
|
+
record,
|
|
2144
|
+
state: releasedMeanwhile ? "released" : "kit",
|
|
2145
|
+
handle: null,
|
|
2146
|
+
since: 0,
|
|
2147
|
+
...options.letGo ? { letGo: options.letGo } : {}
|
|
2148
|
+
});
|
|
2149
|
+
this.persist();
|
|
2150
|
+
}
|
|
2151
|
+
run(runId) {
|
|
2152
|
+
return this.entries.get(runId)?.record;
|
|
2153
|
+
}
|
|
2154
|
+
/** Where the run stands (`null`: not a run of this account, or ended). */
|
|
2155
|
+
stateOf(runId) {
|
|
2156
|
+
return this.entries.get(runId)?.state ?? null;
|
|
2157
|
+
}
|
|
2158
|
+
/** Every run OpenClaw has not reported ended that still holds something, oldest first. */
|
|
2159
|
+
runningRuns() {
|
|
2160
|
+
return [...this.entries.values()].filter((entry) => entry.state !== "released").map((entry) => entry.record).sort((a, b) => a.startedAt - b.startedAt);
|
|
2161
|
+
}
|
|
2162
|
+
hungRuns() {
|
|
2163
|
+
return [...this.entries.values()].filter((entry) => entry.state === "hung").map((entry) => entry.record);
|
|
2164
|
+
}
|
|
2165
|
+
get hungCount() {
|
|
2166
|
+
let count = 0;
|
|
2167
|
+
for (const entry of this.entries.values()) if (entry.state === "hung") count += 1;
|
|
2168
|
+
return count;
|
|
2169
|
+
}
|
|
2170
|
+
/** The handed-off gate-off run still going, if any: no new run starts while it lives. */
|
|
2171
|
+
hungSingleRun() {
|
|
2172
|
+
for (const entry of this.entries.values()) if (entry.state === "hung" && entry.record.kind === "run") return entry.record;
|
|
2173
|
+
return null;
|
|
2174
|
+
}
|
|
2175
|
+
/** Conversations (and invites) held after a restart: adopted (until when), or continued by a run OpenClaw started. */
|
|
2176
|
+
restartHolds() {
|
|
2177
|
+
const holds = [...this.adopted.values()].map((a) => ({
|
|
2178
|
+
record: a.record,
|
|
2179
|
+
until: a.until,
|
|
2180
|
+
watching: null
|
|
2181
|
+
}));
|
|
2182
|
+
for (const entry of this.entries.values()) if (entry.state === "watch") holds.push({ record: entry.record, until: null, watching: entry.record.runId });
|
|
2183
|
+
return holds;
|
|
2184
|
+
}
|
|
2185
|
+
/** The lane generation new turns start on (`integrationLane(accountId, laneGeneration)`). */
|
|
2186
|
+
get laneGeneration() {
|
|
2187
|
+
return this.lane;
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* OpenClaw reported the run ended (`end`: what it did, when known). A turn
|
|
2191
|
+
* held here (handed off, or continued after a restart) gets the after-turn
|
|
2192
|
+
* rule, then its hold drops and the live loop is woken. A turn the kit
|
|
2193
|
+
* still holds is the kit's to record; the live loop is woken once the card
|
|
2194
|
+
* is free, only when an earlier loop started it. A run let go of records
|
|
2195
|
+
* nothing.
|
|
2196
|
+
*/
|
|
2197
|
+
async ended(runId, end) {
|
|
2198
|
+
const entry = this.entries.get(runId);
|
|
2199
|
+
if (!entry) return;
|
|
2200
|
+
this.entries.delete(runId);
|
|
2201
|
+
if (entry.state !== "released") this.keep(entry.record);
|
|
2202
|
+
else this.persist();
|
|
2203
|
+
if (entry.state === "hung" || entry.state === "watch") {
|
|
2204
|
+
try {
|
|
2205
|
+
if (end && this.wiring.recorder && entry.record.kind !== "run") await this.wiring.recorder(entry.record, end);
|
|
2206
|
+
} finally {
|
|
2207
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2208
|
+
this.live?.wake();
|
|
2209
|
+
}
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
if (entry.state === "released" || entry.record.kind === "run") return;
|
|
2213
|
+
if (!this.live || this.live.owner === entry.record.owner) return;
|
|
2214
|
+
this.wakeWhenFree(trackerKey(entry.record.kind, entry.record.id));
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2217
|
+
* Hand a long run off, once, by run id: release the kit's slot for it (its
|
|
2218
|
+
* loop records nothing for it and may start other turns) and hold the
|
|
2219
|
+
* conversation here until the run ends. A gate-off run: the cycle waiting
|
|
2220
|
+
* on it is let go of. A continued run is already held here: it becomes
|
|
2221
|
+
* hung (counted toward `MAX_HUNG_TURNS`). Returns the record when it was
|
|
2222
|
+
* handed off now; null when it was already handed off or let go of.
|
|
2223
|
+
*/
|
|
2224
|
+
handOff(runId) {
|
|
2225
|
+
const entry = this.entries.get(runId);
|
|
2226
|
+
if (!entry || entry.state !== "kit" && entry.state !== "watch") return null;
|
|
2227
|
+
const record = entry.record;
|
|
2228
|
+
entry.since = this.now();
|
|
2229
|
+
if (entry.state === "watch") {
|
|
2230
|
+
entry.state = "hung";
|
|
2231
|
+
this.live?.wake();
|
|
2232
|
+
return record;
|
|
2233
|
+
}
|
|
2234
|
+
this.lane += 1;
|
|
2235
|
+
entry.state = "hung";
|
|
2236
|
+
const turn = trackedTurn(record);
|
|
2237
|
+
if (turn === null) {
|
|
2238
|
+
entry.letGo?.();
|
|
2239
|
+
} else {
|
|
2240
|
+
this.tracker.release(trackerKey(record.kind, record.id));
|
|
2241
|
+
entry.handle = this.tracker.begin(turn);
|
|
2242
|
+
if (!entry.handle) entry.state = "released";
|
|
2243
|
+
}
|
|
2244
|
+
this.live?.wake();
|
|
2245
|
+
return entry.state === "hung" ? record : null;
|
|
2246
|
+
}
|
|
2247
|
+
/**
|
|
2248
|
+
* An operator lets go of a conversation's (or invite's) turn: a hung hold,
|
|
2249
|
+
* a restart hold, or — past `TURN_OVERDUE_MS`, or with `force` — a turn
|
|
2250
|
+
* still running. Its run may still be live and answer: a second reply is
|
|
2251
|
+
* then possible, which is why a turn under 30 minutes (most likely still
|
|
2252
|
+
* working) is refused without `force`. A gate-off run always needs
|
|
2253
|
+
* `force`: it reads the whole tray, so a new run would answer the same
|
|
2254
|
+
* cards while it may still be going.
|
|
2255
|
+
*/
|
|
2256
|
+
release(id, options = {}) {
|
|
2257
|
+
const live = this.live;
|
|
2258
|
+
return live ? live.run(() => this.releaseNow(id, options.force === true)) : this.releaseNow(id, options.force === true);
|
|
2259
|
+
}
|
|
2260
|
+
releaseNow(id, force) {
|
|
2261
|
+
const matches = (record) => record.id === id || record.runId === id;
|
|
2262
|
+
for (const entry of this.entries.values()) {
|
|
2263
|
+
if (entry.state !== "hung" || !matches(entry.record)) continue;
|
|
2264
|
+
if (entry.record.kind === "run" && !force) return this.refuseSingleRun(entry.record);
|
|
2265
|
+
entry.state = "released";
|
|
2266
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2267
|
+
entry.handle = null;
|
|
2268
|
+
this.persist();
|
|
2269
|
+
this.live?.wake();
|
|
2270
|
+
return { released: true, what: "hung", key: trackerKey(entry.record.kind, entry.record.id), runId: entry.record.runId };
|
|
2271
|
+
}
|
|
2272
|
+
for (const [sessionKey, adopted] of this.adopted) {
|
|
2273
|
+
if (adopted.record.id !== id) continue;
|
|
2274
|
+
this.finishAdopted(sessionKey);
|
|
2275
|
+
return { released: true, what: "restart", key: trackerKey(adopted.record.kind, adopted.record.id), runId: null };
|
|
2276
|
+
}
|
|
2277
|
+
for (const entry of this.entries.values()) {
|
|
2278
|
+
if (entry.state !== "kit" && entry.state !== "watch" || !matches(entry.record)) continue;
|
|
2279
|
+
const refused = this.refuseYoung(entry.record.kind, entry.record.id, entry.record.startedAt, force);
|
|
2280
|
+
if (refused) return refused;
|
|
2281
|
+
const key = trackerKey(entry.record.kind, entry.record.id);
|
|
2282
|
+
if (entry.state === "watch") {
|
|
2283
|
+
if (entry.handle) this.tracker.end(entry.handle);
|
|
2284
|
+
entry.handle = null;
|
|
2285
|
+
} else {
|
|
2286
|
+
this.lane += 1;
|
|
2287
|
+
if (entry.record.kind === "run") entry.letGo?.();
|
|
2288
|
+
else this.tracker.release(key);
|
|
2289
|
+
}
|
|
2290
|
+
entry.state = "released";
|
|
2291
|
+
this.persist();
|
|
2292
|
+
this.live?.wake();
|
|
2293
|
+
return { released: true, what: "running", key, runId: entry.record.runId };
|
|
2294
|
+
}
|
|
2295
|
+
for (const held of this.tracker.running()) {
|
|
2296
|
+
const heldId = held.kind === "reply" ? held.conversationId : held.inviteId;
|
|
2297
|
+
if (heldId !== id) continue;
|
|
2298
|
+
const refused = this.refuseYoung(held.kind, heldId, held.startedAt, force);
|
|
2299
|
+
if (refused) return refused;
|
|
2300
|
+
this.lane += 1;
|
|
2301
|
+
const key = trackerKey(held.kind, heldId);
|
|
2302
|
+
if (this.tracker.release(key)) {
|
|
2303
|
+
this.live?.wake();
|
|
2304
|
+
return { released: true, what: "running", key, runId: null };
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
return { released: false, reason: `no turn holds ${id}` };
|
|
2308
|
+
}
|
|
2309
|
+
refuseYoung(kind, id, startedAt, force) {
|
|
2310
|
+
const age = this.now() - startedAt;
|
|
2311
|
+
if (force || age >= TURN_OVERDUE_MS) return null;
|
|
2312
|
+
return {
|
|
2313
|
+
released: false,
|
|
2314
|
+
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`
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
refuseSingleRun(record) {
|
|
2318
|
+
return {
|
|
2319
|
+
released: false,
|
|
2320
|
+
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`
|
|
2321
|
+
};
|
|
2322
|
+
}
|
|
2323
|
+
/**
|
|
2324
|
+
* Adopt the turns the last process left in flight (the store). Each one's
|
|
2325
|
+
* conversation (or invite) is held at once — before the loop's first gate —
|
|
2326
|
+
* for `RESTART_HOLD_MS`; the after-turn rule is applied to what the ended
|
|
2327
|
+
* run did now and again when the hold expires. A run OpenClaw starts in the
|
|
2328
|
+
* turn's session meanwhile (`observeRun`) takes the hold over. A turn first
|
|
2329
|
+
* started more than `STORED_TURN_MAX_AGE_MS` ago is dropped. Returns what
|
|
2330
|
+
* was adopted.
|
|
2331
|
+
*/
|
|
2332
|
+
adopt(stored = this.wiring.store?.load() ?? []) {
|
|
2333
|
+
const adopted = [];
|
|
2334
|
+
const now = this.now();
|
|
2335
|
+
for (const turn of stored) {
|
|
2336
|
+
if (this.entries.has(turn.runId) || this.adopted.has(turn.sessionKey) || this.kept.has(turn.runId)) continue;
|
|
2337
|
+
const first = turn.firstStartedAt ?? turn.startedAt;
|
|
2338
|
+
if (now - first > STORED_TURN_MAX_AGE_MS) {
|
|
2339
|
+
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");
|
|
2340
|
+
continue;
|
|
2341
|
+
}
|
|
2342
|
+
const record = recordOf(turn);
|
|
2343
|
+
const tracked = trackedTurn(record);
|
|
2344
|
+
const handle = tracked ? this.tracker.begin(tracked) : null;
|
|
2345
|
+
if (!handle) continue;
|
|
2346
|
+
const entry = { stored: { ...turn, firstStartedAt: first }, record, handle, until: now + RESTART_HOLD_MS, end: null, timer: null };
|
|
2347
|
+
this.adopted.set(turn.sessionKey, entry);
|
|
2348
|
+
entry.timer = setTimeout(() => this.expireAdopted(turn.sessionKey, entry), RESTART_HOLD_MS);
|
|
2349
|
+
entry.timer.unref?.();
|
|
2350
|
+
adopted.push(record);
|
|
2351
|
+
void this.recordRestartEnded(entry);
|
|
2352
|
+
}
|
|
2353
|
+
this.persist();
|
|
2354
|
+
return adopted;
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* A run started in some session (the `model_call_started` hook). One in
|
|
2358
|
+
* the session of a turn adopted after a restart is OpenClaw continuing
|
|
2359
|
+
* that turn: it takes the hold over as a turn of its own (`watch`), handed
|
|
2360
|
+
* off past `TURN_OVERDUE_MS` like any other.
|
|
2361
|
+
*/
|
|
2362
|
+
observeRun(runId, sessionKey) {
|
|
2363
|
+
if (!sessionKey || this.entries.has(runId)) return;
|
|
2364
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2365
|
+
if (!adopted) return;
|
|
2366
|
+
this.adopted.delete(sessionKey);
|
|
2367
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2368
|
+
const record = { ...adopted.record, runId, startedAt: this.now(), owner: "restart" };
|
|
2369
|
+
this.entries.set(runId, { record, state: "watch", handle: adopted.handle, since: 0 });
|
|
2370
|
+
this.persist();
|
|
2371
|
+
this.wiring.logger?.info(
|
|
2372
|
+
{ runId, sessionKey, [record.kind === "reply" ? "conversationId" : "inviteId"]: record.id },
|
|
2373
|
+
"OpenClaw continued a turn session after the restart \u2014 its conversation stays held until that run ends"
|
|
2374
|
+
);
|
|
2375
|
+
void this.watchContinued(record);
|
|
2376
|
+
}
|
|
2377
|
+
async watchContinued(record) {
|
|
2378
|
+
let end = null;
|
|
2379
|
+
try {
|
|
2380
|
+
end = this.wiring.watch ? await this.wiring.watch(record) : null;
|
|
2381
|
+
} catch {
|
|
2382
|
+
end = null;
|
|
2383
|
+
}
|
|
2384
|
+
if (end === null) return;
|
|
2385
|
+
await this.ended(record.runId, end);
|
|
2386
|
+
}
|
|
2387
|
+
async recordRestartEnded(adopted) {
|
|
2388
|
+
const { record } = adopted;
|
|
2389
|
+
let calls = null;
|
|
2390
|
+
try {
|
|
2391
|
+
calls = this.wiring.readCalls ? await this.wiring.readCalls(record.sessionKey, record.runId) : null;
|
|
2392
|
+
} catch {
|
|
2393
|
+
calls = null;
|
|
2394
|
+
}
|
|
2395
|
+
adopted.end = { status: "failed", agentchatCalls: calls, detail: RESTART_END_DETAIL };
|
|
2396
|
+
if (this.adopted.get(record.sessionKey) !== adopted || !this.wiring.recorder) return;
|
|
2397
|
+
await this.wiring.recorder(record, adopted.end);
|
|
2398
|
+
}
|
|
2399
|
+
/**
|
|
2400
|
+
* The hold expired with nothing continuing the turn: the after-turn rule
|
|
2401
|
+
* once more — the resumed main session may have answered the card
|
|
2402
|
+
* meanwhile — then the conversation is free.
|
|
2403
|
+
*/
|
|
2404
|
+
expireAdopted(sessionKey, adopted) {
|
|
2405
|
+
if (this.adopted.get(sessionKey) !== adopted) return;
|
|
2406
|
+
void (async () => {
|
|
2407
|
+
try {
|
|
2408
|
+
if (this.wiring.recorder) await this.wiring.recorder(adopted.record, adopted.end ?? { status: "failed", agentchatCalls: null, detail: RESTART_END_DETAIL });
|
|
2409
|
+
} catch {
|
|
2410
|
+
}
|
|
2411
|
+
if (this.adopted.get(sessionKey) === adopted) this.finishAdopted(sessionKey);
|
|
2412
|
+
})();
|
|
2413
|
+
}
|
|
2414
|
+
finishAdopted(sessionKey) {
|
|
2415
|
+
const adopted = this.adopted.get(sessionKey);
|
|
2416
|
+
if (!adopted) return;
|
|
2417
|
+
this.adopted.delete(sessionKey);
|
|
2418
|
+
if (adopted.timer) clearTimeout(adopted.timer);
|
|
2419
|
+
this.tracker.end(adopted.handle);
|
|
2420
|
+
this.persist();
|
|
2421
|
+
this.live?.wake();
|
|
2422
|
+
}
|
|
2423
|
+
/** An ended run stays in the store a little longer: a restart ends the run before it ends the process. */
|
|
2424
|
+
keep(record) {
|
|
2425
|
+
const turn = storedOf(record);
|
|
2426
|
+
if (turn) this.kept.set(record.runId, { turn, endedAt: this.now() });
|
|
2427
|
+
this.persist();
|
|
2428
|
+
if (!this.keptTimer) this.schedulePrune();
|
|
2429
|
+
}
|
|
2430
|
+
/** The next prune at the oldest kept entry's expiry. */
|
|
2431
|
+
schedulePrune() {
|
|
2432
|
+
let oldest = Infinity;
|
|
2433
|
+
for (const kept of this.kept.values()) oldest = Math.min(oldest, kept.endedAt);
|
|
2434
|
+
if (oldest === Infinity) return;
|
|
2435
|
+
this.keptTimer = setTimeout(() => this.pruneKept(), Math.max(0, oldest + KEEP_ENDED_MS - this.now()));
|
|
2436
|
+
this.keptTimer.unref?.();
|
|
2437
|
+
}
|
|
2438
|
+
pruneKept() {
|
|
2439
|
+
this.keptTimer = null;
|
|
2440
|
+
const cutoff = this.now() - KEEP_ENDED_MS;
|
|
2441
|
+
for (const [runId, kept] of this.kept) if (kept.endedAt <= cutoff) this.kept.delete(runId);
|
|
2442
|
+
this.persist();
|
|
2443
|
+
this.schedulePrune();
|
|
2444
|
+
}
|
|
2445
|
+
persist() {
|
|
2446
|
+
const store = this.wiring.store;
|
|
2447
|
+
if (!store) return;
|
|
2448
|
+
const turns = /* @__PURE__ */ new Map();
|
|
2449
|
+
for (const entry of this.entries.values()) {
|
|
2450
|
+
if (entry.state === "released") continue;
|
|
2451
|
+
const turn = storedOf(entry.record);
|
|
2452
|
+
if (turn) turns.set(turn.runId, turn);
|
|
2453
|
+
}
|
|
2454
|
+
for (const [runId, kept] of this.kept) turns.set(runId, kept.turn);
|
|
2455
|
+
for (const adopted of this.adopted.values()) turns.set(adopted.stored.runId, adopted.stored);
|
|
2456
|
+
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)");
|
|
2457
|
+
}
|
|
2458
|
+
wakeWhenFree(key, attempts = 300) {
|
|
2459
|
+
const held = key.startsWith("conversation:") ? this.tracker.conversationRunning(key.slice("conversation:".length)) : this.tracker.inviteRunning(key.slice("invite:".length));
|
|
2460
|
+
if (!held || attempts <= 0) {
|
|
2461
|
+
this.live?.wake();
|
|
2462
|
+
return;
|
|
2463
|
+
}
|
|
2464
|
+
const timer = setTimeout(() => this.wakeWhenFree(key, attempts - 1), 100);
|
|
2465
|
+
timer.unref?.();
|
|
2466
|
+
}
|
|
2467
|
+
};
|
|
2468
|
+
var accounts = /* @__PURE__ */ new Map();
|
|
2469
|
+
function accountTurns(accountId) {
|
|
2470
|
+
let turns = accounts.get(accountId);
|
|
2471
|
+
if (!turns) {
|
|
2472
|
+
turns = new AccountTurns();
|
|
2473
|
+
accounts.set(accountId, turns);
|
|
2474
|
+
}
|
|
2475
|
+
return turns;
|
|
2476
|
+
}
|
|
2477
|
+
function findAccountTurns(accountId) {
|
|
2478
|
+
return accounts.get(accountId);
|
|
2479
|
+
}
|
|
2480
|
+
function trackerFor(accountId) {
|
|
2481
|
+
return accountTurns(accountId).tracker;
|
|
2482
|
+
}
|
|
2483
|
+
function observeRunStarted(runId, sessionKey) {
|
|
2484
|
+
if (typeof runId !== "string" || runId.length === 0 || typeof sessionKey !== "string" || sessionKey.length === 0) return;
|
|
2485
|
+
for (const turns of accounts.values()) turns.observeRun(runId, sessionKey);
|
|
2486
|
+
}
|
|
2487
|
+
function runDeadline(cfg) {
|
|
2488
|
+
const value = cfg?.agents?.defaults?.timeoutSeconds;
|
|
2489
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return { seconds: Math.floor(value), configured: true };
|
|
2490
|
+
return { seconds: OPENCLAW_DEFAULT_RUN_TIMEOUT_SECONDS, configured: false };
|
|
2491
|
+
}
|
|
2492
|
+
function whatOf(kind, id) {
|
|
2493
|
+
return kind === "reply" ? `conversation ${id}` : kind === "invite" ? `invite ${id}` : `the gate-off run ${id}`;
|
|
2494
|
+
}
|
|
2495
|
+
function deadlineText(cfg) {
|
|
2496
|
+
const deadline = runDeadline(cfg);
|
|
2497
|
+
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)"}`;
|
|
2498
|
+
}
|
|
2499
|
+
function overdueTurnLine(turn, cfg) {
|
|
2500
|
+
const minutes = Math.round(turn.elapsedMs / 6e4);
|
|
2501
|
+
if (turn.kind === "run") {
|
|
2502
|
+
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)}`;
|
|
2503
|
+
}
|
|
2504
|
+
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`;
|
|
2505
|
+
}
|
|
2506
|
+
function overdueTurnLines(runs, cfg, now = Date.now()) {
|
|
2507
|
+
return runs.filter((run) => now - run.startedAt > TURN_OVERDUE_MS).map((run) => overdueTurnLine({ kind: run.kind, id: run.id, elapsedMs: now - run.startedAt }, cfg));
|
|
2508
|
+
}
|
|
2509
|
+
function restartHoldLines(turns, now = Date.now()) {
|
|
2510
|
+
return turns.restartHolds().map(
|
|
2511
|
+
({ 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`
|
|
2512
|
+
);
|
|
2513
|
+
}
|
|
2514
|
+
function hungTurnsReason(turns, cfg, now = Date.now()) {
|
|
2515
|
+
const single = turns.hungSingleRun();
|
|
2516
|
+
if (single) {
|
|
2517
|
+
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)`;
|
|
2518
|
+
}
|
|
2519
|
+
if (turns.hungCount < MAX_HUNG_TURNS) return null;
|
|
2520
|
+
const held = turns.hungRuns().map((run) => `${whatOf(run.kind, run.id)} for ${Math.floor((now - run.startedAt) / 6e4)} min`).join(", ");
|
|
2521
|
+
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`;
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
// src/binding/release.ts
|
|
2525
|
+
var RELEASE_METHOD = "agentchat.release";
|
|
2526
|
+
function releaseTurnFor(params) {
|
|
2527
|
+
const id = typeof params.id === "string" ? params.id.trim() : "";
|
|
2528
|
+
if (!id) return { ok: false, error: "a conversation (or invite) id is required" };
|
|
2529
|
+
const accountId = typeof params.accountId === "string" && params.accountId.trim() ? params.accountId.trim() : "default";
|
|
2530
|
+
const turns = findAccountTurns(accountId);
|
|
2531
|
+
if (!turns) return { ok: true, result: { released: false, reason: `the AgentChat account "${accountId}" has no turns in this gateway` } };
|
|
2532
|
+
return { ok: true, result: turns.release(id, { force: params.force === true }) };
|
|
2533
|
+
}
|
|
2534
|
+
function registerReleaseGatewayMethod(api) {
|
|
2535
|
+
api.registerGatewayMethod(
|
|
2536
|
+
RELEASE_METHOD,
|
|
2537
|
+
({ params, respond }) => {
|
|
2538
|
+
const outcome = releaseTurnFor(params);
|
|
2539
|
+
if (!outcome.ok) {
|
|
2540
|
+
respond(false, void 0, { code: "INVALID_REQUEST", message: outcome.error });
|
|
2541
|
+
return;
|
|
2542
|
+
}
|
|
2543
|
+
respond(true, outcome.result);
|
|
2544
|
+
},
|
|
2545
|
+
{ scope: "operator.admin" }
|
|
2546
|
+
);
|
|
2547
|
+
}
|
|
2548
|
+
function registerReleaseCli(api) {
|
|
2549
|
+
api.registerCli(
|
|
2550
|
+
({ program }) => {
|
|
2551
|
+
const root = program.command(AGENTCHAT_CHANNEL_ID).description("The AgentChat integration");
|
|
2552
|
+
root.command("release <id>").description(
|
|
2553
|
+
`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.`
|
|
2554
|
+
).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) => {
|
|
2555
|
+
const { callGatewayFromCli } = await import('openclaw/plugin-sdk/gateway-runtime');
|
|
2556
|
+
const result = await callGatewayFromCli(
|
|
2557
|
+
RELEASE_METHOD,
|
|
2558
|
+
{ ...opts.url ? { url: opts.url } : {}, ...opts.token ? { token: opts.token } : {}, ...opts.json ? { json: true } : {} },
|
|
2559
|
+
{ id, accountId: opts.account ?? "default", ...opts.force ? { force: true } : {} }
|
|
2560
|
+
);
|
|
2561
|
+
process.stdout.write(opts.json ? `${JSON.stringify(result)}
|
|
2562
|
+
` : `${releaseLine(id, result)}
|
|
2563
|
+
`);
|
|
2564
|
+
});
|
|
2565
|
+
},
|
|
2566
|
+
{
|
|
2567
|
+
commands: [AGENTCHAT_CHANNEL_ID],
|
|
2568
|
+
descriptors: [{ name: AGENTCHAT_CHANNEL_ID, description: "The AgentChat integration (release a hung turn)", hasSubcommands: true }]
|
|
2569
|
+
}
|
|
2570
|
+
);
|
|
2571
|
+
}
|
|
2572
|
+
function releaseLine(id, result) {
|
|
2573
|
+
if (!result?.released) return `nothing released: ${result?.reason ?? "unknown"}`;
|
|
2574
|
+
if (result.what === "restart") return `released ${id} (held after a gateway restart) \u2014 it may be gated again now`;
|
|
2575
|
+
const what = result.what === "hung" ? "a hung turn" : "a running turn";
|
|
2576
|
+
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`;
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
// src/binding/run-observer.ts
|
|
2580
|
+
function registerRunObserver(api) {
|
|
2581
|
+
api.on("model_call_started", (event, ctx) => {
|
|
2582
|
+
observeRunStarted(event.runId, event.sessionKey ?? ctx?.sessionKey);
|
|
2583
|
+
});
|
|
2584
|
+
}
|
|
2585
|
+
function createLogger(options) {
|
|
2586
|
+
if (options.delegate) {
|
|
2587
|
+
return options.delegate;
|
|
2588
|
+
}
|
|
2589
|
+
const pinoLogger = pino({
|
|
2590
|
+
level: options.level,
|
|
2591
|
+
base: { plugin: "@agentchatme/openclaw" },
|
|
2592
|
+
redact: {
|
|
2593
|
+
paths: buildRedactPaths(options.redactKeys),
|
|
2594
|
+
censor: "[REDACTED]"
|
|
2595
|
+
},
|
|
2596
|
+
timestamp: pino.stdTimeFunctions.isoTime
|
|
2597
|
+
});
|
|
2598
|
+
return wrapPino(pinoLogger);
|
|
2599
|
+
}
|
|
2600
|
+
function buildRedactPaths(keys) {
|
|
2601
|
+
const prefixes = ["", "config.", "headers.", "context.", "req.headers.", "res.headers."];
|
|
2602
|
+
const paths = [];
|
|
2603
|
+
for (const key of keys) {
|
|
2604
|
+
for (const prefix of prefixes) {
|
|
2605
|
+
paths.push(`${prefix}${key}`);
|
|
2606
|
+
}
|
|
2607
|
+
}
|
|
2608
|
+
paths.push(...keys.map((k) => `*.${k}`));
|
|
2609
|
+
return paths;
|
|
2610
|
+
}
|
|
2611
|
+
function wrapPino(p) {
|
|
2612
|
+
return {
|
|
2613
|
+
trace: (obj, msg) => p.trace(obj, msg),
|
|
2614
|
+
debug: (obj, msg) => p.debug(obj, msg),
|
|
2615
|
+
info: (obj, msg) => p.info(obj, msg),
|
|
2616
|
+
warn: (obj, msg) => p.warn(obj, msg),
|
|
2617
|
+
error: (obj, msg) => p.error(obj, msg),
|
|
2618
|
+
child: (bindings) => wrapPino(p.child(bindings))
|
|
2046
2619
|
};
|
|
2047
2620
|
}
|
|
2048
2621
|
|
|
@@ -2107,85 +2680,12 @@ function createNoopMetrics() {
|
|
|
2107
2680
|
incWake: () => void 0
|
|
2108
2681
|
};
|
|
2109
2682
|
}
|
|
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
2683
|
|
|
2186
2684
|
// src/integration/socket.ts
|
|
2187
2685
|
function wakeSourceOf(reason) {
|
|
2188
|
-
|
|
2686
|
+
if (reason === "reminder") return "reminder";
|
|
2687
|
+
if (reason === "unanswered") return "unanswered";
|
|
2688
|
+
return "other";
|
|
2189
2689
|
}
|
|
2190
2690
|
function realtimeOptionsFor(config, extra = {}) {
|
|
2191
2691
|
return {
|
|
@@ -2193,6 +2693,10 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2193
2693
|
baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
|
|
2194
2694
|
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
2195
2695
|
ackOnReceipt: true,
|
|
2696
|
+
// `rewake`: the server re-wakes this socket while cards stay unanswered
|
|
2697
|
+
// (contract v1, D3) — the integration keeps no retry ladder of its own.
|
|
2698
|
+
// `heartbeat` is offered by default (the idle watchdog's proof of life).
|
|
2699
|
+
capabilities: { rewake: true },
|
|
2196
2700
|
reconnect: true,
|
|
2197
2701
|
reconnectInterval: config.reconnect.initialBackoffMs,
|
|
2198
2702
|
maxReconnectInterval: config.reconnect.maxBackoffMs,
|
|
@@ -2201,169 +2705,118 @@ function realtimeOptionsFor(config, extra = {}) {
|
|
|
2201
2705
|
};
|
|
2202
2706
|
}
|
|
2203
2707
|
var IntegrationSocket = class {
|
|
2204
|
-
|
|
2708
|
+
/** The SDK client: handed to the receive loop, which connects and disconnects it. */
|
|
2709
|
+
realtime;
|
|
2205
2710
|
logger;
|
|
2206
2711
|
handlers;
|
|
2207
2712
|
metrics;
|
|
2208
|
-
client;
|
|
2209
|
-
createRealtime;
|
|
2210
|
-
webSocket;
|
|
2211
2713
|
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. */
|
|
2714
|
+
/** The SDK's state as last reported through its `state` event. */
|
|
2215
2715
|
state = "idle";
|
|
2216
2716
|
connectedAt = null;
|
|
2717
|
+
bound = false;
|
|
2217
2718
|
stopping = false;
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
wakes = 0;
|
|
2221
|
-
invites = 0;
|
|
2719
|
+
unbind = [];
|
|
2720
|
+
wakeFrames = 0;
|
|
2222
2721
|
disconnects = 0;
|
|
2223
2722
|
constructor(options) {
|
|
2224
|
-
this.config = options.config;
|
|
2225
2723
|
this.logger = options.logger.child({ component: "socket" });
|
|
2226
2724
|
this.handlers = options.handlers ?? {};
|
|
2227
2725
|
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
2726
|
this.now = options.now ?? Date.now;
|
|
2232
|
-
|
|
2727
|
+
const create = options.createRealtime ?? ((opts) => new RealtimeClient(opts));
|
|
2728
|
+
this.realtime = create(realtimeOptionsFor(options.config, { client: options.client, webSocket: options.webSocket }));
|
|
2233
2729
|
this.metrics.setConnectionState(this.state);
|
|
2234
2730
|
}
|
|
2235
|
-
/**
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2731
|
+
/** Attach the lifecycle handlers. Idempotent. The receive loop connects the client. */
|
|
2732
|
+
bind() {
|
|
2733
|
+
if (this.bound || this.stopping) return;
|
|
2734
|
+
this.bound = true;
|
|
2735
|
+
const realtime = this.realtime;
|
|
2736
|
+
this.unbind.push(
|
|
2737
|
+
realtime.on("state", (next, prev) => this.onState(next, prev)),
|
|
2738
|
+
realtime.onConnect(() => {
|
|
2739
|
+
const at = this.now();
|
|
2740
|
+
this.connectedAt = at;
|
|
2741
|
+
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2742
|
+
this.metrics.incWake({ source: "connect" });
|
|
2743
|
+
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2744
|
+
}),
|
|
2745
|
+
realtime.onDisconnect((info) => {
|
|
2746
|
+
if (this.stopping) return;
|
|
2747
|
+
this.disconnects += 1;
|
|
2748
|
+
this.connectedAt = null;
|
|
2749
|
+
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2750
|
+
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2751
|
+
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2752
|
+
}),
|
|
2753
|
+
realtime.on("blocked", (info) => {
|
|
2754
|
+
if (this.stopping) return;
|
|
2755
|
+
this.metrics.incError({ errorClass: "auth" });
|
|
2756
|
+
this.logger.warn(
|
|
2757
|
+
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2758
|
+
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2759
|
+
);
|
|
2760
|
+
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2761
|
+
}),
|
|
2762
|
+
realtime.onError((error) => {
|
|
2763
|
+
if (this.stopping) return;
|
|
2764
|
+
if (realtime.state === "blocked") {
|
|
2765
|
+
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2766
|
+
return;
|
|
2767
|
+
}
|
|
2768
|
+
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2769
|
+
this.logger.debug({ err: error.message }, "socket error");
|
|
2770
|
+
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2771
|
+
}),
|
|
2772
|
+
// The loop turns a wake frame into a cycle; here it is only labelled
|
|
2773
|
+
// by its reason for the log line and the metric.
|
|
2774
|
+
realtime.on("wake", (frame) => {
|
|
2775
|
+
this.wakeFrames += 1;
|
|
2776
|
+
const payload = frame.payload ?? {};
|
|
2777
|
+
const conversations = Array.isArray(payload.conversation_ids) ? payload.conversation_ids.length : void 0;
|
|
2778
|
+
this.metrics.incWake({ source: wakeSourceOf(payload.reason) });
|
|
2779
|
+
this.logger.info(
|
|
2780
|
+
{
|
|
2781
|
+
reason: payload.reason,
|
|
2782
|
+
step: payload.step,
|
|
2783
|
+
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2784
|
+
...conversations !== void 0 ? { conversations } : {}
|
|
2785
|
+
},
|
|
2786
|
+
"wake \u2014 server wake frame"
|
|
2787
|
+
);
|
|
2788
|
+
})
|
|
2789
|
+
);
|
|
2250
2790
|
}
|
|
2251
|
-
/**
|
|
2252
|
-
|
|
2791
|
+
/** The loop has disconnected the client (or never started it): report `stopped`, detach. Idempotent. */
|
|
2792
|
+
stopped() {
|
|
2253
2793
|
this.stopping = true;
|
|
2254
|
-
const realtime = this.realtime;
|
|
2255
|
-
this.realtime = null;
|
|
2256
2794
|
this.connectedAt = null;
|
|
2257
|
-
|
|
2795
|
+
for (const off of this.unbind.splice(0)) {
|
|
2258
2796
|
try {
|
|
2259
|
-
|
|
2260
|
-
} catch
|
|
2261
|
-
this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
|
|
2797
|
+
off();
|
|
2798
|
+
} catch {
|
|
2262
2799
|
}
|
|
2263
2800
|
}
|
|
2264
2801
|
if (this.state !== "stopped") this.onState("stopped", this.state);
|
|
2265
2802
|
}
|
|
2266
2803
|
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));
|
|
2804
|
+
return { state: this.state, connectedAt: this.connectedAt, counters: { wakeFrames: this.wakeFrames, disconnects: this.disconnects } };
|
|
2353
2805
|
}
|
|
2354
2806
|
/** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
|
|
2355
2807
|
onState(next, prev) {
|
|
2808
|
+
if (this.state === next) return;
|
|
2356
2809
|
this.state = next;
|
|
2357
2810
|
this.metrics.setConnectionState(next);
|
|
2358
2811
|
this.logger.debug({ from: prev, to: next }, "socket state");
|
|
2359
2812
|
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2360
2813
|
}
|
|
2361
|
-
/** A failing handler never takes the socket down
|
|
2814
|
+
/** A failing handler never takes the socket down. */
|
|
2362
2815
|
guard(name, fn) {
|
|
2363
2816
|
try {
|
|
2364
2817
|
fn();
|
|
2365
2818
|
} catch (err) {
|
|
2366
|
-
this.logger.error({ err:
|
|
2819
|
+
this.logger.error({ err: describe4(err), handler: name }, "handler threw \u2014 continuing");
|
|
2367
2820
|
}
|
|
2368
2821
|
}
|
|
2369
2822
|
};
|
|
@@ -2374,7 +2827,7 @@ function classifyRealtimeError(error) {
|
|
|
2374
2827
|
if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
|
|
2375
2828
|
return "other";
|
|
2376
2829
|
}
|
|
2377
|
-
function
|
|
2830
|
+
function describe4(err) {
|
|
2378
2831
|
return err instanceof Error ? err.message : String(err);
|
|
2379
2832
|
}
|
|
2380
2833
|
|
|
@@ -2404,8 +2857,6 @@ function registerIntegration(params) {
|
|
|
2404
2857
|
}
|
|
2405
2858
|
let built = null;
|
|
2406
2859
|
const handlers = {
|
|
2407
|
-
onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
|
|
2408
|
-
onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
|
|
2409
2860
|
onConnected: (at) => built?.handlers.onConnected?.(at),
|
|
2410
2861
|
onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
|
|
2411
2862
|
onBlocked: (info) => built?.handlers.onBlocked?.(info),
|
|
@@ -2417,19 +2868,20 @@ function registerIntegration(params) {
|
|
|
2417
2868
|
built = params.build(socket);
|
|
2418
2869
|
const entry = {
|
|
2419
2870
|
socket,
|
|
2420
|
-
|
|
2871
|
+
loop: built.loop,
|
|
2421
2872
|
texts: built.texts ?? null,
|
|
2873
|
+
textsCache: built.textsCache ?? null,
|
|
2422
2874
|
metrics: params.socketOptions?.metrics ?? null,
|
|
2423
2875
|
config: params.config,
|
|
2424
2876
|
logger: params.logger
|
|
2425
2877
|
};
|
|
2426
2878
|
registry.set(params.accountId, entry);
|
|
2879
|
+
socket.bind();
|
|
2427
2880
|
try {
|
|
2428
|
-
await
|
|
2881
|
+
await built.loop?.loop.start();
|
|
2429
2882
|
} catch (err) {
|
|
2430
2883
|
registry.delete(params.accountId);
|
|
2431
|
-
|
|
2432
|
-
built.texts?.stop();
|
|
2884
|
+
await stopEntry(entry);
|
|
2433
2885
|
throw err;
|
|
2434
2886
|
}
|
|
2435
2887
|
return entry;
|
|
@@ -2444,557 +2896,272 @@ function unregisterIntegration(accountId) {
|
|
|
2444
2896
|
});
|
|
2445
2897
|
}
|
|
2446
2898
|
async function stopEntry(entry) {
|
|
2447
|
-
entry.invoker?.stop();
|
|
2448
|
-
entry.texts?.stop();
|
|
2449
2899
|
try {
|
|
2450
|
-
await entry.
|
|
2900
|
+
await entry.loop?.stop();
|
|
2451
2901
|
} catch (err) {
|
|
2452
|
-
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "
|
|
2902
|
+
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "receive loop stop threw during unregister");
|
|
2453
2903
|
}
|
|
2454
|
-
|
|
2455
|
-
function getIntegration(accountId) {
|
|
2456
|
-
return registry.get(accountId);
|
|
2457
|
-
}
|
|
2458
|
-
|
|
2459
|
-
// src/integration/wake.ts
|
|
2460
|
-
var DEFAULT_DEBOUNCE_MS = 2e3;
|
|
2461
|
-
var DEFAULT_MAX_WINDOW_MS = 6e3;
|
|
2462
|
-
var WakeCoalescer = class {
|
|
2463
|
-
onFire;
|
|
2464
|
-
onDelayedWake;
|
|
2465
|
-
debounceMs;
|
|
2466
|
-
maxWindowMs;
|
|
2467
|
-
now;
|
|
2468
|
-
_setTimeout;
|
|
2469
|
-
_clearTimeout;
|
|
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;
|
|
2904
|
+
if (!entry.loop) {
|
|
2560
2905
|
try {
|
|
2561
|
-
|
|
2906
|
+
entry.socket.realtime.disconnect();
|
|
2562
2907
|
} catch {
|
|
2563
2908
|
}
|
|
2564
2909
|
}
|
|
2565
|
-
|
|
2910
|
+
entry.socket.stopped();
|
|
2911
|
+
entry.textsCache?.stop();
|
|
2912
|
+
}
|
|
2913
|
+
function getIntegration(accountId) {
|
|
2914
|
+
return registry.get(accountId);
|
|
2915
|
+
}
|
|
2916
|
+
function listActiveAccounts() {
|
|
2917
|
+
return [...registry.keys()];
|
|
2918
|
+
}
|
|
2566
2919
|
|
|
2567
|
-
// src/integration/
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
texts;
|
|
2576
|
-
invites;
|
|
2577
|
-
logger;
|
|
2578
|
-
metrics;
|
|
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"
|
|
2651
|
-
);
|
|
2652
|
-
this.pendingInvites.push(invite);
|
|
2653
|
-
this.invitesDirty = true;
|
|
2654
|
-
this.schedule();
|
|
2655
|
-
return true;
|
|
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;
|
|
2707
|
-
}
|
|
2708
|
-
return;
|
|
2709
|
-
}
|
|
2710
|
-
}
|
|
2711
|
-
// ─── one cycle ──────────────────────────────────────────────────────
|
|
2712
|
-
/** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
|
|
2713
|
-
async runCycle() {
|
|
2714
|
-
this.cycles += 1;
|
|
2715
|
-
const started = this.now();
|
|
2716
|
-
let tray;
|
|
2717
|
-
try {
|
|
2718
|
-
tray = await this.client.inbox.tray({ waitMs: 0 });
|
|
2719
|
-
} catch (err) {
|
|
2720
|
-
this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
|
|
2721
|
-
return this.result("tray_failed", 0, false, started, describe4(err));
|
|
2722
|
-
}
|
|
2723
|
-
const allCards = gate.cardsOf(tray);
|
|
2724
|
-
const truncated = tray.truncated === true;
|
|
2725
|
-
if (allCards.length === 0) {
|
|
2726
|
-
this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
|
|
2727
|
-
this.retryRung = 0;
|
|
2728
|
-
return this.result("empty", 0, truncated, started);
|
|
2729
|
-
}
|
|
2730
|
-
const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id));
|
|
2731
|
-
const skippedInFlight = allCards.length - cards.length;
|
|
2732
|
-
if (skippedInFlight > 0) this.skippedWhileInFlight = true;
|
|
2733
|
-
if (cards.length === 0) {
|
|
2734
|
-
this.logger.info({ skippedInFlight }, "every card on the tray has a reply turn running \u2014 nothing new to decide");
|
|
2735
|
-
return { ...this.result("empty", 0, truncated, started), skippedInFlight };
|
|
2736
|
-
}
|
|
2737
|
-
const texts = await this.texts.ensure();
|
|
2738
|
-
if (!texts) {
|
|
2739
|
-
this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
2740
|
-
return { ...this.result("texts_missing", cards.length, truncated, started, "texts missing"), skippedInFlight };
|
|
2741
|
-
}
|
|
2742
|
-
const readiness = this.readiness();
|
|
2743
|
-
if (!readiness.ready) {
|
|
2744
|
-
const changed = this.unreadyReason !== readiness.reason;
|
|
2745
|
-
this.unreadyReason = readiness.reason;
|
|
2746
|
-
this.logger[changed ? "warn" : "debug"]({ cards: cards.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 not gating; the cards wait on the tray");
|
|
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) });
|
|
2920
|
+
// src/integration/turns.ts
|
|
2921
|
+
function createLoopTurnStarter(options) {
|
|
2922
|
+
const now = options.now ?? Date.now;
|
|
2923
|
+
return async (request) => {
|
|
2924
|
+
const id = request.kind === "reply" ? request.conversationId : request.invite.invite_id;
|
|
2925
|
+
const sessionKey = request.kind === "reply" ? wakeSessionKey(options.agentId, now()) : inviteSessionKey(options.agentId, id, now());
|
|
2926
|
+
const watch = options.turns.admission(request.kind, id);
|
|
2927
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
2773
2928
|
if (!admission.ran) {
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
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;
|
|
2929
|
+
options.turns.admitted(watch);
|
|
2930
|
+
return { started: false, error: admission.error };
|
|
2931
|
+
}
|
|
2932
|
+
options.turns.started({
|
|
2933
|
+
runId: admission.runId,
|
|
2934
|
+
kind: request.kind,
|
|
2935
|
+
id,
|
|
2936
|
+
anchor: request.kind === "reply" ? request.anchor : null,
|
|
2937
|
+
sessionKey: admission.sessionKey,
|
|
2938
|
+
startedAt: now(),
|
|
2939
|
+
owner: options.owner,
|
|
2940
|
+
// What the after-turn rule compares when the turn ends outside the
|
|
2941
|
+
// kit's watch (handed off, or after a restart).
|
|
2942
|
+
...request.kind === "reply" ? { card: request.card, category: request.category } : { invite: request.invite }
|
|
2943
|
+
}, { admission: watch });
|
|
2944
|
+
options.logger.info(
|
|
2945
|
+
{ kind: request.kind, sessionKey, runId: admission.runId, ...request.kind === "reply" ? { conversationId: id } : { inviteId: id } },
|
|
2946
|
+
request.kind === "reply" ? "turn start" : "group-invite turn start"
|
|
2947
|
+
);
|
|
2948
|
+
const done = admission.done.then((outcome) => {
|
|
2949
|
+
if (outcome.status === "gone") {
|
|
2950
|
+
options.logger.warn({ sessionKey, runId: outcome.runId }, "turn end not confirmed: the plugin runtime is gone \u2014 its card stays held");
|
|
2951
|
+
return { status: "still_running", detail: "the plugin runtime is gone" };
|
|
2814
2952
|
}
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2953
|
+
const end = turnEndOf(outcome);
|
|
2954
|
+
void options.turns.ended(admission.runId, end);
|
|
2955
|
+
options.logger[outcome.status === "ok" ? "info" : "warn"](
|
|
2956
|
+
{
|
|
2957
|
+
sessionKey,
|
|
2958
|
+
runId: outcome.runId,
|
|
2959
|
+
status: outcome.status,
|
|
2960
|
+
...outcome.error ? { error: outcome.error } : {},
|
|
2961
|
+
...outcome.elapsedMs !== void 0 ? { elapsedMs: outcome.elapsedMs } : {},
|
|
2962
|
+
agentchatCalls: outcome.agentchatCalls ?? null
|
|
2963
|
+
},
|
|
2964
|
+
request.kind === "reply" ? "turn ended (final text discarded; the send is a hosted-tool call)" : "group-invite turn ended"
|
|
2965
|
+
);
|
|
2966
|
+
return end;
|
|
2967
|
+
});
|
|
2968
|
+
return { started: true, done };
|
|
2969
|
+
};
|
|
2970
|
+
}
|
|
2971
|
+
function turnEndOf(outcome) {
|
|
2972
|
+
const agentchatCalls = outcome.agentchatCalls ?? null;
|
|
2973
|
+
if (outcome.status === "ok" && !outcome.error) return { status: "completed", agentchatCalls };
|
|
2974
|
+
return { status: "failed", agentchatCalls, detail: outcome.error ?? `run ended: ${outcome.status ?? "unknown"}` };
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
// src/integration/loop.ts
|
|
2978
|
+
var generation = 0;
|
|
2979
|
+
function createIntegrationLoop(options) {
|
|
2980
|
+
const logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
2981
|
+
const metrics = options.metrics ?? createNoopMetrics();
|
|
2982
|
+
const now = options.now ?? Date.now;
|
|
2983
|
+
generation += 1;
|
|
2984
|
+
const owner = `${options.accountId}#${generation}`;
|
|
2985
|
+
const gateEnabled = options.gateEnabled ?? true;
|
|
2986
|
+
let unreadyReason = null;
|
|
2987
|
+
const readiness = options.readiness ? () => {
|
|
2988
|
+
const ready = options.readiness();
|
|
2989
|
+
if (ready.ready) {
|
|
2990
|
+
if (unreadyReason !== null) logger.info({}, "turns can start again \u2014 gating resumes");
|
|
2991
|
+
unreadyReason = null;
|
|
2992
|
+
return ready;
|
|
2993
|
+
}
|
|
2994
|
+
if (unreadyReason !== ready.reason) logger.warn({ reason: ready.reason }, "not gating \u2014 no turn can start now; the cards wait on the tray");
|
|
2995
|
+
unreadyReason = ready.reason;
|
|
2996
|
+
return ready;
|
|
2997
|
+
} : void 0;
|
|
2998
|
+
const startTurn = createLoopTurnStarter({ accountId: options.accountId, agentId: options.agentId, startRun: options.startRun, turns: options.turns, owner, logger, now });
|
|
2999
|
+
const loop = new integration.ReceiveLoop({
|
|
3000
|
+
client: options.client,
|
|
3001
|
+
texts: options.texts,
|
|
3002
|
+
mode: gateEnabled ? "gateCall" : "singleRun",
|
|
3003
|
+
...gateEnabled ? { callModel: options.callModel, startTurn } : { startRun: singleRunStarter(options, owner, logger, now) },
|
|
3004
|
+
socket: options.socket,
|
|
3005
|
+
...options.handle ? { handle: options.handle } : {},
|
|
3006
|
+
toolNamer: OPENCLAW_TOOL_NAMER,
|
|
3007
|
+
// One account's turns run on one OpenClaw lane anyway; one slot keeps
|
|
3008
|
+
// the rest held out of the gate (no second model call decides them).
|
|
3009
|
+
maxConcurrentTurns: 1,
|
|
3010
|
+
tracker: options.turns.tracker,
|
|
3011
|
+
...readiness ? { readiness } : {},
|
|
3012
|
+
...options.paceMs !== void 0 ? { paceMs: options.paceMs } : {},
|
|
3013
|
+
...options.quietMs !== void 0 ? { quietMs: options.quietMs } : {},
|
|
3014
|
+
...options.maxMs !== void 0 ? { maxMs: options.maxMs } : {},
|
|
3015
|
+
now,
|
|
3016
|
+
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
3017
|
+
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {},
|
|
3018
|
+
onEvent: (event) => logEvent(event, logger, metrics)
|
|
3019
|
+
});
|
|
3020
|
+
const inLoopContext = AsyncLocalStorage.snapshot();
|
|
3021
|
+
options.turns.setLive(
|
|
3022
|
+
owner,
|
|
3023
|
+
() => inLoopContext(() => loop.wake()),
|
|
3024
|
+
(fn) => inLoopContext(fn)
|
|
3025
|
+
);
|
|
3026
|
+
return {
|
|
3027
|
+
loop,
|
|
3028
|
+
async stop() {
|
|
3029
|
+
options.turns.clearLive(owner);
|
|
3030
|
+
await loop.stop();
|
|
2839
3031
|
}
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
skippedInFlight: 0,
|
|
2855
|
-
truncated,
|
|
2856
|
-
latencyMs: this.now() - started,
|
|
2857
|
-
failure
|
|
3032
|
+
};
|
|
3033
|
+
}
|
|
3034
|
+
function singleRunStarter(options, owner, logger, now) {
|
|
3035
|
+
return async (request) => {
|
|
3036
|
+
const hung = options.turns.hungSingleRun();
|
|
3037
|
+
if (hung) {
|
|
3038
|
+
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)");
|
|
3039
|
+
return { status: "not_started", detail: `the gate-off run ${hung.runId} is still going` };
|
|
3040
|
+
}
|
|
3041
|
+
const sessionKey = wakeSessionKey(options.agentId, now());
|
|
3042
|
+
logger.info({ sessionKey, cards: request.cards, invites: request.invites }, "gate off \u2014 one run with the served wake instruction");
|
|
3043
|
+
const admission = await options.startRun({ sessionKey, prompt: request.prompt, lane: integrationLane(options.accountId, options.turns.laneGeneration) });
|
|
3044
|
+
if (!admission.ran) return { status: "not_started", detail: admission.error };
|
|
3045
|
+
let letGo = () => {
|
|
2858
3046
|
};
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
3047
|
+
const handedOff = new Promise((resolve) => {
|
|
3048
|
+
letGo = () => resolve("let_go");
|
|
3049
|
+
});
|
|
3050
|
+
const { runId } = admission;
|
|
3051
|
+
options.turns.started({ runId, kind: "run", id: runId, anchor: null, sessionKey: admission.sessionKey, startedAt: now(), owner }, { letGo });
|
|
3052
|
+
const ended = admission.done.then((outcome) => {
|
|
3053
|
+
if (outcome.status !== "gone") void options.turns.ended(runId);
|
|
3054
|
+
logger[outcome.status === "ok" ? "info" : "warn"]({ sessionKey, runId, status: outcome.status, agentchatCalls: outcome.agentchatCalls ?? null }, "gate off \u2014 run ended");
|
|
3055
|
+
return outcome;
|
|
3056
|
+
});
|
|
3057
|
+
const first = await Promise.race([ended, handedOff]);
|
|
3058
|
+
if (first === "let_go") {
|
|
3059
|
+
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`)");
|
|
3060
|
+
return { status: "failed", detail: "the run was handed off while still going" };
|
|
2867
3061
|
}
|
|
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
|
-
|
|
3062
|
+
return first.status === "ok" && !first.error ? { status: "completed" } : { status: "failed", detail: first.error ?? `run ended: ${first.status ?? "unknown"}` };
|
|
3063
|
+
};
|
|
3064
|
+
}
|
|
3065
|
+
function logEvent(event, logger, metrics) {
|
|
3066
|
+
switch (event.type) {
|
|
3067
|
+
case "wake":
|
|
3068
|
+
if (event.source === "message") metrics.incWake({ source: "message" });
|
|
3069
|
+
else if (event.source === "invite") metrics.incWake({ source: "invite" });
|
|
3070
|
+
logger.debug({ source: event.source, ...event.conversationId ? { conversationId: event.conversationId } : {} }, "wake");
|
|
3071
|
+
return;
|
|
3072
|
+
case "echo":
|
|
3073
|
+
logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
|
|
3074
|
+
return;
|
|
3075
|
+
case "cycle": {
|
|
3076
|
+
const s = event.summary;
|
|
3077
|
+
const fields = {
|
|
3078
|
+
outcome: s.outcome,
|
|
3079
|
+
cards: s.cards,
|
|
3080
|
+
invites: s.invites,
|
|
3081
|
+
reply: s.reply,
|
|
3082
|
+
dismiss: s.dismiss,
|
|
3083
|
+
defer: s.defer,
|
|
3084
|
+
undecided: s.undecided,
|
|
3085
|
+
recordFailures: s.recordFailures,
|
|
3086
|
+
turnsStarted: s.turnsStarted,
|
|
3087
|
+
turnsRefused: s.turnsRefused,
|
|
3088
|
+
heldByTurns: s.heldByTurns,
|
|
3089
|
+
...s.truncated ? { truncated: true } : {},
|
|
3090
|
+
...s.failure ? { failure: s.failure } : {}
|
|
3091
|
+
};
|
|
3092
|
+
switch (s.outcome) {
|
|
3093
|
+
case "empty":
|
|
3094
|
+
logger.info({}, "tray empty \u2014 nothing to decide");
|
|
3095
|
+
return;
|
|
3096
|
+
case "nothing_owed":
|
|
3097
|
+
logger.info(fields, "nothing new to decide (muted cards, or cards a running turn holds)");
|
|
3098
|
+
return;
|
|
3099
|
+
case "fail_closed":
|
|
3100
|
+
logger.warn(fields, "gate failed closed \u2014 nothing recorded, no turn started; the server re-wakes");
|
|
3101
|
+
return;
|
|
3102
|
+
case "tray_failed":
|
|
3103
|
+
logger.warn(fields, "tray read failed \u2014 the cards stay on the tray; the server re-wakes");
|
|
3104
|
+
return;
|
|
3105
|
+
case "texts_missing":
|
|
3106
|
+
logger.warn(fields, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
3107
|
+
return;
|
|
3108
|
+
case "tools_unavailable":
|
|
3109
|
+
logger.debug(fields, "not gating \u2014 no turn can start now");
|
|
3110
|
+
return;
|
|
3111
|
+
case "abandoned":
|
|
3112
|
+
logger.warn(fields, "cycle abandoned \u2014 it ran past its deadline; nothing more is done for it, the next wake starts a new one");
|
|
3113
|
+
return;
|
|
3114
|
+
default: {
|
|
3115
|
+
const incomplete = s.turnsRefused > 0 || s.recordFailures > 0 || s.undecided > 0;
|
|
3116
|
+
logger[incomplete ? "warn" : "info"](fields, incomplete ? "gate \u2014 some cards were left on the tray; the server re-wakes" : "gate");
|
|
3117
|
+
return;
|
|
2918
3118
|
}
|
|
2919
3119
|
}
|
|
2920
|
-
);
|
|
2921
|
-
}
|
|
2922
|
-
/** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
|
|
2923
|
-
replyTurnEnded(conversationId) {
|
|
2924
|
-
this.replyTurnsInFlight.delete(conversationId);
|
|
2925
|
-
if (this.skippedWhileInFlight && !this.stopped) {
|
|
2926
|
-
this.skippedWhileInFlight = false;
|
|
2927
|
-
this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
|
|
2928
|
-
this.coalescer.wake();
|
|
2929
3120
|
}
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
3121
|
+
case "turn_started":
|
|
3122
|
+
return;
|
|
3123
|
+
// the turn starter logs it with the OpenClaw session and run
|
|
3124
|
+
case "turn_refused":
|
|
3125
|
+
logger.warn({ kind: event.kind, id: event.id, error: event.error }, "turn not started \u2014 nothing recorded; the card stays on the tray");
|
|
3126
|
+
return;
|
|
3127
|
+
case "turn_outcome": {
|
|
3128
|
+
const o = event.outcome;
|
|
3129
|
+
logger.info(
|
|
3130
|
+
{ conversationId: o.conversationId, action: o.action, reason: o.reason, recorded: event.recorded, ...o.action !== "none" ? { through: o.throughMessageId } : {} },
|
|
3131
|
+
event.recorded ? `${o.action === "record_reply" ? "reply" : "dismiss"} recorded after the turn (${o.reason})` : `nothing recorded after the turn (${o.reason})`
|
|
2940
3132
|
);
|
|
3133
|
+
return;
|
|
2941
3134
|
}
|
|
3135
|
+
case "invite_outcome":
|
|
3136
|
+
logger.info(
|
|
3137
|
+
{ inviteId: event.outcome.inviteId, action: event.outcome.action, reason: event.outcome.reason, recorded: event.recorded },
|
|
3138
|
+
event.recorded ? "invite dismissed after a second silent turn (left pending)" : `nothing recorded for the invite (${event.outcome.reason})`
|
|
3139
|
+
);
|
|
3140
|
+
return;
|
|
3141
|
+
case "run":
|
|
3142
|
+
return;
|
|
3143
|
+
// single-run mode logs the run itself
|
|
3144
|
+
case "error":
|
|
3145
|
+
logger.debug({ err: event.error.message }, "receive loop notice");
|
|
3146
|
+
return;
|
|
2942
3147
|
}
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
if (batch.length > 0) {
|
|
2952
|
-
const readiness = this.readiness();
|
|
2953
|
-
if (!readiness.ready) {
|
|
2954
|
-
const changed = this.unreadyReason !== readiness.reason;
|
|
2955
|
-
this.unreadyReason = readiness.reason;
|
|
2956
|
-
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");
|
|
2957
|
-
return;
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
let texts = null;
|
|
2961
|
-
let refused = 0;
|
|
2962
|
-
let waitingForTexts = 0;
|
|
2963
|
-
for (const invite of batch) {
|
|
2964
|
-
if (this.stopped) return;
|
|
2965
|
-
texts ??= await this.texts.ensure();
|
|
2966
|
-
if (!texts) {
|
|
2967
|
-
waitingForTexts = batch.length;
|
|
2968
|
-
break;
|
|
2969
|
-
}
|
|
2970
|
-
const sessionKey = inviteSessionKey(this.agentId, invite.inviteId);
|
|
2971
|
-
this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, "group-invite turn start");
|
|
2972
|
-
let admission;
|
|
2973
|
-
try {
|
|
2974
|
-
admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2975
|
-
} catch (err) {
|
|
2976
|
-
admission = { ran: false, error: describe4(err) };
|
|
2977
|
-
}
|
|
2978
|
-
if (!admission.ran) {
|
|
2979
|
-
refused += 1;
|
|
2980
|
-
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");
|
|
2981
|
-
continue;
|
|
2982
|
-
}
|
|
2983
|
-
this.inviteTurns += 1;
|
|
2984
|
-
this.invites.markOffered(invite.inviteId);
|
|
2985
|
-
this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId);
|
|
2986
|
-
this.admitted(sessionKey, admission, "group-invite turn complete");
|
|
2987
|
-
}
|
|
2988
|
-
if (this.stopped) return;
|
|
2989
|
-
if (waitingForTexts > 0) {
|
|
2990
|
-
this.logger.warn({ pending: waitingForTexts, ...this.retry() }, "served texts not available \u2014 invite turns wait; re-waking later");
|
|
2991
|
-
} else if (refused > 0) {
|
|
2992
|
-
this.logger.warn({ pending: refused, ...this.retry() }, "invite turns refused \u2014 re-waking later");
|
|
2993
|
-
}
|
|
2994
|
-
}
|
|
3148
|
+
}
|
|
3149
|
+
var TROUBLE_OUTCOMES = /* @__PURE__ */ new Set(["fail_closed", "tools_unavailable", "texts_missing", "abandoned"]);
|
|
3150
|
+
var CYCLE_TROUBLE_RUN = 3;
|
|
3151
|
+
var TROUBLE_MEANING = {
|
|
3152
|
+
fail_closed: "the gate call failed (model unreachable, too slow, or nothing usable)",
|
|
3153
|
+
tools_unavailable: "no turn could have the hosted tools",
|
|
3154
|
+
texts_missing: "the served texts are not available",
|
|
3155
|
+
abandoned: "the cycle ran past its deadline and was abandoned"
|
|
2995
3156
|
};
|
|
2996
|
-
function
|
|
2997
|
-
|
|
3157
|
+
function cycleTroubleLine(recentCycles) {
|
|
3158
|
+
let run = 0;
|
|
3159
|
+
for (let i = recentCycles.length - 1; i >= 0 && TROUBLE_OUTCOMES.has(recentCycles[i].outcome); i -= 1) run += 1;
|
|
3160
|
+
if (run < CYCLE_TROUBLE_RUN) return null;
|
|
3161
|
+
const last = recentCycles[recentCycles.length - 1];
|
|
3162
|
+
const kinds = [...new Set(recentCycles.slice(-run).map((c) => c.outcome))];
|
|
3163
|
+
const meaning = kinds.map((k) => TROUBLE_MEANING[k] ?? k).join("; ");
|
|
3164
|
+
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`;
|
|
2998
3165
|
}
|
|
2999
3166
|
function adaptLog(log) {
|
|
3000
3167
|
if (!log) return void 0;
|
|
@@ -3052,7 +3219,7 @@ var agentchatGatewayAdapter = {
|
|
|
3052
3219
|
}
|
|
3053
3220
|
if (readLegacyReplyGateFailOpenFromEnv()) {
|
|
3054
3221
|
ctx.log?.warn?.(
|
|
3055
|
-
`[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)
|
|
3222
|
+
`[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`
|
|
3056
3223
|
);
|
|
3057
3224
|
}
|
|
3058
3225
|
const refusal = multiAccountRefusal(ctx.cfg);
|
|
@@ -3074,20 +3241,57 @@ var agentchatGatewayAdapter = {
|
|
|
3074
3241
|
}
|
|
3075
3242
|
const client = getClient({ accountId: ctx.accountId, config });
|
|
3076
3243
|
const gateTimeoutMs = readReplyGateTimeoutMsFromEnv();
|
|
3077
|
-
const
|
|
3244
|
+
const overdueWarned = /* @__PURE__ */ new Map();
|
|
3245
|
+
const turns = accountTurns(ctx.accountId);
|
|
3246
|
+
const reportOverdue = (runId, kind, id, elapsedMs, handed) => {
|
|
3247
|
+
const mark = Math.floor((elapsedMs + OVERDUE_SLACK_MS) / TURN_OVERDUE_MS);
|
|
3248
|
+
if (!handed && overdueWarned.get(runId) === mark) return;
|
|
3249
|
+
overdueWarned.set(runId, mark);
|
|
3250
|
+
ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${overdueTurnLine({ kind, id, elapsedMs }, readLiveConfig(ctx.cfg).cfg)}`);
|
|
3251
|
+
};
|
|
3252
|
+
const onStillRunning = ({ runId, sessionKey, elapsedMs }) => {
|
|
3253
|
+
const run = turns.run(runId);
|
|
3254
|
+
if (turns.stateOf(runId) === "released") {
|
|
3255
|
+
logger.debug({ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4) }, "released turn still running in OpenClaw \u2014 it holds nothing");
|
|
3256
|
+
return;
|
|
3257
|
+
}
|
|
3258
|
+
logger.info(
|
|
3259
|
+
{ runId, sessionKey, elapsedMin: Math.round(elapsedMs / 6e4), ...run ? { [run.kind === "reply" ? "conversationId" : run.kind === "invite" ? "inviteId" : "run"]: run.id } : {} },
|
|
3260
|
+
"turn still running \u2014 its conversation stays in flight until OpenClaw reports the run ended"
|
|
3261
|
+
);
|
|
3262
|
+
if (!run || !isOverdue(elapsedMs)) return;
|
|
3263
|
+
const handed = turns.handOff(runId) !== null;
|
|
3264
|
+
reportOverdue(runId, run.kind, run.id, elapsedMs, handed);
|
|
3265
|
+
};
|
|
3266
|
+
const watchRun = createRunWatcher({ onStillRunning });
|
|
3267
|
+
turns.configure({
|
|
3268
|
+
recorder: createAfterTurnRecorder({ client, logger }),
|
|
3269
|
+
store: new TurnStore(ctx.accountId),
|
|
3270
|
+
watch: async (record) => {
|
|
3271
|
+
const outcome = await watchRun(record);
|
|
3272
|
+
return outcome ? turnEndOf(outcome) : null;
|
|
3273
|
+
},
|
|
3274
|
+
readCalls: (sessionKey, runId) => readAgentChatCalls(getPluginRuntime(), sessionKey, runId),
|
|
3275
|
+
logger
|
|
3276
|
+
});
|
|
3277
|
+
turns.adopt();
|
|
3278
|
+
for (const line of restartHoldLines(turns)) ctx.log?.warn?.(`[agentchat:${ctx.accountId}] ${line}`);
|
|
3279
|
+
for (const file of removeOldStateFiles(ctx.accountId)) logger.info({ file }, "removed a file an earlier release kept (no longer used)");
|
|
3280
|
+
const textsCache = createTextsCache({ client, accountId: ctx.accountId, logger });
|
|
3281
|
+
const texts = new OpenClawTexts(textsCache);
|
|
3282
|
+
const first = await textsCache.start();
|
|
3283
|
+
if (first) logger.info({ version: first.version, manual: first.manual?.version, source: textsCache.source }, "served texts in hand");
|
|
3284
|
+
else logger.warn({ err: textsCache.lastError }, "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 nothing is gated until the first copy arrives");
|
|
3078
3285
|
const handle = config.agentHandle;
|
|
3079
3286
|
if (handle) {
|
|
3080
|
-
|
|
3081
|
-
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
|
|
3287
|
+
const refresh = (copy) => {
|
|
3288
|
+
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, spellTextsForOpenClaw(copy).identity_line);
|
|
3082
3289
|
if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
|
|
3083
3290
|
else if (refreshed.outcome === "failed") ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? "unknown error"}`);
|
|
3084
|
-
}
|
|
3291
|
+
};
|
|
3292
|
+
if (first) refresh(first);
|
|
3293
|
+
textsCache.onChange((copy) => refresh(copy));
|
|
3085
3294
|
}
|
|
3086
|
-
await texts.start();
|
|
3087
|
-
const invites = new InviteLedger({
|
|
3088
|
-
accountId: ctx.accountId,
|
|
3089
|
-
onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
|
|
3090
|
-
});
|
|
3091
3295
|
const metrics = createInMemoryMetrics();
|
|
3092
3296
|
await registerIntegration({
|
|
3093
3297
|
accountId: ctx.accountId,
|
|
@@ -3095,33 +3299,44 @@ var agentchatGatewayAdapter = {
|
|
|
3095
3299
|
logger,
|
|
3096
3300
|
socketOptions: { client, metrics },
|
|
3097
3301
|
build: (socket) => {
|
|
3098
|
-
const
|
|
3302
|
+
const loop = createIntegrationLoop({
|
|
3099
3303
|
accountId: ctx.accountId,
|
|
3100
3304
|
agentId,
|
|
3101
3305
|
client,
|
|
3306
|
+
texts,
|
|
3307
|
+
socket: socket.realtime,
|
|
3308
|
+
handle: config.agentHandle,
|
|
3102
3309
|
callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
|
|
3103
|
-
|
|
3310
|
+
// A turn holds its conversation until OpenClaw confirms its run
|
|
3311
|
+
// ended; a wait that elapses is asked again (`integration/run.ts`).
|
|
3312
|
+
startRun: createRuntimeTurnStarter({
|
|
3313
|
+
onStillRunning,
|
|
3314
|
+
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")
|
|
3315
|
+
}),
|
|
3104
3316
|
// Gating waits until a turn can have the hosted tools (the MCP
|
|
3105
3317
|
// entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
|
|
3106
3318
|
// its key in this process): a connect wake on a cold gateway
|
|
3107
3319
|
// otherwise spends a gate call and runs a turn that cannot look.
|
|
3108
3320
|
readiness: () => {
|
|
3109
3321
|
const live = readLiveConfig(ctx.cfg);
|
|
3322
|
+
const hung = hungTurnsReason(turns, live.cfg);
|
|
3323
|
+
if (hung) return { ready: false, reason: hung };
|
|
3110
3324
|
return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
|
|
3111
3325
|
},
|
|
3112
|
-
|
|
3113
|
-
|
|
3326
|
+
// The account's runs outlive this loop: a config change restarts
|
|
3327
|
+
// the account while its runs go on in OpenClaw, so every loop for
|
|
3328
|
+
// the account shares the same turns (and the kit tracker in them).
|
|
3329
|
+
turns,
|
|
3114
3330
|
logger,
|
|
3115
3331
|
metrics,
|
|
3116
3332
|
gateEnabled: readReplyGateEnabledFromEnv()
|
|
3117
3333
|
});
|
|
3118
3334
|
let blocked = false;
|
|
3119
3335
|
return {
|
|
3120
|
-
|
|
3336
|
+
loop,
|
|
3121
3337
|
texts,
|
|
3338
|
+
textsCache,
|
|
3122
3339
|
handlers: {
|
|
3123
|
-
onWake: (source) => invoker.wake(source),
|
|
3124
|
-
onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
|
|
3125
3340
|
onConnected: (at) => {
|
|
3126
3341
|
if (blocked) {
|
|
3127
3342
|
blocked = false;
|
|
@@ -3129,7 +3344,6 @@ var agentchatGatewayAdapter = {
|
|
|
3129
3344
|
}
|
|
3130
3345
|
ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
|
|
3131
3346
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: "linked", lastConnectedAt: at }, "ready"));
|
|
3132
|
-
void catchUpInvites(ctx.accountId, client, invoker, logger);
|
|
3133
3347
|
},
|
|
3134
3348
|
onBlocked: (info) => {
|
|
3135
3349
|
const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
|
|
@@ -3185,23 +3399,6 @@ var agentchatGatewayAdapter = {
|
|
|
3185
3399
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
|
|
3186
3400
|
}
|
|
3187
3401
|
};
|
|
3188
|
-
async function catchUpInvites(accountId, client, invoker, logger) {
|
|
3189
|
-
try {
|
|
3190
|
-
const invites = await client.listGroupInvites();
|
|
3191
|
-
if (!Array.isArray(invites)) return;
|
|
3192
|
-
let surfaced = 0;
|
|
3193
|
-
for (const row of invites) {
|
|
3194
|
-
const invite = groupInviteFromRecord(row);
|
|
3195
|
-
if (invite && invoker.groupInvite(invite, "catch-up")) surfaced += 1;
|
|
3196
|
-
}
|
|
3197
|
-
if (surfaced > 0) logger.info({ accountId, surfaced }, "pending group invites surfaced on connect");
|
|
3198
|
-
} catch (err) {
|
|
3199
|
-
logger.warn(
|
|
3200
|
-
{ accountId, err: err instanceof Error ? err.message : String(err) },
|
|
3201
|
-
"pending-invite catch-up failed \u2014 live invite frames are unaffected and the agent can still list invites with the hosted tools"
|
|
3202
|
-
);
|
|
3203
|
-
}
|
|
3204
|
-
}
|
|
3205
3402
|
var PROBE_MIN_MS = 1e3;
|
|
3206
3403
|
var PROBE_MAX_MS = 1e4;
|
|
3207
3404
|
function formatCounts(counts) {
|
|
@@ -3243,15 +3440,27 @@ var agentchatStatusAdapter = {
|
|
|
3243
3440
|
const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
|
|
3244
3441
|
const live = getIntegration(account.accountId);
|
|
3245
3442
|
const health = live?.socket.getHealth();
|
|
3246
|
-
const
|
|
3247
|
-
const
|
|
3443
|
+
const loopStatus = live?.loop?.loop.status();
|
|
3444
|
+
const counters = loopStatus ? {
|
|
3445
|
+
wakes: loopStatus.coalescer.wakes,
|
|
3446
|
+
cycles: loopStatus.coalescer.cycles,
|
|
3447
|
+
turns: loopStatus.counters.turnsStarted + loopStatus.counters.inviteTurnsStarted + loopStatus.counters.runsStarted
|
|
3448
|
+
} : void 0;
|
|
3449
|
+
const turnsHere = live ? findAccountTurns(account.accountId) ?? null : null;
|
|
3450
|
+
const hungReason = turnsHere ? hungTurnsReason(turnsHere, cfg) : null;
|
|
3451
|
+
const overdue = turnsHere ? [...hungReason ? [hungReason] : [], ...overdueTurnLines(turnsHere.runningRuns(), cfg), ...restartHoldLines(turnsHere)] : [];
|
|
3452
|
+
const trouble = loopStatus ? cycleTroubleLine(loopStatus.recentCycles ?? []) : null;
|
|
3453
|
+
const servedFrom = live?.texts?.source;
|
|
3454
|
+
const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
|
|
3248
3455
|
const socketCounters = live?.metrics?.snapshot?.();
|
|
3249
|
-
const
|
|
3456
|
+
const integration6 = {
|
|
3250
3457
|
mode: readWakeModeFromEnv().mode,
|
|
3251
3458
|
...health ? { state: health.state } : {},
|
|
3252
3459
|
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
3253
3460
|
...textsSource ? { texts: textsSource } : {},
|
|
3254
|
-
...socketCounters ? { socket: socketCounters } : {}
|
|
3461
|
+
...socketCounters ? { socket: socketCounters } : {},
|
|
3462
|
+
...overdue.length > 0 ? { overdue } : {},
|
|
3463
|
+
...trouble ? { trouble } : {}
|
|
3255
3464
|
};
|
|
3256
3465
|
const refusal = multiAccountRefusal(cfg);
|
|
3257
3466
|
return {
|
|
@@ -3261,7 +3470,7 @@ var agentchatStatusAdapter = {
|
|
|
3261
3470
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3262
3471
|
mcp,
|
|
3263
3472
|
placement,
|
|
3264
|
-
integration,
|
|
3473
|
+
integration: integration6,
|
|
3265
3474
|
...refusal ? { refusal } : {},
|
|
3266
3475
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3267
3476
|
};
|
|
@@ -3299,6 +3508,8 @@ var agentchatStatusAdapter = {
|
|
|
3299
3508
|
tone: "muted"
|
|
3300
3509
|
});
|
|
3301
3510
|
}
|
|
3511
|
+
if (d.trouble) lines.push({ text: d.trouble, tone: "warn" });
|
|
3512
|
+
for (const line of d.overdue ?? []) lines.push({ text: line, tone: "warn" });
|
|
3302
3513
|
if (d.texts === "missing") {
|
|
3303
3514
|
lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
|
|
3304
3515
|
} else if (d.texts === "cache") {
|
|
@@ -3342,6 +3553,18 @@ var agentchatDoctorAdapter = {
|
|
|
3342
3553
|
);
|
|
3343
3554
|
}
|
|
3344
3555
|
}
|
|
3556
|
+
for (const accountId of listActiveAccounts()) {
|
|
3557
|
+
const status = getIntegration(accountId)?.loop?.loop.status();
|
|
3558
|
+
if (!status) continue;
|
|
3559
|
+
const turns = findAccountTurns(accountId);
|
|
3560
|
+
if (turns) {
|
|
3561
|
+
const hung = hungTurnsReason(turns, cfg);
|
|
3562
|
+
if (hung) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${hung}`);
|
|
3563
|
+
for (const line of [...overdueTurnLines(turns.runningRuns(), cfg), ...restartHoldLines(turns)]) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${line}`);
|
|
3564
|
+
}
|
|
3565
|
+
const trouble = cycleTroubleLine(status.recentCycles ?? []);
|
|
3566
|
+
if (trouble) warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${trouble}`);
|
|
3567
|
+
}
|
|
3345
3568
|
return warnings;
|
|
3346
3569
|
},
|
|
3347
3570
|
async repairConfig({ cfg }) {
|
|
@@ -3636,9 +3859,9 @@ var agentchatPlugin = {
|
|
|
3636
3859
|
listAccountIds(cfg) {
|
|
3637
3860
|
const section = readChannelSection(cfg);
|
|
3638
3861
|
if (!section) return [];
|
|
3639
|
-
const { accounts } = section;
|
|
3640
|
-
if (
|
|
3641
|
-
const ids = Object.keys(
|
|
3862
|
+
const { accounts: accounts2 } = section;
|
|
3863
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
3864
|
+
const ids = Object.keys(accounts2);
|
|
3642
3865
|
if (ids.length > 0) return ids;
|
|
3643
3866
|
}
|
|
3644
3867
|
const hasFlatFields = typeof section.apiKey === "string" || typeof section.apiBase === "string" || typeof section.agentHandle === "string";
|
|
@@ -3678,9 +3901,9 @@ var agentchatPlugin = {
|
|
|
3678
3901
|
hasConfiguredState({ cfg }) {
|
|
3679
3902
|
const section = readChannelSection(cfg);
|
|
3680
3903
|
if (!section) return false;
|
|
3681
|
-
const { accounts } = section;
|
|
3682
|
-
if (
|
|
3683
|
-
for (const entry of Object.values(
|
|
3904
|
+
const { accounts: accounts2 } = section;
|
|
3905
|
+
if (accounts2 && typeof accounts2 === "object" && !Array.isArray(accounts2)) {
|
|
3906
|
+
for (const entry of Object.values(accounts2)) {
|
|
3684
3907
|
if (entry && typeof entry === "object") {
|
|
3685
3908
|
const candidate = entry.apiKey;
|
|
3686
3909
|
if (isApiKeyPresent(candidate)) return true;
|
|
@@ -3724,7 +3947,15 @@ var agentchatChannelEntry = defineChannelPluginEntry({
|
|
|
3724
3947
|
// (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
|
|
3725
3948
|
// The integration reads `runtime.llm.complete` (the gate on the agent's own
|
|
3726
3949
|
// model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
|
|
3727
|
-
setRuntime: (runtime) => setPluginRuntime(runtime)
|
|
3950
|
+
setRuntime: (runtime) => setPluginRuntime(runtime),
|
|
3951
|
+
// `openclaw agentchat release <conversation_id>`: the CLI half is
|
|
3952
|
+
// registered for every CLI (parse-time metadata), the gateway half only
|
|
3953
|
+
// where the integration runs.
|
|
3954
|
+
registerCliMetadata: (api) => registerReleaseCli(api),
|
|
3955
|
+
registerFull: (api) => {
|
|
3956
|
+
registerReleaseGatewayMethod(api);
|
|
3957
|
+
registerRunObserver(api);
|
|
3958
|
+
}
|
|
3728
3959
|
});
|
|
3729
3960
|
var agentchatSetupEntry = defineSetupPluginEntry(agentchatPlugin);
|
|
3730
3961
|
|
|
@@ -3738,6 +3969,6 @@ function hasAgentChatConfiguredState(config) {
|
|
|
3738
3969
|
return true;
|
|
3739
3970
|
}
|
|
3740
3971
|
|
|
3741
|
-
export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError,
|
|
3972
|
+
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 };
|
|
3742
3973
|
//# sourceMappingURL=index.js.map
|
|
3743
3974
|
//# sourceMappingURL=index.js.map
|