@agentchatme/openclaw 0.10.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/README.md +7 -6
- package/RUNBOOK.md +4 -3
- package/dist/binding/agents-anchor.cjs.map +1 -1
- package/dist/binding/agents-anchor.d.cts +1 -1
- package/dist/binding/agents-anchor.d.ts +1 -1
- package/dist/binding/agents-anchor.js.map +1 -1
- package/dist/index.cjs +577 -810
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -189
- package/dist/index.d.ts +31 -189
- package/dist/index.js +577 -806
- package/dist/index.js.map +1 -1
- package/dist/setup-entry.cjs +560 -781
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.js +561 -782
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +5 -5
- package/package.json +2 -2
- package/skills/agentchat/SKILL.md +77 -40
package/dist/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
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 {
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { integration, AgentChatClient, ConnectionError, RealtimeClient } from 'agentchatme';
|
|
6
|
+
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';
|
|
5
7
|
import { readApiKeyFromEnv } from './credentials/read-env.js';
|
|
6
8
|
import * as fs from 'fs';
|
|
7
9
|
import * as path2 from 'path';
|
|
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';
|
|
9
10
|
import { resolveBoundAgentId, resolveOpenClawDefaultAgentId, resolveOpenClawStateDir } from './openclaw-layout.js';
|
|
10
11
|
import { removeAgentsAnchor, agentsAnchorPath, hasAgentsAnchorFor, writeAgentsAnchor, readAgentsAnchor } from './binding/agents-anchor.js';
|
|
11
12
|
import { z } from 'zod';
|
|
@@ -105,22 +106,8 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
|
|
|
105
106
|
return { ...cfg ?? {}, channels };
|
|
106
107
|
}
|
|
107
108
|
|
|
108
|
-
// src/errors.ts
|
|
109
|
-
var AgentChatChannelError = class extends Error {
|
|
110
|
-
class_;
|
|
111
|
-
retryAfterMs;
|
|
112
|
-
statusCode;
|
|
113
|
-
constructor(class_, message, options = {}) {
|
|
114
|
-
super(message, { cause: options.cause });
|
|
115
|
-
this.name = "AgentChatChannelError";
|
|
116
|
-
this.class_ = class_;
|
|
117
|
-
this.retryAfterMs = options.retryAfterMs;
|
|
118
|
-
this.statusCode = options.statusCode;
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
|
|
122
109
|
// src/version.ts
|
|
123
|
-
var PACKAGE_VERSION = "0.
|
|
110
|
+
var PACKAGE_VERSION = "0.11.0";
|
|
124
111
|
|
|
125
112
|
// src/client-identity.ts
|
|
126
113
|
var AGENTCHAT_CLIENT_NAME = "openclaw";
|
|
@@ -129,227 +116,6 @@ var AGENTCHAT_CLIENT_IDENTITY = {
|
|
|
129
116
|
version: PACKAGE_VERSION
|
|
130
117
|
};
|
|
131
118
|
|
|
132
|
-
// src/setup-client.ts
|
|
133
|
-
var DEFAULT_API_BASE = "https://api.agentchat.me";
|
|
134
|
-
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
135
|
-
async function validateApiKey(apiKey, opts = {}) {
|
|
136
|
-
if (!apiKey || typeof apiKey !== "string") {
|
|
137
|
-
return { ok: false, reason: "unauthorized", message: "API key is empty" };
|
|
138
|
-
}
|
|
139
|
-
const client = new AgentChatClient({
|
|
140
|
-
apiKey,
|
|
141
|
-
baseUrl: apiBaseOf(opts.apiBase),
|
|
142
|
-
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
143
|
-
timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
144
|
-
retry: ONE_ATTEMPT,
|
|
145
|
-
...opts.fetch ? { fetch: opts.fetch } : {}
|
|
146
|
-
});
|
|
147
|
-
let me;
|
|
148
|
-
try {
|
|
149
|
-
me = await client.getMe();
|
|
150
|
-
} catch (err) {
|
|
151
|
-
const failure = describeFailure(err);
|
|
152
|
-
if (failure.kind === "network") {
|
|
153
|
-
const unreachable = failure.timedOut || /ECONN|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(failure.message);
|
|
154
|
-
return {
|
|
155
|
-
ok: false,
|
|
156
|
-
reason: unreachable ? "unreachable" : "network-error",
|
|
157
|
-
message: `agentchat: GET /v1/agents/me failed: ${failure.message}`
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
const status = failure.status;
|
|
161
|
-
if (status === 401) return { ok: false, reason: "unauthorized", status, message: "API key is invalid or revoked" };
|
|
162
|
-
if (status === 403) return { ok: false, reason: "forbidden", status, message: "API key lacks permission to read /agents/me" };
|
|
163
|
-
if (status === 410) return { ok: false, reason: "deleted", status, message: "Agent account has been deleted" };
|
|
164
|
-
return { ok: false, reason: "server-error", status, message: `AgentChat API returned ${status}` };
|
|
165
|
-
}
|
|
166
|
-
const body = asRecord(me);
|
|
167
|
-
const email = typeof body?.email === "string" ? body.email : typeof body?.email_masked === "string" ? body.email_masked : null;
|
|
168
|
-
if (!body || typeof body.handle !== "string" || email === null || typeof body.created_at !== "string") {
|
|
169
|
-
return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/me returned an unrecognized shape" };
|
|
170
|
-
}
|
|
171
|
-
return {
|
|
172
|
-
ok: true,
|
|
173
|
-
agent: {
|
|
174
|
-
handle: body.handle,
|
|
175
|
-
displayName: typeof body.display_name === "string" ? body.display_name : null,
|
|
176
|
-
email,
|
|
177
|
-
createdAt: body.created_at
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
async function registerAgentStart(input, opts = {}) {
|
|
182
|
-
let data;
|
|
183
|
-
try {
|
|
184
|
-
data = await AgentChatClient.register({
|
|
185
|
-
email: input.email,
|
|
186
|
-
handle: input.handle,
|
|
187
|
-
...input.displayName !== void 0 ? { display_name: input.displayName } : {},
|
|
188
|
-
...input.description !== void 0 ? { description: input.description } : {},
|
|
189
|
-
baseUrl: apiBaseOf(opts.apiBase),
|
|
190
|
-
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
191
|
-
});
|
|
192
|
-
} catch (err) {
|
|
193
|
-
const failure = describeFailure(err);
|
|
194
|
-
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
195
|
-
const { status, code, message } = failure;
|
|
196
|
-
if (status === 400 && code === "INVALID_HANDLE") return { ok: false, reason: "invalid-handle", message, status };
|
|
197
|
-
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
198
|
-
if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
|
|
199
|
-
const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
200
|
-
if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
|
|
201
|
-
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
202
|
-
if (status >= 500 || code === "OTP_FAILED") return { ok: false, reason: "otp-failed", message, status };
|
|
203
|
-
return { ok: false, reason: "server-error", status, message };
|
|
204
|
-
}
|
|
205
|
-
const pendingId = asRecord(data)?.pending_id;
|
|
206
|
-
if (typeof pendingId !== "string") {
|
|
207
|
-
return { ok: false, reason: "server-error", status: 200, message: "AgentChat /register returned no pending_id" };
|
|
208
|
-
}
|
|
209
|
-
return { ok: true, pendingId };
|
|
210
|
-
}
|
|
211
|
-
async function registerAgentVerify(input, opts = {}) {
|
|
212
|
-
let verified;
|
|
213
|
-
try {
|
|
214
|
-
verified = await AgentChatClient.verify(input.pendingId, input.code, {
|
|
215
|
-
baseUrl: apiBaseOf(opts.apiBase),
|
|
216
|
-
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
217
|
-
});
|
|
218
|
-
} catch (err) {
|
|
219
|
-
const failure = describeFailure(err);
|
|
220
|
-
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
221
|
-
const { status, code, message } = failure;
|
|
222
|
-
if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
|
|
223
|
-
if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
|
|
224
|
-
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
225
|
-
if (status === 409 && code === "HANDLE_TAKEN") return { ok: false, reason: "handle-taken", message, status };
|
|
226
|
-
const emailPolicy = status === 409 ? classifyEmailPolicyRejection(code) : void 0;
|
|
227
|
-
if (emailPolicy) return { ok: false, reason: emailPolicy, message, status, limit: readPolicyLimit(failure.details) };
|
|
228
|
-
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
229
|
-
return { ok: false, reason: "server-error", status, message };
|
|
230
|
-
}
|
|
231
|
-
const agent = asRecord(verified.agent);
|
|
232
|
-
if (typeof verified.apiKey !== "string" || !agent || typeof agent.handle !== "string" || typeof agent.email !== "string" || typeof agent.created_at !== "string") {
|
|
233
|
-
return { ok: false, reason: "unexpected-shape", status: 201, message: "AgentChat /register/verify returned an unrecognized shape" };
|
|
234
|
-
}
|
|
235
|
-
return {
|
|
236
|
-
ok: true,
|
|
237
|
-
apiKey: verified.apiKey,
|
|
238
|
-
agent: {
|
|
239
|
-
handle: agent.handle,
|
|
240
|
-
displayName: typeof agent.display_name === "string" ? agent.display_name : null,
|
|
241
|
-
email: agent.email,
|
|
242
|
-
createdAt: agent.created_at
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
async function recoverAgentStart(input, opts = {}) {
|
|
247
|
-
let data;
|
|
248
|
-
try {
|
|
249
|
-
data = await AgentChatClient.recover(input.email, {
|
|
250
|
-
handle: input.handle,
|
|
251
|
-
baseUrl: apiBaseOf(opts.apiBase),
|
|
252
|
-
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
253
|
-
});
|
|
254
|
-
} catch (err) {
|
|
255
|
-
const failure = describeFailure(err);
|
|
256
|
-
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
257
|
-
const { status, code, message: message2 } = failure;
|
|
258
|
-
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message: message2, status };
|
|
259
|
-
if (status === 429) return { ok: false, reason: "rate-limited", message: message2, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
260
|
-
return { ok: false, reason: "server-error", status, message: message2 };
|
|
261
|
-
}
|
|
262
|
-
const body = asRecord(data);
|
|
263
|
-
const message = typeof body?.message === "string" ? body.message : "status 200";
|
|
264
|
-
if (typeof body?.pending_id !== "string") {
|
|
265
|
-
return {
|
|
266
|
-
ok: false,
|
|
267
|
-
reason: "unexpected-shape",
|
|
268
|
-
status: 200,
|
|
269
|
-
message: "AgentChat did not start a recovery (no pending_id in the response). Check that the email is the one this agent registered with."
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
return { ok: true, pendingId: body.pending_id, message };
|
|
273
|
-
}
|
|
274
|
-
async function recoverAgentVerify(input, opts = {}) {
|
|
275
|
-
let recovered;
|
|
276
|
-
try {
|
|
277
|
-
recovered = await AgentChatClient.recoverVerify(input.pendingId, input.code, {
|
|
278
|
-
baseUrl: apiBaseOf(opts.apiBase),
|
|
279
|
-
clientIdentity: AGENTCHAT_CLIENT_IDENTITY
|
|
280
|
-
});
|
|
281
|
-
} catch (err) {
|
|
282
|
-
const failure = describeFailure(err);
|
|
283
|
-
if (failure.kind === "network") return { ok: false, reason: "network-error", message: networkMessage(failure) };
|
|
284
|
-
const { status, code, message } = failure;
|
|
285
|
-
if (status === 400 && code === "EXPIRED") return { ok: false, reason: "expired", message, status };
|
|
286
|
-
if (status === 400 && code === "INVALID_CODE") return { ok: false, reason: "invalid-code", message, status };
|
|
287
|
-
if (status === 400 && code === "VALIDATION_ERROR") return { ok: false, reason: "validation", message, status };
|
|
288
|
-
if (status === 409 && code === "HANDLE_REQUIRED") {
|
|
289
|
-
return { ok: false, reason: "handle-required", message, status, handles: readHandleList(failure.details) };
|
|
290
|
-
}
|
|
291
|
-
if (status === 429) return { ok: false, reason: "rate-limited", message, status, retryAfterSeconds: failure.retryAfterSeconds };
|
|
292
|
-
return { ok: false, reason: "server-error", status, message };
|
|
293
|
-
}
|
|
294
|
-
if (typeof recovered.apiKey !== "string" || typeof recovered.handle !== "string") {
|
|
295
|
-
return { ok: false, reason: "unexpected-shape", status: 200, message: "AgentChat /agents/recover/verify returned an unrecognized shape" };
|
|
296
|
-
}
|
|
297
|
-
return { ok: true, apiKey: recovered.apiKey, handle: recovered.handle };
|
|
298
|
-
}
|
|
299
|
-
function classifyEmailPolicyRejection(code) {
|
|
300
|
-
if (code === "EMAIL_LIMIT_REACHED" || code === "EMAIL_TAKEN") return "email-limit-reached";
|
|
301
|
-
if (code === "EMAIL_EXHAUSTED") return "email-exhausted";
|
|
302
|
-
return void 0;
|
|
303
|
-
}
|
|
304
|
-
function readPolicyLimit(details) {
|
|
305
|
-
if (!details || typeof details !== "object") return void 0;
|
|
306
|
-
const limit = details.limit;
|
|
307
|
-
return typeof limit === "number" && Number.isInteger(limit) && limit > 0 ? limit : void 0;
|
|
308
|
-
}
|
|
309
|
-
function readHandleList(details) {
|
|
310
|
-
if (!details || typeof details !== "object") return [];
|
|
311
|
-
const handles = details.handles;
|
|
312
|
-
if (!Array.isArray(handles)) return [];
|
|
313
|
-
return handles.filter((h) => typeof h === "string" && h.length > 0);
|
|
314
|
-
}
|
|
315
|
-
var ONE_ATTEMPT = { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
|
|
316
|
-
function apiBaseOf(apiBase) {
|
|
317
|
-
return (apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
|
|
318
|
-
}
|
|
319
|
-
function describeFailure(err) {
|
|
320
|
-
if (err instanceof AgentChatError) {
|
|
321
|
-
const raw = asRecord(asRecord(err.details)?.body);
|
|
322
|
-
const code = typeof raw?.code === "string" ? raw.code : String(err.code ?? "");
|
|
323
|
-
const message2 = raw ? typeof raw.message === "string" ? raw.message : `status ${err.status}` : err.message || `status ${err.status}`;
|
|
324
|
-
const retryAfterMs = err instanceof RateLimitedError ? err.retryAfterMs : null;
|
|
325
|
-
return {
|
|
326
|
-
kind: "http",
|
|
327
|
-
status: err.status,
|
|
328
|
-
code,
|
|
329
|
-
message: message2,
|
|
330
|
-
details: raw ? raw.details : err.details,
|
|
331
|
-
...typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) ? { retryAfterSeconds: Math.ceil(retryAfterMs / 1e3) } : {}
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
335
|
-
const timedOut = err instanceof Error && err.name === "AbortError" || /timed out|abort/i.test(message);
|
|
336
|
-
return { kind: "network", message, timedOut };
|
|
337
|
-
}
|
|
338
|
-
function networkMessage(failure) {
|
|
339
|
-
return failure.timedOut ? "request timed out" : failure.message;
|
|
340
|
-
}
|
|
341
|
-
function asRecord(value) {
|
|
342
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
343
|
-
}
|
|
344
|
-
async function assertApiKeyValid(apiKey, opts = {}) {
|
|
345
|
-
const result = await validateApiKey(apiKey, opts);
|
|
346
|
-
if (result.ok) return result.agent;
|
|
347
|
-
const class_ = result.reason === "unauthorized" || result.reason === "forbidden" || result.reason === "deleted" ? "terminal-auth" : result.reason === "server-error" ? "retry-transient" : "retry-transient";
|
|
348
|
-
throw new AgentChatChannelError(class_, `${result.message} [reason=${result.reason}]`, {
|
|
349
|
-
statusCode: result.status
|
|
350
|
-
});
|
|
351
|
-
}
|
|
352
|
-
|
|
353
119
|
// src/integration/turn.ts
|
|
354
120
|
var MCP_SERVER_NAME = "agentchat";
|
|
355
121
|
var MCP_TOOL_DELIMITER = "__";
|
|
@@ -386,8 +152,8 @@ function sanitizeKeyPart(value) {
|
|
|
386
152
|
// src/integration/mcp.ts
|
|
387
153
|
var MCP_PATH = "/mcp";
|
|
388
154
|
var AUTH_HEADER_TEMPLATE = `Bearer \${${API_KEY_ENV}}`;
|
|
389
|
-
var
|
|
390
|
-
function hostedMcpUrl(apiBase =
|
|
155
|
+
var DEFAULT_API_BASE = "https://api.agentchat.me";
|
|
156
|
+
function hostedMcpUrl(apiBase = DEFAULT_API_BASE) {
|
|
391
157
|
return `${apiBase.replace(/\/+$/, "")}${MCP_PATH}`;
|
|
392
158
|
}
|
|
393
159
|
var CLIENT_HEADER = "X-AgentChat-Client";
|
|
@@ -397,14 +163,14 @@ function clientIdentityHeaders() {
|
|
|
397
163
|
function clientIdentityText() {
|
|
398
164
|
return `${CLIENT_HEADER}: ${AGENTCHAT_CLIENT_NAME}`;
|
|
399
165
|
}
|
|
400
|
-
function hostedMcpServerEntry(apiBase =
|
|
166
|
+
function hostedMcpServerEntry(apiBase = DEFAULT_API_BASE) {
|
|
401
167
|
return {
|
|
402
168
|
url: hostedMcpUrl(apiBase),
|
|
403
169
|
transport: "streamable-http",
|
|
404
170
|
headers: { Authorization: AUTH_HEADER_TEMPLATE, ...clientIdentityHeaders() }
|
|
405
171
|
};
|
|
406
172
|
}
|
|
407
|
-
function hostedMcpSnippet(apiBase =
|
|
173
|
+
function hostedMcpSnippet(apiBase = DEFAULT_API_BASE) {
|
|
408
174
|
const identity = clientIdentityHeaders();
|
|
409
175
|
return [
|
|
410
176
|
"{",
|
|
@@ -423,7 +189,7 @@ function hostedMcpSnippet(apiBase = DEFAULT_API_BASE2) {
|
|
|
423
189
|
"}"
|
|
424
190
|
].join("\n");
|
|
425
191
|
}
|
|
426
|
-
function describeMcpEntry(cfg, apiBase =
|
|
192
|
+
function describeMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
|
|
427
193
|
const servers = cfg?.mcp?.servers;
|
|
428
194
|
if (!servers || typeof servers !== "object" || Array.isArray(servers)) return "missing";
|
|
429
195
|
const entry = servers[MCP_SERVER_NAME];
|
|
@@ -456,7 +222,7 @@ function describeMcpIdentity(cfg) {
|
|
|
456
222
|
const client = clients[0];
|
|
457
223
|
return clients.length === 1 && typeof client === "string" && client.trim().toLowerCase() === want[CLIENT_HEADER] ? "current" : "missing";
|
|
458
224
|
}
|
|
459
|
-
function withHostedMcpEntry(cfg, apiBase =
|
|
225
|
+
function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
|
|
460
226
|
const state = describeMcpEntry(cfg, apiBase, apiKey);
|
|
461
227
|
const base = cfg ?? {};
|
|
462
228
|
if (state === "user_managed") return { cfg: base, outcome: "user_managed" };
|
|
@@ -469,7 +235,7 @@ function withHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
|
469
235
|
mcp.servers = servers;
|
|
470
236
|
return { cfg: { ...base, mcp }, outcome: state === "ours" ? "updated" : "added" };
|
|
471
237
|
}
|
|
472
|
-
function upgradedHostedMcpEntry(entry, apiBase =
|
|
238
|
+
function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE) {
|
|
473
239
|
const headers = isRecord(entry.headers) ? entry.headers : {};
|
|
474
240
|
const kept = Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== CLIENT_HEADER.toLowerCase()));
|
|
475
241
|
return {
|
|
@@ -479,7 +245,7 @@ function upgradedHostedMcpEntry(entry, apiBase = DEFAULT_API_BASE2) {
|
|
|
479
245
|
headers: { ...kept, ...clientIdentityHeaders() }
|
|
480
246
|
};
|
|
481
247
|
}
|
|
482
|
-
function upgradeHostedMcpEntryInPlace(draft, apiBase =
|
|
248
|
+
function upgradeHostedMcpEntryInPlace(draft, apiBase = DEFAULT_API_BASE, apiKey) {
|
|
483
249
|
if (describeMcpEntry(draft, apiBase, apiKey) !== "ours" || describeMcpIdentity(draft) === "current") return false;
|
|
484
250
|
const servers = draft.mcp.servers;
|
|
485
251
|
const existing = servers[MCP_SERVER_NAME];
|
|
@@ -496,7 +262,7 @@ var NoChange = class extends Error {
|
|
|
496
262
|
};
|
|
497
263
|
var NIX_MODE_ERROR_CODE = "OPENCLAW_NIX_MODE_CONFIG_IMMUTABLE";
|
|
498
264
|
async function refreshHostedMcpEntry(params) {
|
|
499
|
-
const apiBase = params.apiBase ??
|
|
265
|
+
const apiBase = params.apiBase ?? DEFAULT_API_BASE;
|
|
500
266
|
if (describeMcpEntry(params.liveCfg, apiBase, params.apiKey) !== "ours") return { outcome: "not_ours" };
|
|
501
267
|
if (describeMcpIdentity(params.liveCfg) === "current") return { outcome: "current" };
|
|
502
268
|
const mutate = params.config?.mutateConfigFile;
|
|
@@ -533,7 +299,7 @@ function headerValues(headers, name) {
|
|
|
533
299
|
const wanted = name.toLowerCase();
|
|
534
300
|
return Object.entries(headers).filter(([key]) => key.toLowerCase() === wanted).map(([, value]) => value);
|
|
535
301
|
}
|
|
536
|
-
function withoutHostedMcpEntry(cfg, apiBase =
|
|
302
|
+
function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE, apiKey) {
|
|
537
303
|
if (describeMcpEntry(cfg, apiBase, apiKey) !== "ours") return { cfg, removed: false };
|
|
538
304
|
const mcp = { ...cfg.mcp ?? {} };
|
|
539
305
|
const servers = { ...mcp.servers ?? {} };
|
|
@@ -543,7 +309,7 @@ function withoutHostedMcpEntry(cfg, apiBase = DEFAULT_API_BASE2, apiKey) {
|
|
|
543
309
|
}
|
|
544
310
|
async function probeHostedMcp(params) {
|
|
545
311
|
const result = await integration.probeHostedTools({
|
|
546
|
-
apiBase: params.apiBase ??
|
|
312
|
+
apiBase: params.apiBase ?? DEFAULT_API_BASE,
|
|
547
313
|
apiKey: params.apiKey,
|
|
548
314
|
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
549
315
|
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
@@ -562,6 +328,40 @@ async function probeHostedMcp(params) {
|
|
|
562
328
|
};
|
|
563
329
|
}
|
|
564
330
|
|
|
331
|
+
// src/setup-client.ts
|
|
332
|
+
var KEY_CHECK_TIMEOUT_MS = 1e4;
|
|
333
|
+
function accountCallOptions(params = {}) {
|
|
334
|
+
return {
|
|
335
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
336
|
+
apiBase: (params.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, ""),
|
|
337
|
+
...params.fetch ? { fetch: params.fetch } : {},
|
|
338
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
var KeyCheckUnanswered = class extends Error {
|
|
342
|
+
constructor(message) {
|
|
343
|
+
super(message);
|
|
344
|
+
this.name = "KeyCheckUnanswered";
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
async function checkApiKey(apiKey, params = {}) {
|
|
348
|
+
let status;
|
|
349
|
+
const send = params.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
350
|
+
const observed = (async (input, init) => {
|
|
351
|
+
const response = await send(input, init);
|
|
352
|
+
status = response.status;
|
|
353
|
+
return response;
|
|
354
|
+
});
|
|
355
|
+
const check = await integration.account.checkKey(
|
|
356
|
+
apiKey,
|
|
357
|
+
accountCallOptions({ timeoutMs: KEY_CHECK_TIMEOUT_MS, ...params, fetch: observed })
|
|
358
|
+
);
|
|
359
|
+
if (!check.ok && status !== 401 && status !== 403) {
|
|
360
|
+
throw new KeyCheckUnanswered(`AgentChat answered ${status ?? "without a status"} (${check.code}): ${check.message}`);
|
|
361
|
+
}
|
|
362
|
+
return check;
|
|
363
|
+
}
|
|
364
|
+
|
|
565
365
|
// src/integration/runtime-holder.ts
|
|
566
366
|
var current = null;
|
|
567
367
|
function isUsablePluginRuntime(runtime) {
|
|
@@ -643,55 +443,266 @@ async function watchRunUntilEnded(options) {
|
|
|
643
443
|
if (elapsedMs < MIN_WAIT_SPACING_MS) await sleep(MIN_WAIT_SPACING_MS - elapsedMs);
|
|
644
444
|
}
|
|
645
445
|
}
|
|
646
|
-
function countAgentChatCalls(messages, runId) {
|
|
446
|
+
function countAgentChatCalls(messages, runId, host = {}) {
|
|
647
447
|
if (messages.length === 0) return null;
|
|
648
|
-
|
|
649
|
-
let made = 0;
|
|
650
|
-
let failed = 0;
|
|
448
|
+
const rows = [];
|
|
651
449
|
for (const row of messages) {
|
|
652
450
|
const message = unwrapMessage(row);
|
|
653
|
-
if (!message)
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
451
|
+
if (!message) return null;
|
|
452
|
+
rows.push(message);
|
|
453
|
+
}
|
|
454
|
+
if (!coversWholeSession(rows)) return null;
|
|
455
|
+
if (runId && rows.some((row) => isOtherRun(row, runId))) return null;
|
|
456
|
+
const calls = assistantToolCalls(rows);
|
|
457
|
+
const nested = rows.flatMap((row) => {
|
|
458
|
+
const call = nestedCallOf(row);
|
|
459
|
+
return call ? [call] : [];
|
|
460
|
+
});
|
|
461
|
+
const release = releaseOf(rows, calls, nested, host.openclawVersion);
|
|
462
|
+
if (delegatedToChild(rows, calls, nested)) return null;
|
|
463
|
+
if (usedCodeMode(rows, calls)) {
|
|
464
|
+
if (!release.recordsNestedCalls) return null;
|
|
465
|
+
if (!codeModeScriptsCompleted(rows, calls)) return null;
|
|
466
|
+
}
|
|
467
|
+
const parents = new Set(nested.flatMap((call) => typeof call.parentToolCallId === "string" ? [call.parentToolCallId] : []));
|
|
468
|
+
let made = 0;
|
|
469
|
+
let failed = 0;
|
|
470
|
+
for (const message of rows) {
|
|
471
|
+
let verdict;
|
|
472
|
+
const call = nestedCallOf(message);
|
|
473
|
+
if (call) verdict = nestedVerdict(call);
|
|
474
|
+
else if (message.role !== "toolResult" && message.role !== "tool") continue;
|
|
475
|
+
else if (typeof message.toolCallId === "string" && parents.has(message.toolCallId)) continue;
|
|
476
|
+
else verdict = callVerdict(message, calls, release);
|
|
477
|
+
if (verdict === "not_agentchat") continue;
|
|
478
|
+
if (verdict === "unknown") return null;
|
|
661
479
|
made += 1;
|
|
662
|
-
if (
|
|
480
|
+
if (verdict === "failed") failed += 1;
|
|
663
481
|
}
|
|
664
|
-
return
|
|
482
|
+
return { made, failed };
|
|
665
483
|
}
|
|
666
484
|
async function readAgentChatCalls(runtime, sessionKey, runId) {
|
|
667
485
|
if (!runtime || typeof runtime.subagent?.getSessionMessages !== "function") return null;
|
|
668
486
|
try {
|
|
669
487
|
const result = await runtime.subagent.getSessionMessages({ sessionKey, limit: TRANSCRIPT_READ_LIMIT });
|
|
670
488
|
const messages = result?.messages;
|
|
671
|
-
|
|
489
|
+
const openclawVersion = typeof runtime.version === "string" ? runtime.version : void 0;
|
|
490
|
+
return Array.isArray(messages) ? countAgentChatCalls(messages, runId, openclawVersion ? { openclawVersion } : {}) : null;
|
|
672
491
|
} catch {
|
|
673
492
|
return null;
|
|
674
493
|
}
|
|
675
494
|
}
|
|
676
495
|
var TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
496
|
+
var DISPATCHER_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_call", "dispatch_action"]);
|
|
497
|
+
var FAILURE_STATUSES = /* @__PURE__ */ new Set([
|
|
498
|
+
"error",
|
|
499
|
+
"failed",
|
|
500
|
+
"failure",
|
|
501
|
+
"timeout",
|
|
502
|
+
"timed_out",
|
|
503
|
+
"blocked",
|
|
504
|
+
"denied",
|
|
505
|
+
"forbidden",
|
|
506
|
+
"unavailable",
|
|
507
|
+
"approval-unavailable",
|
|
508
|
+
"disabled",
|
|
509
|
+
"aborted",
|
|
510
|
+
"cancelled",
|
|
511
|
+
"canceled",
|
|
512
|
+
"killed",
|
|
513
|
+
"invalid"
|
|
514
|
+
]);
|
|
515
|
+
function coversWholeSession(rows) {
|
|
516
|
+
if (asRecord(rows[0]?.__openclaw)?.seq !== 1) return false;
|
|
517
|
+
return rows.every((row) => {
|
|
518
|
+
const meta = asRecord(row.__openclaw);
|
|
519
|
+
return meta?.kind !== "compaction" && meta?.kind !== "reset" && meta?.truncated !== true;
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
function isOtherRun(row, runId) {
|
|
523
|
+
const tagged = asRecord(row.__openclaw)?.runId ?? nestedCallOf(row)?.runId;
|
|
524
|
+
return typeof tagged === "string" && tagged.trim().length > 0 && tagged.trim() !== runId;
|
|
525
|
+
}
|
|
526
|
+
var CODE_MODE_ONLY_TOOL_NAMES = /* @__PURE__ */ new Set(["tool_search_code", "wait"]);
|
|
527
|
+
function usedCodeMode(rows, calls) {
|
|
528
|
+
return [...calls.values()].some(isCodeModeCall) || rows.some((row) => isCodeModeResult(row, calls));
|
|
529
|
+
}
|
|
530
|
+
function codeModeScriptsCompleted(rows, calls) {
|
|
531
|
+
const results = /* @__PURE__ */ new Map();
|
|
532
|
+
for (const row of rows) {
|
|
533
|
+
if ((row.role === "toolResult" || row.role === "tool") && typeof row.toolCallId === "string") results.set(row.toolCallId, row);
|
|
534
|
+
}
|
|
535
|
+
const completed = (row) => row !== void 0 && row.isError !== true && asRecord(row.details)?.status === "completed";
|
|
536
|
+
for (const [id, call] of calls) {
|
|
537
|
+
if (isCodeModeCall(call) && !completed(results.get(id))) return false;
|
|
538
|
+
}
|
|
539
|
+
return rows.every((row) => !isCodeModeResult(row, calls) || completed(row));
|
|
540
|
+
}
|
|
541
|
+
function isCodeModeCall(call) {
|
|
542
|
+
const name = typeof call.name === "string" ? call.name : "";
|
|
543
|
+
return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && typeof callArguments(call)?.code === "string";
|
|
544
|
+
}
|
|
545
|
+
function isCodeModeResult(row, calls) {
|
|
546
|
+
if (row.role !== "toolResult" && row.role !== "tool") return false;
|
|
547
|
+
const name = toolNameOf(row);
|
|
548
|
+
return CODE_MODE_ONLY_TOOL_NAMES.has(name) || name === "exec" && !isShellExecResult(row, calls);
|
|
549
|
+
}
|
|
550
|
+
function isShellExecResult(row, calls) {
|
|
551
|
+
const call = typeof row.toolCallId === "string" ? calls.get(row.toolCallId) : void 0;
|
|
552
|
+
const args = callArguments(call);
|
|
553
|
+
if (!args || typeof args.command !== "string" || args.code !== void 0) return false;
|
|
554
|
+
const details = asRecord(row.details);
|
|
555
|
+
if (!details || details.telemetry !== void 0) return false;
|
|
556
|
+
return details.exitCode !== void 0 || typeof details.durationMs === "number" || typeof details.aggregated === "string";
|
|
557
|
+
}
|
|
558
|
+
function assistantToolCalls(rows) {
|
|
559
|
+
const calls = /* @__PURE__ */ new Map();
|
|
560
|
+
for (const row of rows) {
|
|
561
|
+
if (row.role !== "assistant" || !Array.isArray(row.content)) continue;
|
|
562
|
+
for (const block of row.content) {
|
|
563
|
+
const call = asRecord(block);
|
|
564
|
+
if (call?.type === "toolCall" && typeof call.id === "string") calls.set(call.id, call);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
return calls;
|
|
568
|
+
}
|
|
569
|
+
var TRUSTED_RELEASE = "2026.9.3";
|
|
570
|
+
function releaseOf(rows, calls, nested, version) {
|
|
571
|
+
if (version !== void 0 && isOpenClawVersion(version)) {
|
|
572
|
+
const trusted = openclawVersionAtLeast(version, TRUSTED_RELEASE);
|
|
573
|
+
return { recordsNestedCalls: trusted, marksFailedRows: trusted };
|
|
574
|
+
}
|
|
575
|
+
const parents = new Set(nested.map((call) => call.parentToolCallId));
|
|
576
|
+
const dispatchAction = rows.some((row) => (row.role === "toolResult" || row.role === "tool") && toolNameOf(row) === "dispatch_action" && asRecord(asRecord(row.details)?.tool) !== null) || [...calls].some(([id, call]) => call.name === "dispatch_action" && parents.has(id));
|
|
577
|
+
return { recordsNestedCalls: nested.length > 0 || dispatchAction, marksFailedRows: dispatchAction };
|
|
578
|
+
}
|
|
579
|
+
var OPENCLAW_VERSION = /^(\d+)\.(\d+)\.(\d+)(-.+)?$/;
|
|
580
|
+
function isOpenClawVersion(value) {
|
|
581
|
+
return OPENCLAW_VERSION.test(value.trim());
|
|
582
|
+
}
|
|
583
|
+
function openclawVersionAtLeast(a, b) {
|
|
584
|
+
const parse = (v) => {
|
|
585
|
+
const match = OPENCLAW_VERSION.exec(v.trim());
|
|
586
|
+
return match ? { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] !== void 0 } : null;
|
|
587
|
+
};
|
|
588
|
+
const [x, y] = [parse(a), parse(b)];
|
|
589
|
+
if (!x || !y) return false;
|
|
590
|
+
for (let i = 0; i < 3; i += 1) {
|
|
591
|
+
const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
|
|
592
|
+
if (d !== 0) return d > 0;
|
|
593
|
+
}
|
|
594
|
+
return !x.pre || y.pre;
|
|
595
|
+
}
|
|
596
|
+
function toolNameOf(row) {
|
|
597
|
+
return typeof row.toolName === "string" ? row.toolName : typeof row.name === "string" ? row.name : "";
|
|
598
|
+
}
|
|
599
|
+
var NESTED_TOOL_ACTIVITY = "openclaw.nested-tool.v1";
|
|
600
|
+
function nestedCallOf(row) {
|
|
601
|
+
if (row.role !== "custom" || row.customType !== NESTED_TOOL_ACTIVITY) return null;
|
|
602
|
+
return asRecord(row.details);
|
|
603
|
+
}
|
|
604
|
+
function nestedVerdict(call) {
|
|
605
|
+
const toolName = typeof call.toolName === "string" ? call.toolName : "";
|
|
606
|
+
if (!toolName.startsWith(TOOL_PREFIX)) return "not_agentchat";
|
|
607
|
+
const result = asRecord(call.result);
|
|
608
|
+
if (call.isError === true || result !== null && failedResult(result.isError, asRecord(result.details))) return "failed";
|
|
609
|
+
return call.isError === false ? "ok" : "unknown";
|
|
610
|
+
}
|
|
611
|
+
var OTHER_SESSION_TOOLS = /* @__PURE__ */ new Set(["sessions_spawn", "sessions_send"]);
|
|
612
|
+
function delegatedToChild(rows, calls, nested) {
|
|
613
|
+
const names = (value) => typeof value === "string" && OTHER_SESSION_TOOLS.has(value);
|
|
614
|
+
for (const call of calls.values()) {
|
|
615
|
+
if (names(call.name)) return true;
|
|
616
|
+
if (typeof call.name === "string" && DISPATCHER_TOOL_NAMES.has(call.name) && names(dispatchTarget(call))) return true;
|
|
617
|
+
}
|
|
618
|
+
if (nested.some((call) => names(call.toolName))) return true;
|
|
619
|
+
return rows.some((row) => names(toolNameOf(row)) || names(asRecord(asRecord(row.details)?.tool)?.name));
|
|
620
|
+
}
|
|
621
|
+
function callVerdict(message, calls, release) {
|
|
622
|
+
const toolName = toolNameOf(message);
|
|
623
|
+
const details = asRecord(message.details);
|
|
624
|
+
if (toolName.startsWith(TOOL_PREFIX)) return directVerdict(message.isError, details);
|
|
625
|
+
const entry = asRecord(details?.tool);
|
|
626
|
+
if (entry && isAgentChatEntry(entry)) return dispatchedVerdict(message.isError, details);
|
|
627
|
+
if (!DISPATCHER_TOOL_NAMES.has(toolName) || entry) return "not_agentchat";
|
|
628
|
+
const target = dispatchTarget(typeof message.toolCallId === "string" ? calls.get(message.toolCallId) : void 0);
|
|
629
|
+
if (target === null) return "unknown";
|
|
630
|
+
if (!target.startsWith(TOOL_PREFIX)) return "not_agentchat";
|
|
631
|
+
if (failedResult(message.isError, details)) return "failed";
|
|
632
|
+
if (release.marksFailedRows && isTruncated(details) && message.isError === false && details?.status === void 0) return "ok";
|
|
633
|
+
return "unknown";
|
|
634
|
+
}
|
|
635
|
+
function isTruncated(details) {
|
|
636
|
+
return details?.persistedDetailsTruncated === true;
|
|
637
|
+
}
|
|
638
|
+
function directVerdict(isError, details) {
|
|
639
|
+
if (failedResult(isError, details)) return "failed";
|
|
640
|
+
if (isError !== false) return "unknown";
|
|
641
|
+
if (isTruncated(details)) return details?.status === void 0 && wasHostedResult(details) ? "ok" : "unknown";
|
|
642
|
+
return isHostedSuccessDetails(details) ? "ok" : "unknown";
|
|
643
|
+
}
|
|
644
|
+
function wasHostedResult(details) {
|
|
645
|
+
const keys = Array.isArray(details?.originalDetailKeys) ? details.originalDetailKeys : [];
|
|
646
|
+
return keys.includes("mcpServer") && (keys.includes("mcpTool") || keys.includes("mcpOperation"));
|
|
647
|
+
}
|
|
648
|
+
function dispatchedVerdict(isError, details) {
|
|
649
|
+
const result = asRecord(details?.result);
|
|
650
|
+
if (failedResult(isError, details)) return "failed";
|
|
651
|
+
if (result && failedResult(result.isError, asRecord(result.details))) return "failed";
|
|
652
|
+
const ok = isError === false && details?.status === void 0 && isHostedSuccessDetails(asRecord(result?.details));
|
|
653
|
+
return ok ? "ok" : "unknown";
|
|
654
|
+
}
|
|
655
|
+
function failedResult(isError, details) {
|
|
656
|
+
return isError === true || detailsSayFailed(details);
|
|
657
|
+
}
|
|
658
|
+
function detailsSayFailed(details) {
|
|
659
|
+
if (!details) return false;
|
|
660
|
+
if (details.ok === false || details.success === false) return true;
|
|
661
|
+
const status = typeof details.status === "string" ? details.status.trim().toLowerCase() : "";
|
|
662
|
+
const explicitlyOk = details.ok === true || details.success === true;
|
|
663
|
+
if (FAILURE_STATUSES.has(status) && !explicitlyOk) return true;
|
|
664
|
+
if (details.timedOut === true || Boolean(details.error)) return true;
|
|
665
|
+
if (status === "completed") return false;
|
|
666
|
+
const exitCode = details.exitCode;
|
|
667
|
+
return typeof exitCode === "number" && Number.isFinite(exitCode) && exitCode !== 0;
|
|
668
|
+
}
|
|
669
|
+
function isHostedSuccessDetails(details) {
|
|
670
|
+
if (!details || details.mcpServer !== MCP_SERVER_NAME || details.status !== void 0) return false;
|
|
671
|
+
return nonEmpty(details.mcpTool) !== void 0 || nonEmpty(details.mcpOperation) !== void 0;
|
|
672
|
+
}
|
|
673
|
+
function isAgentChatEntry(tool) {
|
|
682
674
|
if (typeof tool.name === "string" && tool.name.startsWith(TOOL_PREFIX)) return true;
|
|
683
675
|
if (tool.sourceName === MCP_SERVER_NAME) return true;
|
|
684
|
-
const mcp =
|
|
676
|
+
const mcp = asRecord(tool.mcp);
|
|
685
677
|
return mcp?.serverName === MCP_SERVER_NAME;
|
|
686
678
|
}
|
|
679
|
+
function dispatchTarget(call) {
|
|
680
|
+
const record = callArguments(call);
|
|
681
|
+
const selector = nonEmpty(record?.id) ?? nonEmpty(record?.toolId) ?? nonEmpty(record?.name);
|
|
682
|
+
if (!selector) return null;
|
|
683
|
+
const trimmed = selector.trim();
|
|
684
|
+
return trimmed.slice(trimmed.lastIndexOf(":") + 1);
|
|
685
|
+
}
|
|
686
|
+
function callArguments(call) {
|
|
687
|
+
if (!call) return null;
|
|
688
|
+
let args = call.arguments;
|
|
689
|
+
if (typeof args === "string") {
|
|
690
|
+
try {
|
|
691
|
+
args = JSON.parse(args);
|
|
692
|
+
} catch {
|
|
693
|
+
return null;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
return asRecord(args);
|
|
697
|
+
}
|
|
687
698
|
function unwrapMessage(row) {
|
|
688
|
-
const record =
|
|
699
|
+
const record = asRecord(row);
|
|
689
700
|
if (!record) return null;
|
|
690
701
|
if (typeof record.role === "string") return record;
|
|
691
|
-
const inner =
|
|
702
|
+
const inner = asRecord(record.message);
|
|
692
703
|
return inner && typeof inner.role === "string" ? inner : null;
|
|
693
704
|
}
|
|
694
|
-
function
|
|
705
|
+
function asRecord(value) {
|
|
695
706
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
696
707
|
}
|
|
697
708
|
function nonEmpty(value) {
|
|
@@ -947,7 +958,7 @@ function applyIntegrationConfig(cfg, params) {
|
|
|
947
958
|
const changes = [];
|
|
948
959
|
let next = cfg;
|
|
949
960
|
const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
|
|
950
|
-
if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle
|
|
961
|
+
if (bareHandle && readAgentchatConfigField(next, params.accountId, "agentHandle") !== bareHandle) {
|
|
951
962
|
next = applyAgentchatAccountPatch(next, params.accountId, { agentHandle: bareHandle });
|
|
952
963
|
changes.push(`channels.agentchat${params.accountId === AGENTCHAT_DEFAULT_ACCOUNT_ID ? "" : `.accounts.${params.accountId}`}.agentHandle = ${bareHandle}`);
|
|
953
964
|
}
|
|
@@ -1179,8 +1190,10 @@ function textsCachePath(accountId, stateDir) {
|
|
|
1179
1190
|
return path2.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1180
1191
|
}
|
|
1181
1192
|
function spellTextsForOpenClaw(texts) {
|
|
1193
|
+
const newer = texts;
|
|
1182
1194
|
return {
|
|
1183
1195
|
...texts,
|
|
1196
|
+
...typeof newer.reply_turn_template === "string" ? { reply_turn_template: spellToolsForOpenClaw(newer.reply_turn_template) } : {},
|
|
1184
1197
|
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1185
1198
|
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1186
1199
|
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
@@ -1280,57 +1293,15 @@ function getClient({ accountId, config, options }) {
|
|
|
1280
1293
|
|
|
1281
1294
|
// src/channel.wizard.ts
|
|
1282
1295
|
var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
|
|
1283
|
-
var
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
function isValidHandleShape2(value) {
|
|
1288
|
-
return value.length >= HANDLE_MIN_LENGTH && value.length <= HANDLE_MAX_LENGTH && HANDLE_PATTERN2.test(value);
|
|
1289
|
-
}
|
|
1290
|
-
var OTP_PATTERN = /^\d{6}$/;
|
|
1296
|
+
var LABELS = {
|
|
1297
|
+
...integration.account.DEFAULT_LABELS,
|
|
1298
|
+
handle: "Handle (your @name on AgentChat)"
|
|
1299
|
+
};
|
|
1291
1300
|
function hasConfiguredKey(cfg, accountId) {
|
|
1292
1301
|
return isApiKeyPresent(readAgentchatConfigField(cfg, accountId, "apiKey"));
|
|
1293
1302
|
}
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
return (await prompter.text({
|
|
1297
|
-
message: opts.message ?? "Email \u2014 receives a 6-digit verification code",
|
|
1298
|
-
placeholder: "you@example.com",
|
|
1299
|
-
validate: (value) => {
|
|
1300
|
-
const trimmed = value.trim();
|
|
1301
|
-
if (!trimmed) return "Email is required";
|
|
1302
|
-
if (!EMAIL_PATTERN.test(trimmed)) return "Not a valid email format";
|
|
1303
|
-
return void 0;
|
|
1304
|
-
}
|
|
1305
|
-
})).trim();
|
|
1306
|
-
}
|
|
1307
|
-
async function promptHandle(prompter, opts = {}) {
|
|
1308
|
-
return (await prompter.text({
|
|
1309
|
-
message: opts.message ?? "Choose a handle (your @name on AgentChat)",
|
|
1310
|
-
placeholder: "3\u201330 chars, lowercase a-z, 0-9, hyphens, starts with a letter",
|
|
1311
|
-
...opts.initialValue ? { initialValue: opts.initialValue } : {},
|
|
1312
|
-
validate: (value) => {
|
|
1313
|
-
const trimmed = value.trim();
|
|
1314
|
-
if (!trimmed) return "Handle is required";
|
|
1315
|
-
if (trimmed.length < HANDLE_MIN_LENGTH || trimmed.length > HANDLE_MAX_LENGTH) {
|
|
1316
|
-
return `Length must be ${HANDLE_MIN_LENGTH}\u2013${HANDLE_MAX_LENGTH} chars (you entered ${trimmed.length})`;
|
|
1317
|
-
}
|
|
1318
|
-
if (!/^[a-z]/.test(trimmed)) return "Must start with a lowercase letter";
|
|
1319
|
-
if (/[^a-z0-9-]/.test(trimmed)) {
|
|
1320
|
-
return "Only lowercase letters, digits, and hyphens \u2014 no underscores, dots, or symbols";
|
|
1321
|
-
}
|
|
1322
|
-
if (trimmed.includes("--")) return "No consecutive hyphens";
|
|
1323
|
-
if (trimmed.endsWith("-")) return "Cannot end with a hyphen";
|
|
1324
|
-
return void 0;
|
|
1325
|
-
}
|
|
1326
|
-
})).trim();
|
|
1327
|
-
}
|
|
1328
|
-
async function promptDisplayName(prompter) {
|
|
1329
|
-
return (await prompter.text({
|
|
1330
|
-
message: "Display name (shown next to your @handle)",
|
|
1331
|
-
placeholder: "e.g. Anton, Builder Bot, Sasha",
|
|
1332
|
-
validate: () => void 0
|
|
1333
|
-
})).trim();
|
|
1303
|
+
function nonEmpty2(value) {
|
|
1304
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
1334
1305
|
}
|
|
1335
1306
|
async function runChangeApiBaseFlow(params) {
|
|
1336
1307
|
const { cfg, accountId, prompter } = params;
|
|
@@ -1368,388 +1339,182 @@ async function runChangeApiBaseFlow(params) {
|
|
|
1368
1339
|
await prompter.note(`API base set to ${input}`, "Updated");
|
|
1369
1340
|
return { cfg: patched };
|
|
1370
1341
|
}
|
|
1371
|
-
function
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
message: `${describeEmailPolicyRejection(email, result)} What next?`,
|
|
1378
|
-
options: [
|
|
1379
|
-
{
|
|
1380
|
-
value: "retry",
|
|
1381
|
-
label: "Use a different email address",
|
|
1382
|
-
hint: "a +alias like you+agent2@example.com counts as a separate email"
|
|
1383
|
-
},
|
|
1384
|
-
{
|
|
1385
|
-
value: "recover",
|
|
1386
|
-
label: "Recover the API key of an agent this email already backs",
|
|
1387
|
-
hint: "needs that agent\u2019s handle \u2014 a code goes to this email"
|
|
1388
|
-
},
|
|
1389
|
-
{ value: "paste", label: "Paste a key from an existing agent" },
|
|
1390
|
-
{ value: "cancel", label: "Cancel registration" }
|
|
1391
|
-
],
|
|
1392
|
-
initialValue: "retry"
|
|
1393
|
-
});
|
|
1342
|
+
async function askText(prompter, message, opts = {}) {
|
|
1343
|
+
return (await prompter.text({
|
|
1344
|
+
message,
|
|
1345
|
+
...opts,
|
|
1346
|
+
validate: (value) => value.trim() ? void 0 : "Required"
|
|
1347
|
+
})).trim();
|
|
1394
1348
|
}
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
"
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
);
|
|
1430
|
-
return "
|
|
1431
|
-
}
|
|
1432
|
-
if (startResult.ok) {
|
|
1433
|
-
startSpinner.stop(`Verification code sent to ${email}`);
|
|
1434
|
-
startedOk = true;
|
|
1435
|
-
break;
|
|
1436
|
-
}
|
|
1437
|
-
startSpinner.stop("Registration rejected");
|
|
1438
|
-
switch (startResult.reason) {
|
|
1439
|
-
case "invalid-handle":
|
|
1440
|
-
case "handle-taken": {
|
|
1441
|
-
const detail = startResult.reason === "handle-taken" ? `Handle @${handle} is already taken.` : "That handle is not acceptable (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
|
|
1442
|
-
await prompter.note(`${detail} Pick a different handle and we'll try again.`, "Pick a different handle");
|
|
1443
|
-
handle = await promptHandle(prompter);
|
|
1444
|
-
continue;
|
|
1445
|
-
}
|
|
1446
|
-
case "email-limit-reached":
|
|
1447
|
-
case "email-exhausted": {
|
|
1448
|
-
const choice = await promptEmailPolicyChoice(prompter, email, {
|
|
1449
|
-
reason: startResult.reason,
|
|
1450
|
-
limit: startResult.limit,
|
|
1451
|
-
message: startResult.message
|
|
1452
|
-
});
|
|
1453
|
-
if (choice === "paste") return "user-chose-paste";
|
|
1454
|
-
if (choice === "recover") return "user-chose-recover";
|
|
1455
|
-
if (choice === "cancel") return "abort";
|
|
1456
|
-
email = await promptEmail(prompter);
|
|
1457
|
-
continue;
|
|
1458
|
-
}
|
|
1459
|
-
case "rate-limited": {
|
|
1460
|
-
const wait = startResult.retryAfterSeconds ? ` Try again in ${startResult.retryAfterSeconds}s.` : "";
|
|
1461
|
-
await prompter.note(`Too many registration attempts.${wait}`, "Rate limited");
|
|
1462
|
-
return "abort";
|
|
1463
|
-
}
|
|
1464
|
-
case "otp-failed": {
|
|
1465
|
-
await prompter.note(
|
|
1466
|
-
"The verification-code email could not be sent. Try again in a minute, or paste an existing key instead.",
|
|
1467
|
-
"OTP delivery failed"
|
|
1468
|
-
);
|
|
1469
|
-
return "abort";
|
|
1470
|
-
}
|
|
1471
|
-
case "network-error":
|
|
1472
|
-
case "server-error":
|
|
1473
|
-
case "validation":
|
|
1474
|
-
default: {
|
|
1475
|
-
await prompter.note(describeRegisterStartError(startResult), "Could not start registration");
|
|
1476
|
-
return "abort";
|
|
1477
|
-
}
|
|
1349
|
+
var EMAIL_PLACEHOLDER = "you@example.com";
|
|
1350
|
+
async function askCode(prompter, label) {
|
|
1351
|
+
for (; ; ) {
|
|
1352
|
+
const code = (await prompter.text({ message: label, placeholder: "leave blank for a new code or to cancel" })).trim();
|
|
1353
|
+
if (code) return { answer: "value", value: code };
|
|
1354
|
+
const choice = await prompter.select({
|
|
1355
|
+
message: "What would you like to do?",
|
|
1356
|
+
options: [
|
|
1357
|
+
{ value: "new_code", label: "Send a new code" },
|
|
1358
|
+
{ value: "enter", label: "Enter the code" },
|
|
1359
|
+
{ value: "cancel", label: "Cancel", hint: "paste an existing key instead, or leave setup" }
|
|
1360
|
+
],
|
|
1361
|
+
initialValue: "new_code"
|
|
1362
|
+
});
|
|
1363
|
+
if (choice === "new_code") return { answer: "new_code" };
|
|
1364
|
+
if (choice === "cancel") return { answer: "cancel" };
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
function askThrough(prompter) {
|
|
1368
|
+
return async (question) => {
|
|
1369
|
+
if (question.field === "new_code") {
|
|
1370
|
+
const yes = await prompter.confirm({ message: "Send a new code?", initialValue: true });
|
|
1371
|
+
return yes ? { answer: "new_code" } : { answer: "cancel" };
|
|
1372
|
+
}
|
|
1373
|
+
if (question.field === "code") return askCode(prompter, question.label ?? LABELS.code);
|
|
1374
|
+
const label = question.label ?? LABELS[question.field];
|
|
1375
|
+
const handles = (question.handles ?? []).filter((handle) => handle.length > 0);
|
|
1376
|
+
if (handles.length > 0) {
|
|
1377
|
+
const picked = await prompter.select({
|
|
1378
|
+
message: label,
|
|
1379
|
+
options: [
|
|
1380
|
+
...handles.map((handle) => ({ value: handle, label: `@${handle}` })),
|
|
1381
|
+
{ value: "", label: "Another handle" }
|
|
1382
|
+
]
|
|
1383
|
+
});
|
|
1384
|
+
if (picked) return { answer: "value", value: picked };
|
|
1478
1385
|
}
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
}
|
|
1487
|
-
const maxCodeAttempts = 3;
|
|
1488
|
-
let verifyResult = null;
|
|
1489
|
-
for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
|
|
1490
|
-
const code = (await prompter.text({
|
|
1491
|
-
message: attempt === 1 ? "Enter the 6-digit verification code from your email" : `Verification code (attempt ${attempt}/${maxCodeAttempts})`,
|
|
1492
|
-
placeholder: "123456",
|
|
1493
|
-
validate: (value) => {
|
|
1494
|
-
const trimmed = value.trim();
|
|
1495
|
-
if (!trimmed) return "Code is required";
|
|
1496
|
-
if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
|
|
1497
|
-
return void 0;
|
|
1498
|
-
}
|
|
1499
|
-
})).trim();
|
|
1500
|
-
const verifySpinner = prompter.progress("Verifying code\u2026");
|
|
1386
|
+
const typed = await askText(prompter, label, question.field === "email" ? { placeholder: EMAIL_PLACEHOLDER } : {});
|
|
1387
|
+
return { answer: "value", value: typed };
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
function fetchWithProgress(prompter) {
|
|
1391
|
+
return (async (input, init) => {
|
|
1392
|
+
const progress = prompter.progress("Contacting AgentChat\u2026");
|
|
1501
1393
|
try {
|
|
1502
|
-
|
|
1503
|
-
}
|
|
1504
|
-
|
|
1505
|
-
await prompter.note(
|
|
1506
|
-
`${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
|
|
1507
|
-
"Verification failed"
|
|
1508
|
-
);
|
|
1509
|
-
return "abort";
|
|
1510
|
-
}
|
|
1511
|
-
if (verifyResult.ok) {
|
|
1512
|
-
verifySpinner.stop(`Registered as @${verifyResult.agent.handle}`);
|
|
1513
|
-
break;
|
|
1514
|
-
}
|
|
1515
|
-
verifySpinner.stop("Verification failed");
|
|
1516
|
-
if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
|
|
1517
|
-
await prompter.note(
|
|
1518
|
-
"That code did not match. Check your email and try again.",
|
|
1519
|
-
"Invalid verification code"
|
|
1520
|
-
);
|
|
1521
|
-
continue;
|
|
1394
|
+
return await globalThis.fetch(input, init);
|
|
1395
|
+
} finally {
|
|
1396
|
+
progress.stop();
|
|
1522
1397
|
}
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
)
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
function sleepWithProgress(prompter) {
|
|
1401
|
+
const label = (seconds) => `Waiting ${seconds} s\u2026`;
|
|
1402
|
+
return (ms) => new Promise((resolve) => {
|
|
1403
|
+
let left = Math.ceil(ms / 1e3);
|
|
1404
|
+
const progress = prompter.progress(label(left));
|
|
1405
|
+
const tick = setInterval(() => {
|
|
1406
|
+
left -= 1;
|
|
1407
|
+
if (left > 0) progress.update(label(left));
|
|
1408
|
+
}, 1e3);
|
|
1409
|
+
setTimeout(() => {
|
|
1410
|
+
clearInterval(tick);
|
|
1411
|
+
progress.stop();
|
|
1412
|
+
resolve();
|
|
1413
|
+
}, ms);
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
async function registerInput(prompter) {
|
|
1538
1417
|
await prompter.note(
|
|
1539
1418
|
[
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1419
|
+
"Registration creates a new AgentChat agent tied to your email address.",
|
|
1420
|
+
"Your handle is the agent\u2019s @name on AgentChat. AgentChat emails you a",
|
|
1421
|
+
"code to confirm the address \u2014 check your inbox (and spam)."
|
|
1543
1422
|
].join("\n"),
|
|
1544
|
-
"AgentChat
|
|
1423
|
+
"AgentChat: register a new agent"
|
|
1545
1424
|
);
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
};
|
|
1553
|
-
}
|
|
1554
|
-
function describeRegisterStartError(result) {
|
|
1555
|
-
switch (result.reason) {
|
|
1556
|
-
case "invalid-handle":
|
|
1557
|
-
return "That handle is not acceptable. Try a different one (3\u201330 chars \u2014 lowercase letters/digits/hyphens; must start with a letter).";
|
|
1558
|
-
case "handle-taken":
|
|
1559
|
-
return "That handle is already taken. Try a different one.";
|
|
1560
|
-
case "email-limit-reached":
|
|
1561
|
-
return `${result.limit === void 0 ? result.message : `This email already backs ${result.limit} active agents \u2014 the per-email limit.`} Use a different email (a +alias works), recover a key for one of its agents, or paste an existing key.`;
|
|
1562
|
-
case "email-exhausted":
|
|
1563
|
-
return `${result.limit === void 0 ? result.message : `This email has used all ${result.limit} of its lifetime account registrations.`} Use a different email (a +alias works), or paste a key from an existing agent.`;
|
|
1564
|
-
case "rate-limited": {
|
|
1565
|
-
const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
|
|
1566
|
-
return `Rate limited.${wait}`;
|
|
1567
|
-
}
|
|
1568
|
-
case "otp-failed":
|
|
1569
|
-
return "The verification-code email could not be sent. Try again in a minute.";
|
|
1570
|
-
case "network-error":
|
|
1571
|
-
case "server-error":
|
|
1572
|
-
case "validation":
|
|
1573
|
-
default:
|
|
1574
|
-
return result.message;
|
|
1575
|
-
}
|
|
1576
|
-
}
|
|
1577
|
-
function describeRegisterVerifyError(result) {
|
|
1578
|
-
switch (result.reason) {
|
|
1579
|
-
case "expired":
|
|
1580
|
-
return "This code expired. Restart the wizard to receive a new one.";
|
|
1581
|
-
case "invalid-code":
|
|
1582
|
-
return "Too many incorrect codes. Restart the wizard to receive a new one.";
|
|
1583
|
-
case "handle-taken":
|
|
1584
|
-
return "Your chosen handle was claimed by another registration in the meantime. Restart with a different handle.";
|
|
1585
|
-
case "email-limit-reached":
|
|
1586
|
-
return `${result.limit === void 0 ? result.message : `This email reached its limit of ${result.limit} active agents while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`;
|
|
1587
|
-
case "email-exhausted":
|
|
1588
|
-
return `${result.limit === void 0 ? result.message : `This email used all ${result.limit} of its lifetime account registrations while you were verifying.`} Restart with a different email (a +alias works), or paste an existing key.`;
|
|
1589
|
-
case "rate-limited": {
|
|
1590
|
-
const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
|
|
1591
|
-
return `Rate limited.${wait}`;
|
|
1592
|
-
}
|
|
1593
|
-
case "network-error":
|
|
1594
|
-
case "server-error":
|
|
1595
|
-
case "unexpected-shape":
|
|
1596
|
-
case "validation":
|
|
1597
|
-
default:
|
|
1598
|
-
return result.message;
|
|
1599
|
-
}
|
|
1425
|
+
const email = await askText(prompter, LABELS.email, { placeholder: EMAIL_PLACEHOLDER });
|
|
1426
|
+
const handle = await askText(prompter, LABELS.handle);
|
|
1427
|
+
const displayName = (await prompter.text({
|
|
1428
|
+
message: "Display name (shown next to your @handle)",
|
|
1429
|
+
placeholder: "e.g. Anton, Builder Bot, Sasha"
|
|
1430
|
+
})).trim();
|
|
1431
|
+
return { email, handle, ...displayName ? { display_name: displayName } : {} };
|
|
1600
1432
|
}
|
|
1601
|
-
async function
|
|
1602
|
-
const { cfg, accountId, prompter, apiBase } = params;
|
|
1603
|
-
const storedHandle = readAgentchatConfigField(cfg, accountId, "agentHandle");
|
|
1604
|
-
const defaultHandle = storedHandle && isValidHandleShape2(storedHandle) ? storedHandle : void 0;
|
|
1433
|
+
async function recoverInput(prompter, configuredHandle) {
|
|
1605
1434
|
await prompter.note(
|
|
1606
1435
|
[
|
|
1607
|
-
"Recovery
|
|
1608
|
-
"
|
|
1609
|
-
"
|
|
1610
|
-
"is
|
|
1611
|
-
...defaultHandle ? ["", `@${defaultHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
|
|
1436
|
+
"Recovery issues a new API key for an agent you registered. AgentChat",
|
|
1437
|
+
"emails a code to the address the agent registered with; the old key",
|
|
1438
|
+
"stops working once the new one is issued.",
|
|
1439
|
+
...configuredHandle ? ["", `@${configuredHandle} is configured here \u2014 press Enter at the handle prompt to recover it.`] : []
|
|
1612
1440
|
].join("\n"),
|
|
1613
1441
|
"AgentChat: recover a lost API key"
|
|
1614
1442
|
);
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1443
|
+
if (!configuredHandle) return {};
|
|
1444
|
+
const handle = (await prompter.text({ message: LABELS.handle, initialValue: configuredHandle })).trim();
|
|
1445
|
+
return handle ? { handle } : {};
|
|
1446
|
+
}
|
|
1447
|
+
async function notCompleted(prompter, kind) {
|
|
1448
|
+
await prompter.note(
|
|
1449
|
+
`${kind === "register" ? "Registration" : "Recovery"} was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.`,
|
|
1450
|
+
"Falling back to credential entry"
|
|
1451
|
+
);
|
|
1452
|
+
return void 0;
|
|
1453
|
+
}
|
|
1454
|
+
async function runAccountFlow(params) {
|
|
1455
|
+
const { kind, cfg, accountId, prompter } = params;
|
|
1456
|
+
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
|
|
1457
|
+
const input = kind === "register" ? await registerInput(prompter) : await recoverInput(prompter, nonEmpty2(readAgentchatConfigField(cfg, accountId, "agentHandle")));
|
|
1458
|
+
let result;
|
|
1624
1459
|
try {
|
|
1625
|
-
|
|
1460
|
+
result = await integration.account.run({
|
|
1461
|
+
kind,
|
|
1462
|
+
input,
|
|
1463
|
+
labels: LABELS,
|
|
1464
|
+
ask: askThrough(prompter),
|
|
1465
|
+
show: (message) => prompter.note(message, "AgentChat"),
|
|
1466
|
+
sleep: sleepWithProgress(prompter),
|
|
1467
|
+
...accountCallOptions({ apiBase, fetch: fetchWithProgress(prompter) })
|
|
1468
|
+
});
|
|
1626
1469
|
} catch (err) {
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
`${err instanceof Error ? err.message : String(err)}. Try again when the network is available, or paste an existing key instead.`,
|
|
1630
|
-
"Recovery failed"
|
|
1631
|
-
);
|
|
1632
|
-
return "abort";
|
|
1633
|
-
}
|
|
1634
|
-
if (!startResult.ok) {
|
|
1635
|
-
startSpinner.stop("Recovery rejected");
|
|
1636
|
-
await prompter.note(describeRecoverStartError(startResult), "Could not start recovery");
|
|
1637
|
-
return "abort";
|
|
1638
|
-
}
|
|
1639
|
-
startSpinner.stop(startResult.message);
|
|
1640
|
-
const maxCodeAttempts = 3;
|
|
1641
|
-
let verifyResult = null;
|
|
1642
|
-
for (let attempt = 1; attempt <= maxCodeAttempts; attempt += 1) {
|
|
1643
|
-
const code = (await prompter.text({
|
|
1644
|
-
message: attempt === 1 ? `Enter the 6-digit recovery code (check ${email}, including spam)` : `Recovery code (attempt ${attempt}/${maxCodeAttempts})`,
|
|
1645
|
-
placeholder: "123456",
|
|
1646
|
-
validate: (value) => {
|
|
1647
|
-
const trimmed = value.trim();
|
|
1648
|
-
if (!trimmed) return "Code is required";
|
|
1649
|
-
if (!OTP_PATTERN.test(trimmed)) return "Code is 6 digits";
|
|
1650
|
-
return void 0;
|
|
1651
|
-
}
|
|
1652
|
-
})).trim();
|
|
1653
|
-
const verifySpinner = prompter.progress("Verifying code\u2026");
|
|
1654
|
-
try {
|
|
1655
|
-
verifyResult = await recoverAgentVerify({ pendingId: startResult.pendingId, code }, { apiBase });
|
|
1656
|
-
} catch (err) {
|
|
1657
|
-
verifySpinner.stop("Could not reach AgentChat");
|
|
1658
|
-
await prompter.note(
|
|
1659
|
-
`${err instanceof Error ? err.message : String(err)}. Try again, or paste an existing key instead.`,
|
|
1660
|
-
"Recovery failed"
|
|
1661
|
-
);
|
|
1662
|
-
return "abort";
|
|
1663
|
-
}
|
|
1664
|
-
if (verifyResult.ok) {
|
|
1665
|
-
verifySpinner.stop(`Recovered @${verifyResult.handle}`);
|
|
1666
|
-
break;
|
|
1667
|
-
}
|
|
1668
|
-
verifySpinner.stop("Verification failed");
|
|
1669
|
-
if (verifyResult.reason === "invalid-code" && attempt < maxCodeAttempts) {
|
|
1670
|
-
await prompter.note(
|
|
1671
|
-
"That code did not match. Check your email and try again \u2014 if no code arrived, the handle and email may not belong to the same agent.",
|
|
1672
|
-
"Invalid recovery code"
|
|
1673
|
-
);
|
|
1674
|
-
continue;
|
|
1675
|
-
}
|
|
1676
|
-
await prompter.note(describeRecoverVerifyError(verifyResult), "Recovery failed");
|
|
1677
|
-
return "abort";
|
|
1678
|
-
}
|
|
1679
|
-
if (!verifyResult || !verifyResult.ok) {
|
|
1470
|
+
if (err instanceof WizardCancelledError) throw err;
|
|
1471
|
+
const unreached = err instanceof ConnectionError || err instanceof Error && err.name === "AbortError";
|
|
1680
1472
|
await prompter.note(
|
|
1681
|
-
|
|
1682
|
-
"Recovery failed
|
|
1473
|
+
err instanceof Error ? err.message : String(err),
|
|
1474
|
+
unreached ? "Could not reach AgentChat" : `${kind === "register" ? "Registration" : "Recovery"} failed`
|
|
1683
1475
|
);
|
|
1684
|
-
return
|
|
1476
|
+
return notCompleted(prompter, kind);
|
|
1685
1477
|
}
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
patch.agentHandle = verifyResult.handle;
|
|
1689
|
-
}
|
|
1690
|
-
const nextCfg = applyAgentchatAccountPatch(cfg, accountId, patch);
|
|
1478
|
+
if (result.outcome !== "done") return notCompleted(prompter, kind);
|
|
1479
|
+
const nextCfg = applyAgentchatAccountPatch(cfg, accountId, { apiKey: result.apiKey, agentHandle: result.handle });
|
|
1691
1480
|
await prompter.note(
|
|
1692
1481
|
[
|
|
1693
|
-
`Handle:
|
|
1694
|
-
`API key:
|
|
1695
|
-
"",
|
|
1696
|
-
"The previous key for this agent has been revoked."
|
|
1482
|
+
`Handle: @${result.handle}`,
|
|
1483
|
+
`API key: ${redactKey(result.apiKey)} (saved to your OpenClaw config)`
|
|
1697
1484
|
].join("\n"),
|
|
1698
|
-
"AgentChat API key recovered"
|
|
1485
|
+
kind === "register" ? "AgentChat account created" : "AgentChat API key recovered"
|
|
1699
1486
|
);
|
|
1700
1487
|
return {
|
|
1701
1488
|
cfg: nextCfg,
|
|
1702
1489
|
credentialValues: {
|
|
1703
|
-
token:
|
|
1490
|
+
token: result.apiKey,
|
|
1704
1491
|
[JUST_REGISTERED_SENTINEL]: "1"
|
|
1705
1492
|
}
|
|
1706
1493
|
};
|
|
1707
1494
|
}
|
|
1708
|
-
function describeRecoverStartError(result) {
|
|
1709
|
-
switch (result.reason) {
|
|
1710
|
-
case "rate-limited": {
|
|
1711
|
-
const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
|
|
1712
|
-
return `Too many recovery attempts from this network.${wait}`;
|
|
1713
|
-
}
|
|
1714
|
-
case "validation":
|
|
1715
|
-
return `AgentChat rejected the request: ${result.message}`;
|
|
1716
|
-
case "network-error":
|
|
1717
|
-
case "server-error":
|
|
1718
|
-
case "unexpected-shape":
|
|
1719
|
-
default:
|
|
1720
|
-
return result.message;
|
|
1721
|
-
}
|
|
1722
|
-
}
|
|
1723
|
-
function describeRecoverVerifyError(result) {
|
|
1724
|
-
switch (result.reason) {
|
|
1725
|
-
case "expired":
|
|
1726
|
-
return "This recovery code expired. Restart the wizard to request a new one.";
|
|
1727
|
-
case "invalid-code":
|
|
1728
|
-
return "Too many incorrect codes. Restart the wizard to request a new one.";
|
|
1729
|
-
case "handle-required": {
|
|
1730
|
-
const handles = result.handles ?? [];
|
|
1731
|
-
const list = handles.length > 0 ? `
|
|
1732
|
-
|
|
1733
|
-
Agents on this email:
|
|
1734
|
-
${handles.map((h) => ` @${h}`).join("\n")}` : "";
|
|
1735
|
-
return `This email backs more than one agent. Run recovery again and enter the handle you want to recover.${list}`;
|
|
1736
|
-
}
|
|
1737
|
-
case "rate-limited": {
|
|
1738
|
-
const wait = result.retryAfterSeconds ? ` Try again in ${result.retryAfterSeconds}s.` : "";
|
|
1739
|
-
return `Rate limited.${wait}`;
|
|
1740
|
-
}
|
|
1741
|
-
case "network-error":
|
|
1742
|
-
case "server-error":
|
|
1743
|
-
case "unexpected-shape":
|
|
1744
|
-
case "validation":
|
|
1745
|
-
default:
|
|
1746
|
-
return result.message;
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
1495
|
function redactKey(apiKey) {
|
|
1750
1496
|
if (apiKey.length < 12) return "\u2022\u2022\u2022\u2022";
|
|
1751
1497
|
return `${apiKey.slice(0, 8)}\u2026${apiKey.slice(-4)}`;
|
|
1752
1498
|
}
|
|
1499
|
+
async function saveEnteredKey(cfg, accountId, value, key) {
|
|
1500
|
+
if (typeof value !== "string" || !nonEmpty2(key)) return cfg;
|
|
1501
|
+
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
|
|
1502
|
+
let check;
|
|
1503
|
+
try {
|
|
1504
|
+
check = await checkApiKey(key, { apiBase });
|
|
1505
|
+
} catch {
|
|
1506
|
+
check = null;
|
|
1507
|
+
}
|
|
1508
|
+
if (check !== null && !check.ok) return cfg;
|
|
1509
|
+
const handle = check?.handle;
|
|
1510
|
+
const sameKey = readAgentchatConfigField(cfg, accountId, "apiKey") === value;
|
|
1511
|
+
const withKey = applyAgentchatAccountPatch(cfg, accountId, {
|
|
1512
|
+
apiKey: value,
|
|
1513
|
+
// A new key whose handle is unknown must not keep the old key's handle.
|
|
1514
|
+
...handle ? { agentHandle: handle } : sameKey ? {} : { agentHandle: void 0 }
|
|
1515
|
+
});
|
|
1516
|
+
return applyIntegrationConfig(withKey, { accountId, handle, apiKey: key, apiBase: apiBase ?? DEFAULT_API_BASE }).cfg;
|
|
1517
|
+
}
|
|
1753
1518
|
var agentchatSetupWizard = {
|
|
1754
1519
|
channel: AGENTCHAT_CHANNEL_ID,
|
|
1755
1520
|
// AgentChat is one-agent-per-account by product design — the agent IS the
|
|
@@ -1794,9 +1559,9 @@ var agentchatSetupWizard = {
|
|
|
1794
1559
|
"AgentChat is a messaging platform for AI agents \u2014 direct messages,",
|
|
1795
1560
|
"groups, presence, attachments. Registration is free.",
|
|
1796
1561
|
"",
|
|
1797
|
-
"This wizard
|
|
1798
|
-
"API key, or
|
|
1799
|
-
"
|
|
1562
|
+
"This wizard registers a new agent by email code, accepts an existing",
|
|
1563
|
+
"API key, or recovers a lost key by email code \u2014 your choice in the",
|
|
1564
|
+
"next prompt."
|
|
1800
1565
|
]
|
|
1801
1566
|
},
|
|
1802
1567
|
prepare: async ({ cfg, accountId, credentialValues, prompter }) => {
|
|
@@ -1832,7 +1597,7 @@ var agentchatSetupWizard = {
|
|
|
1832
1597
|
options: [
|
|
1833
1598
|
{
|
|
1834
1599
|
value: "register",
|
|
1835
|
-
label: "Register a new agent (email
|
|
1600
|
+
label: "Register a new agent (email code)",
|
|
1836
1601
|
hint: "no account yet \u2014 the wizard creates one"
|
|
1837
1602
|
},
|
|
1838
1603
|
{
|
|
@@ -1842,64 +1607,14 @@ var agentchatSetupWizard = {
|
|
|
1842
1607
|
},
|
|
1843
1608
|
{
|
|
1844
1609
|
value: "recover",
|
|
1845
|
-
label: "Recover a lost API key (
|
|
1610
|
+
label: "Recover a lost API key (email code)",
|
|
1846
1611
|
hint: "an agent exists but its key is gone \u2014 re-issue it"
|
|
1847
1612
|
}
|
|
1848
1613
|
],
|
|
1849
1614
|
initialValue: "register"
|
|
1850
1615
|
});
|
|
1851
|
-
if (choice === "paste")
|
|
1852
|
-
|
|
1853
|
-
}
|
|
1854
|
-
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
|
|
1855
|
-
const recover = async () => {
|
|
1856
|
-
try {
|
|
1857
|
-
const result = await runRecoverFlow({ cfg, accountId, prompter, apiBase });
|
|
1858
|
-
if (result === "abort") {
|
|
1859
|
-
await prompter.note(
|
|
1860
|
-
"Recovery was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
|
|
1861
|
-
"Falling back to credential entry"
|
|
1862
|
-
);
|
|
1863
|
-
return;
|
|
1864
|
-
}
|
|
1865
|
-
return result;
|
|
1866
|
-
} catch (err) {
|
|
1867
|
-
if (err instanceof WizardCancelledError) throw err;
|
|
1868
|
-
await prompter.note(
|
|
1869
|
-
`${err instanceof Error ? err.message : String(err)}`,
|
|
1870
|
-
"Recovery flow failed"
|
|
1871
|
-
);
|
|
1872
|
-
return;
|
|
1873
|
-
}
|
|
1874
|
-
};
|
|
1875
|
-
if (choice === "recover") {
|
|
1876
|
-
return await recover();
|
|
1877
|
-
}
|
|
1878
|
-
let registerOutcome;
|
|
1879
|
-
try {
|
|
1880
|
-
registerOutcome = await runRegisterFlow({ cfg, accountId, prompter, apiBase });
|
|
1881
|
-
} catch (err) {
|
|
1882
|
-
if (err instanceof WizardCancelledError) throw err;
|
|
1883
|
-
await prompter.note(
|
|
1884
|
-
`${err instanceof Error ? err.message : String(err)}`,
|
|
1885
|
-
"Registration flow failed"
|
|
1886
|
-
);
|
|
1887
|
-
return;
|
|
1888
|
-
}
|
|
1889
|
-
if (registerOutcome === "abort") {
|
|
1890
|
-
await prompter.note(
|
|
1891
|
-
"Registration was not completed. You can still paste an existing API key at the next prompt, or cancel the wizard.",
|
|
1892
|
-
"Falling back to credential entry"
|
|
1893
|
-
);
|
|
1894
|
-
return;
|
|
1895
|
-
}
|
|
1896
|
-
if (registerOutcome === "user-chose-paste") {
|
|
1897
|
-
return;
|
|
1898
|
-
}
|
|
1899
|
-
if (registerOutcome === "user-chose-recover") {
|
|
1900
|
-
return await recover();
|
|
1901
|
-
}
|
|
1902
|
-
return registerOutcome;
|
|
1616
|
+
if (choice === "paste") return;
|
|
1617
|
+
return await runAccountFlow({ kind: choice, cfg, accountId, prompter });
|
|
1903
1618
|
},
|
|
1904
1619
|
credentials: [
|
|
1905
1620
|
{
|
|
@@ -1912,9 +1627,9 @@ var agentchatSetupWizard = {
|
|
|
1912
1627
|
inputPrompt: "Paste your AgentChat API key (ac_\u2026)",
|
|
1913
1628
|
helpTitle: "AgentChat API key",
|
|
1914
1629
|
helpLines: [
|
|
1915
|
-
"
|
|
1916
|
-
"
|
|
1917
|
-
"
|
|
1630
|
+
"AgentChat checks the key before it is saved: a key it does not",
|
|
1631
|
+
"accept is not saved, so a bad key fails here instead of flapping",
|
|
1632
|
+
"reconnects at runtime."
|
|
1918
1633
|
],
|
|
1919
1634
|
allowEnv: () => true,
|
|
1920
1635
|
shouldPrompt: ({ credentialValues, currentValue }) => {
|
|
@@ -1932,61 +1647,67 @@ var agentchatSetupWizard = {
|
|
|
1932
1647
|
resolvedValue: configured ? apiKey : void 0,
|
|
1933
1648
|
envValue
|
|
1934
1649
|
};
|
|
1650
|
+
},
|
|
1651
|
+
// The key the person entered, checked before it is saved.
|
|
1652
|
+
applySet: ({ cfg, accountId, value, resolvedValue }) => saveEnteredKey(cfg, accountId, value, resolvedValue),
|
|
1653
|
+
applyUseEnv: ({ cfg, accountId }) => {
|
|
1654
|
+
const key = readApiKeyFromEnv(MIN_API_KEY_LENGTH);
|
|
1655
|
+
return key ? saveEnteredKey(cfg, accountId, key, key) : cfg;
|
|
1935
1656
|
}
|
|
1936
1657
|
}
|
|
1937
1658
|
],
|
|
1938
1659
|
finalize: async ({ cfg, accountId, credentialValues, prompter }) => {
|
|
1939
|
-
const
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
}
|
|
1660
|
+
const stored = nonEmpty2(readAgentchatConfigField(cfg, accountId, "apiKey"));
|
|
1661
|
+
const apiKey = nonEmpty2(credentialValues.token) ?? stored;
|
|
1662
|
+
if (!apiKey) return;
|
|
1943
1663
|
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase");
|
|
1944
|
-
const spinner = prompter.progress("
|
|
1664
|
+
const spinner = prompter.progress("Checking the API key with AgentChat\u2026");
|
|
1665
|
+
let check;
|
|
1945
1666
|
try {
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
const handle = result.agent.handle;
|
|
1950
|
-
const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
|
|
1951
|
-
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
|
|
1952
|
-
const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
|
|
1953
|
-
const failed = placed.steps.filter((s) => s.status === "failed");
|
|
1954
|
-
const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
|
|
1955
|
-
await prompter.note(
|
|
1956
|
-
[
|
|
1957
|
-
...formatPlacement(placed.steps),
|
|
1958
|
-
"",
|
|
1959
|
-
placed.mcp === "added" || placed.steps.some((s) => s.name === "key" && s.status === "changed") ? "Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools." : "The agent is reachable: a peer's message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.",
|
|
1960
|
-
...failed.length > 0 ? ["", "Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry."] : [],
|
|
1961
|
-
...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
|
|
1962
|
-
].join("\n"),
|
|
1963
|
-
"AgentChat integration placed"
|
|
1964
|
-
);
|
|
1965
|
-
const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
|
|
1966
|
-
return { cfg: applied.cfg };
|
|
1967
|
-
}
|
|
1968
|
-
spinner.stop(`API key did not pass the live check (${result.reason})`);
|
|
1667
|
+
check = await checkApiKey(apiKey, { apiBase });
|
|
1668
|
+
} catch (err) {
|
|
1669
|
+
spinner.stop("Could not reach AgentChat to check the key");
|
|
1969
1670
|
await prompter.note(
|
|
1970
1671
|
[
|
|
1971
|
-
|
|
1672
|
+
err instanceof Error ? err.message : String(err),
|
|
1972
1673
|
"",
|
|
1973
|
-
"The config was saved \u2014
|
|
1974
|
-
"to replace the key, or edit ~/.openclaw/config.yaml directly."
|
|
1674
|
+
stored === apiKey ? "The config was saved \u2014 the runtime will retry on startup." : "The key was not saved."
|
|
1975
1675
|
].join("\n"),
|
|
1976
|
-
"AgentChat
|
|
1676
|
+
"AgentChat API unreachable"
|
|
1977
1677
|
);
|
|
1978
|
-
|
|
1979
|
-
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
if (!check.ok) {
|
|
1681
|
+
spinner.stop("AgentChat did not accept the API key");
|
|
1980
1682
|
await prompter.note(
|
|
1981
1683
|
[
|
|
1982
|
-
|
|
1684
|
+
check.message,
|
|
1983
1685
|
"",
|
|
1984
|
-
"
|
|
1686
|
+
stored === apiKey ? "This key is the one in your OpenClaw config. Re-run `openclaw channels add agentchat` \u2192 Replace the API key to recover a lost key or paste another one." : "The key was not saved. Re-run `openclaw channels add agentchat` to paste another key, register a new agent, or recover a lost key."
|
|
1985
1687
|
].join("\n"),
|
|
1986
|
-
"AgentChat API
|
|
1688
|
+
"AgentChat API key not accepted"
|
|
1987
1689
|
);
|
|
1690
|
+
return;
|
|
1988
1691
|
}
|
|
1989
|
-
|
|
1692
|
+
spinner.stop(`Authenticated as @${check.handle}`);
|
|
1693
|
+
const handle = check.handle;
|
|
1694
|
+
const resolvedBase = apiBase ?? DEFAULT_API_BASE;
|
|
1695
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
|
|
1696
|
+
const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
|
|
1697
|
+
const failed = placed.steps.filter((s) => s.status === "failed");
|
|
1698
|
+
const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
|
|
1699
|
+
await prompter.note(
|
|
1700
|
+
[
|
|
1701
|
+
...formatPlacement(placed.steps),
|
|
1702
|
+
"",
|
|
1703
|
+
placed.mcp === "added" || placed.steps.some((s) => s.name === "key" && s.status === "changed") ? "Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools." : "The agent is reachable: a peer's message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.",
|
|
1704
|
+
...failed.length > 0 ? ["", "Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry."] : [],
|
|
1705
|
+
...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
|
|
1706
|
+
].join("\n"),
|
|
1707
|
+
"AgentChat integration placed"
|
|
1708
|
+
);
|
|
1709
|
+
const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
|
|
1710
|
+
return { cfg: applied.cfg };
|
|
1990
1711
|
},
|
|
1991
1712
|
completionNote: {
|
|
1992
1713
|
title: "AgentChat is ready",
|
|
@@ -3187,6 +2908,12 @@ function logEvent(event, logger, metrics) {
|
|
|
3187
2908
|
case "echo":
|
|
3188
2909
|
logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "own echo \u2014 not a wake");
|
|
3189
2910
|
return;
|
|
2911
|
+
case "notice":
|
|
2912
|
+
logger.debug(event.conversationId ? { conversationId: event.conversationId } : {}, "system notice \u2014 acked, not a wake");
|
|
2913
|
+
return;
|
|
2914
|
+
case "gate_chunk":
|
|
2915
|
+
logger.debug({ cycle: event.cycle, chunk: event.index, of: event.of, cards: event.cards, outcome: event.outcome, undecided: event.undecided, ...event.failure ? { failure: event.failure } : {} }, "gate chunk");
|
|
2916
|
+
return;
|
|
3190
2917
|
case "cycle": {
|
|
3191
2918
|
const s = event.summary;
|
|
3192
2919
|
const fields = {
|
|
@@ -3595,7 +3322,7 @@ var agentchatStatusAdapter = {
|
|
|
3595
3322
|
const servedFrom = live?.texts?.source;
|
|
3596
3323
|
const textsSource = live ? servedFrom === "server" || servedFrom === "cache" ? servedFrom : "missing" : void 0;
|
|
3597
3324
|
const socketCounters = live?.metrics?.snapshot?.();
|
|
3598
|
-
const
|
|
3325
|
+
const integration8 = {
|
|
3599
3326
|
mode: readWakeModeFromEnv().mode,
|
|
3600
3327
|
...health ? { state: health.state } : {},
|
|
3601
3328
|
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
@@ -3612,7 +3339,7 @@ var agentchatStatusAdapter = {
|
|
|
3612
3339
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3613
3340
|
mcp,
|
|
3614
3341
|
placement,
|
|
3615
|
-
integration:
|
|
3342
|
+
integration: integration8,
|
|
3616
3343
|
...refusal ? { refusal } : {},
|
|
3617
3344
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3618
3345
|
};
|
|
@@ -3679,7 +3406,7 @@ var agentchatDoctorAdapter = {
|
|
|
3679
3406
|
continue;
|
|
3680
3407
|
}
|
|
3681
3408
|
const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
3682
|
-
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ??
|
|
3409
|
+
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
|
|
3683
3410
|
const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
|
|
3684
3411
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
3685
3412
|
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
|
|
@@ -3718,16 +3445,16 @@ var agentchatDoctorAdapter = {
|
|
|
3718
3445
|
for (const accountId of listConfiguredAccountIds(cfg)) {
|
|
3719
3446
|
if (!isAgentchatAccountEnabled(cfg, accountId)) continue;
|
|
3720
3447
|
const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
3721
|
-
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ??
|
|
3448
|
+
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
|
|
3722
3449
|
bases.set(apiBase, apiKey);
|
|
3723
3450
|
if (apiKey && !readAgentchatConfigField(cfg, accountId, "agentHandle")) {
|
|
3724
3451
|
try {
|
|
3725
|
-
const result = await
|
|
3452
|
+
const result = await checkApiKey(apiKey, { apiBase });
|
|
3726
3453
|
if (result.ok) {
|
|
3727
|
-
next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.
|
|
3728
|
-
changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.
|
|
3454
|
+
next = applyAgentchatAccountPatch(next, accountId, { agentHandle: result.handle });
|
|
3455
|
+
changes.push(`set channels.agentchat${accountId === "default" ? "" : `.accounts.${accountId}`}.agentHandle = ${result.handle}`);
|
|
3729
3456
|
} else {
|
|
3730
|
-
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.
|
|
3457
|
+
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and the key did not pass the live check (${result.code}): ${result.message}`);
|
|
3731
3458
|
}
|
|
3732
3459
|
} catch (err) {
|
|
3733
3460
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] agentHandle not set and AgentChat was not reachable to learn it: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -3782,7 +3509,7 @@ var uiHints = {
|
|
|
3782
3509
|
label: "AgentChat API key",
|
|
3783
3510
|
placeholder: "ac_\u2026",
|
|
3784
3511
|
sensitive: true,
|
|
3785
|
-
help: "The setup wizard registers
|
|
3512
|
+
help: "The setup wizard registers a new agent or recovers a lost key by email code, or accepts an existing ac_\u2026 key; setup checks a key with AgentChat before saving it."
|
|
3786
3513
|
},
|
|
3787
3514
|
apiBase: {
|
|
3788
3515
|
label: "API base URL",
|
|
@@ -3793,19 +3520,26 @@ var uiHints = {
|
|
|
3793
3520
|
agentHandle: {
|
|
3794
3521
|
label: "Agent handle",
|
|
3795
3522
|
placeholder: "my-agent",
|
|
3796
|
-
help: "
|
|
3523
|
+
help: "The handle the API key belongs to, as AgentChat returned it; setup and `openclaw doctor --fix` write it."
|
|
3797
3524
|
},
|
|
3798
3525
|
reconnect: { label: "Reconnect backoff", advanced: true },
|
|
3799
3526
|
ping: { label: "WebSocket ping cadence", advanced: true },
|
|
3800
3527
|
outbound: { label: "Outbound send tuning", advanced: true },
|
|
3801
3528
|
observability: { label: "Logs & metrics", advanced: true }
|
|
3802
3529
|
};
|
|
3803
|
-
|
|
3804
|
-
function validHandle(value) {
|
|
3530
|
+
function handleOf(value) {
|
|
3805
3531
|
if (typeof value !== "string") return void 0;
|
|
3806
3532
|
const bare = value.trim().replace(/^@/, "");
|
|
3807
|
-
return bare.length
|
|
3533
|
+
return bare.length > 0 ? bare : void 0;
|
|
3534
|
+
}
|
|
3535
|
+
function keyRefusal(check) {
|
|
3536
|
+
return [
|
|
3537
|
+
`AgentChat did not accept the API key (${check.code}): ${check.message}`,
|
|
3538
|
+
"The key was not saved. Run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)."
|
|
3539
|
+
].join("\n");
|
|
3808
3540
|
}
|
|
3541
|
+
var keyAskedBeforeWrite = null;
|
|
3542
|
+
var keyDigest = (apiKey) => createHash("sha256").update(apiKey).digest("hex");
|
|
3809
3543
|
function say(runtime, level, line) {
|
|
3810
3544
|
const env = runtime;
|
|
3811
3545
|
const fn = env?.[level];
|
|
@@ -3813,13 +3547,18 @@ function say(runtime, level, line) {
|
|
|
3813
3547
|
}
|
|
3814
3548
|
var agentchatSetupAdapter = {
|
|
3815
3549
|
/**
|
|
3816
|
-
* Pre-write gate:
|
|
3817
|
-
*
|
|
3818
|
-
*
|
|
3550
|
+
* Pre-write gate: a key AgentChat turned away in
|
|
3551
|
+
* `prepareAccountConfigInput` ends here (OpenClaw prints the line and
|
|
3552
|
+
* writes nothing); otherwise a cheap, sync check that the caller supplied
|
|
3553
|
+
* an API key that's at least plausibly shaped. On an OpenClaw without
|
|
3554
|
+
* `prepareAccountConfigInput`, the lifecycle hook refuses a rejected key
|
|
3555
|
+
* before the write.
|
|
3819
3556
|
*/
|
|
3820
3557
|
validateInput({ input }) {
|
|
3558
|
+
const refusal = input.keyRefusal;
|
|
3559
|
+
if (typeof refusal === "string" && refusal.length > 0) return refusal;
|
|
3821
3560
|
if (typeof input.token !== "string" || input.token.trim().length === 0) {
|
|
3822
|
-
return "apiKey is required \u2014 pass via --token, or run `openclaw channels add agentchat` to register a new agent or recover a lost key (
|
|
3561
|
+
return "apiKey is required \u2014 pass via --token, or run `openclaw channels add agentchat` to register a new agent or recover a lost key (email code)";
|
|
3823
3562
|
}
|
|
3824
3563
|
if (input.token.length < MIN_API_KEY_LENGTH) {
|
|
3825
3564
|
return `apiKey looks too short (got ${input.token.length} chars, expect \u2265${MIN_API_KEY_LENGTH})`;
|
|
@@ -3837,29 +3576,31 @@ var agentchatSetupAdapter = {
|
|
|
3837
3576
|
return null;
|
|
3838
3577
|
},
|
|
3839
3578
|
/**
|
|
3840
|
-
*
|
|
3841
|
-
*
|
|
3842
|
-
*
|
|
3843
|
-
*
|
|
3579
|
+
* Ask AgentChat about the key BEFORE the write. Accepted: the handle it
|
|
3580
|
+
* belongs to goes into the same config write OpenClaw already makes.
|
|
3581
|
+
* Turned away (401 / 403): the input carries the refusal, `validateInput`
|
|
3582
|
+
* returns it, and OpenClaw writes nothing. No verdict (unreachable, a
|
|
3583
|
+
* 5xx): the key is written for the runtime to try, as the wizard does.
|
|
3844
3584
|
*/
|
|
3845
|
-
async prepareAccountConfigInput({ accountId, input, runtime }) {
|
|
3585
|
+
async prepareAccountConfigInput({ cfg, accountId, input, runtime }) {
|
|
3846
3586
|
const apiKey = typeof input.token === "string" ? input.token : void 0;
|
|
3847
3587
|
if (!apiKey || apiKey.length < MIN_API_KEY_LENGTH) return input;
|
|
3848
|
-
const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url :
|
|
3588
|
+
const apiBase = typeof input.url === "string" && input.url.length > 0 ? input.url : readAgentchatConfigField(cfg, accountId, "apiBase");
|
|
3589
|
+
keyAskedBeforeWrite = keyDigest(apiKey);
|
|
3849
3590
|
try {
|
|
3850
|
-
const result = await
|
|
3591
|
+
const result = await checkApiKey(apiKey, { apiBase });
|
|
3851
3592
|
if (result.ok) {
|
|
3852
|
-
say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.
|
|
3593
|
+
say(runtime, "log", `[agentchat:${accountId}] authenticated as @${result.handle}`);
|
|
3853
3594
|
try {
|
|
3854
3595
|
placeApiKeyInDotEnv(apiKey);
|
|
3855
3596
|
} catch (err) {
|
|
3856
3597
|
say(runtime, "error", `[agentchat:${accountId}] could not write AGENTCHAT_API_KEY to ${dotEnvPath()}: ${err instanceof Error ? err.message : String(err)}`);
|
|
3857
3598
|
}
|
|
3858
|
-
return { ...input, agentHandle: result.
|
|
3599
|
+
return { ...input, agentHandle: result.handle };
|
|
3859
3600
|
}
|
|
3860
|
-
|
|
3601
|
+
return { ...input, keyRefusal: keyRefusal(result) };
|
|
3861
3602
|
} catch (err) {
|
|
3862
|
-
say(runtime, "error", `[agentchat:${accountId}]
|
|
3603
|
+
say(runtime, "error", `[agentchat:${accountId}] no verdict on the API key, saving it for the runtime to try: ${err instanceof Error ? err.message : String(err)}`);
|
|
3863
3604
|
}
|
|
3864
3605
|
return input;
|
|
3865
3606
|
},
|
|
@@ -3873,12 +3614,12 @@ var agentchatSetupAdapter = {
|
|
|
3873
3614
|
const patch = {};
|
|
3874
3615
|
if (typeof input.token === "string" && input.token.length > 0) patch.apiKey = input.token;
|
|
3875
3616
|
if (typeof input.url === "string" && input.url.length > 0) patch.apiBase = input.url;
|
|
3876
|
-
const handle =
|
|
3617
|
+
const handle = handleOf(input.agentHandle);
|
|
3877
3618
|
if (handle) patch.agentHandle = handle;
|
|
3878
3619
|
const withAccount = applyAgentchatAccountPatch(cfg, accountId, patch);
|
|
3879
3620
|
const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
|
|
3880
3621
|
if (!apiKey) return withAccount;
|
|
3881
|
-
const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ??
|
|
3622
|
+
const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE;
|
|
3882
3623
|
return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
|
|
3883
3624
|
},
|
|
3884
3625
|
/**
|
|
@@ -3889,16 +3630,16 @@ var agentchatSetupAdapter = {
|
|
|
3889
3630
|
async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
|
|
3890
3631
|
const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
3891
3632
|
if (!apiKey) return;
|
|
3892
|
-
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ??
|
|
3893
|
-
let handle =
|
|
3633
|
+
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
|
|
3634
|
+
let handle = handleOf(input.agentHandle) ?? handleOf(readAgentchatConfigField(cfg, accountId, "agentHandle"));
|
|
3894
3635
|
if (!handle) {
|
|
3895
3636
|
try {
|
|
3896
|
-
const result = await
|
|
3637
|
+
const result = await checkApiKey(apiKey, { apiBase });
|
|
3897
3638
|
if (result.ok) {
|
|
3898
|
-
handle = result.
|
|
3639
|
+
handle = result.handle;
|
|
3899
3640
|
say(runtime, "log", `[agentchat:${accountId}] authenticated as @${handle}; run \`openclaw doctor --fix\` to persist channels.agentchat.agentHandle`);
|
|
3900
3641
|
} else {
|
|
3901
|
-
say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.
|
|
3642
|
+
say(runtime, "error", `[agentchat:${accountId}] api key did not pass live check (${result.code}): ${result.message}`);
|
|
3902
3643
|
return;
|
|
3903
3644
|
}
|
|
3904
3645
|
} catch (err) {
|
|
@@ -3932,8 +3673,24 @@ function accountSectionPersistable(cfg, accountId) {
|
|
|
3932
3673
|
if (!raw) return true;
|
|
3933
3674
|
return agentchatChannelConfigSchema.safeParse(raw).success;
|
|
3934
3675
|
}
|
|
3676
|
+
async function refuseRejectedKey(prevCfg, nextCfg, accountId, runtime) {
|
|
3677
|
+
const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
|
|
3678
|
+
if (!apiKey || apiKey === readAgentchatConfigField(prevCfg, accountId, "apiKey")) return;
|
|
3679
|
+
if (keyAskedBeforeWrite === keyDigest(apiKey)) return;
|
|
3680
|
+
let check;
|
|
3681
|
+
try {
|
|
3682
|
+
check = await checkApiKey(apiKey, { apiBase: readAgentchatConfigField(nextCfg, accountId, "apiBase") });
|
|
3683
|
+
} catch (err) {
|
|
3684
|
+
say(runtime, "error", `[agentchat:${accountId}] no verdict on the API key, saving it for the runtime to try: ${err instanceof Error ? err.message : String(err)}`);
|
|
3685
|
+
return;
|
|
3686
|
+
}
|
|
3687
|
+
if (check.ok) return;
|
|
3688
|
+
say(runtime, "error", keyRefusal(check));
|
|
3689
|
+
throw new WizardCancelledError("AgentChat did not accept the API key");
|
|
3690
|
+
}
|
|
3935
3691
|
var agentchatLifecycleAdapter = {
|
|
3936
3692
|
async onAccountConfigChanged({ prevCfg, nextCfg, accountId, runtime }) {
|
|
3693
|
+
await refuseRejectedKey(prevCfg, nextCfg, accountId, runtime);
|
|
3937
3694
|
const wasEnabled = isAccountEnabled(prevCfg, accountId);
|
|
3938
3695
|
const isEnabled = isAccountEnabled(nextCfg, accountId);
|
|
3939
3696
|
if (wasEnabled === isEnabled) return;
|
|
@@ -3949,13 +3706,13 @@ var agentchatLifecycleAdapter = {
|
|
|
3949
3706
|
for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3950
3707
|
return;
|
|
3951
3708
|
}
|
|
3952
|
-
const handle =
|
|
3709
|
+
const handle = handleOf(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
|
|
3953
3710
|
if (!handle) {
|
|
3954
3711
|
say(runtime, "log", `[agentchat:${accountId}] agentHandle not in config \u2014 run \`openclaw doctor --fix\` to learn it from the key and place the identity line`);
|
|
3955
3712
|
return;
|
|
3956
3713
|
}
|
|
3957
3714
|
const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
|
|
3958
|
-
const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ??
|
|
3715
|
+
const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE;
|
|
3959
3716
|
const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
|
|
3960
3717
|
const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
|
|
3961
3718
|
if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);
|
|
@@ -4118,6 +3875,20 @@ function hasAgentChatConfiguredState(config) {
|
|
|
4118
3875
|
return true;
|
|
4119
3876
|
}
|
|
4120
3877
|
|
|
4121
|
-
|
|
3878
|
+
// src/errors.ts
|
|
3879
|
+
var AgentChatChannelError = class extends Error {
|
|
3880
|
+
class_;
|
|
3881
|
+
retryAfterMs;
|
|
3882
|
+
statusCode;
|
|
3883
|
+
constructor(class_, message, options = {}) {
|
|
3884
|
+
super(message, { cause: options.cause });
|
|
3885
|
+
this.name = "AgentChatChannelError";
|
|
3886
|
+
this.class_ = class_;
|
|
3887
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
3888
|
+
this.statusCode = options.statusCode;
|
|
3889
|
+
}
|
|
3890
|
+
};
|
|
3891
|
+
|
|
3892
|
+
export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, IntegrationSocket, MAX_HUNG_TURNS, MCP_SERVER_NAME, OPENCLAW_TOOL_NAMER, OpenClawTexts, accountCallOptions, accountTurns, agentchatChannelEntry, agentchatPlugin, agentchatSetupEntry, agentchatPlugin as agentchatSetupPlugin, checkApiKey, createInMemoryMetrics, createIntegrationLoop, createLoopTurnStarter, createMetrics, createNoopMetrics, createTextsCache, agentchatChannelEntry as default, hasAgentChatConfiguredState, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, loadIdentityLine, mcpToolName, parseChannelConfig, probeHostedMcp, realtimeOptionsFor, spellTextsForOpenClaw, spellToolsForOpenClaw, trackerFor, turnEndOf };
|
|
4122
3893
|
//# sourceMappingURL=index.js.map
|
|
4123
3894
|
//# sourceMappingURL=index.js.map
|