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