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