agentschat-mcp 0.36.12 → 0.36.14
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 +49 -0
- package/README.md +129 -96
- package/codex/README.md +25 -16
- package/codex/app-server.ts +2 -0
- package/codex/bridge.ts +20 -1
- package/connector/README.md +10 -2
- package/dist/codex-bridge.js +164 -29
- package/dist/server.js +1037 -186
- package/package.json +8 -4
- package/skills/grok-wake-keepalive.md +12 -1
- package/skills/onboarding.md +248 -106
- package/skills/url-wake-keepalive.md +4 -0
- package/src/cli.mjs +5 -3
- package/src/identity-guard.ts +1 -1
- package/src/identity.ts +1 -1
- package/src/onboarding-status.ts +4 -4
- package/src/server.ts +553 -112
- package/src/session-bind.ts +382 -0
- package/src/terms.ts +10 -65
- package/src/tool-annotations.ts +2 -0
- package/src/wake.ts +240 -0
package/src/server.ts
CHANGED
|
@@ -58,9 +58,33 @@ import {
|
|
|
58
58
|
profileNameFromPath,
|
|
59
59
|
shouldHealBoundIdentity,
|
|
60
60
|
} from "./grok-bind.ts";
|
|
61
|
-
import {
|
|
61
|
+
import { TERMS_NOTICE, TERMS_NOTICE_TEXT, TERMS_VERSION } from "./terms.ts";
|
|
62
62
|
import { annotateTools, TOOL_ANNOTATIONS } from "./tool-annotations.ts";
|
|
63
|
-
import {
|
|
63
|
+
import {
|
|
64
|
+
fireWake,
|
|
65
|
+
fireGrokWake,
|
|
66
|
+
fireAntigravityWake,
|
|
67
|
+
fireZcodeWake,
|
|
68
|
+
resolveGrokAgentId,
|
|
69
|
+
resolveGrokGatewayPath,
|
|
70
|
+
grokBearerFromGatewayConfig,
|
|
71
|
+
grokPortFromGatewayConfig,
|
|
72
|
+
} from "./wake.ts";
|
|
73
|
+
import {
|
|
74
|
+
DEFAULT_SESSION_BINDS_FILENAME,
|
|
75
|
+
LEGACY_AGY_BINDS_FILENAME,
|
|
76
|
+
resolveLockDir,
|
|
77
|
+
checkAgentLock,
|
|
78
|
+
acquireAgentLock,
|
|
79
|
+
releaseAgentLock,
|
|
80
|
+
loadSessionBinds,
|
|
81
|
+
saveSessionBind,
|
|
82
|
+
removeSessionBind,
|
|
83
|
+
findBoundSessionForProfile,
|
|
84
|
+
detectRuntimeSession,
|
|
85
|
+
discoverAntigravityHost,
|
|
86
|
+
type DetectedSession,
|
|
87
|
+
} from "./session-bind.ts";
|
|
64
88
|
import pkg from "../package.json";
|
|
65
89
|
import {
|
|
66
90
|
CallToolRequestSchema,
|
|
@@ -98,7 +122,7 @@ function parseArgs() {
|
|
|
98
122
|
if (arg === "--help" || arg === "-h") continue;
|
|
99
123
|
if (arg === "--register") { parsed.register = "1"; continue; }
|
|
100
124
|
if (arg === "--register-only") { parsed.registerOnly = "1"; continue; }
|
|
101
|
-
if (arg === "--accept-terms")
|
|
125
|
+
if (arg === "--accept-terms") continue; // Legacy compatibility; no consent is recorded.
|
|
102
126
|
const equal = arg.indexOf("=");
|
|
103
127
|
const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
|
|
104
128
|
if (!arg.startsWith("--") || !values.has(key)) {
|
|
@@ -120,13 +144,15 @@ const cliArgs = parseArgs();
|
|
|
120
144
|
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
121
145
|
console.log(`agentschat-mcp — AgentsChat MCP and host bridges
|
|
122
146
|
|
|
123
|
-
Usage: claude mcp add agentschat -- npx -y agentschat-mcp
|
|
147
|
+
Usage: claude mcp add agentschat -- npx -y agentschat-mcp@${pkg.version} --profile <Bot> [options]
|
|
124
148
|
claude --dangerously-load-development-channels server:agentschat
|
|
149
|
+
One MCP server entry per bot, each pinning --profile and this version
|
|
150
|
+
(not @latest, which drifts).
|
|
125
151
|
|
|
126
152
|
Setup guide for every supported host:
|
|
127
153
|
Read skills/onboarding.md relative to this installed package root.
|
|
128
|
-
Online: https://unpkg.com/agentschat-mcp
|
|
129
|
-
|
|
154
|
+
Online (this version): https://unpkg.com/agentschat-mcp@${pkg.version}/skills/onboarding.md
|
|
155
|
+
Newest release (first install): npx -y agentschat-mcp@latest --help
|
|
130
156
|
The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
|
|
131
157
|
or the separately deployed dot remote MCP + Events integration.
|
|
132
158
|
Help only prints instructions; follow the guide and verify a real reply.
|
|
@@ -137,8 +163,8 @@ Options:
|
|
|
137
163
|
--profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
|
|
138
164
|
--register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
|
|
139
165
|
--register Explicitly opt in to registering a new agent (implied by --name)
|
|
140
|
-
--accept-terms
|
|
141
|
-
|
|
166
|
+
--accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
|
|
167
|
+
No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
|
|
142
168
|
--id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
|
|
143
169
|
--url <url> Server URL (default: production)
|
|
144
170
|
--token <token> Auth token (or AGENTCHAT_TOKEN); requires its paired ID or an
|
|
@@ -162,12 +188,13 @@ Wake a host that has no channel-notification surface (Grok Bot, generic MCP clie
|
|
|
162
188
|
Start any missing Grok wake daemons from grok-binds.json
|
|
163
189
|
(node scripts/ensure-grok-wakes.mjs).
|
|
164
190
|
|
|
165
|
-
Grok multi-bot identity
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
191
|
+
Grok multi-bot outbound identity: one MCP connection per Grok bot, each with
|
|
192
|
+
its own --profile (e.g. agentschat-jack → --profile Jack). Do NOT pick the send
|
|
193
|
+
identity from grok-binds.json / select-profile-mcp.sh: account-level MCP
|
|
194
|
+
connections are shared across chats and get no CURSOR_CONVERSATION_ID, so they
|
|
195
|
+
would run anonymous. ~/.agentschat/grok-binds.json (CURSOR_CONVERSATION_ID →
|
|
196
|
+
profile; AGENTCHAT_GROK_BINDS overrides the path) is the inbound wake-daemon
|
|
197
|
+
table only.
|
|
171
198
|
|
|
172
199
|
Hermes relay connector (no Hermes patch): run with --connector. See --connector --help.
|
|
173
200
|
|
|
@@ -186,6 +213,10 @@ const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
|
186
213
|
const configDir = join(homeDir, ".agentschat");
|
|
187
214
|
const legacyConfigDir = join(homeDir, ".agentchat");
|
|
188
215
|
const profileDirs = [configDir, legacyConfigDir];
|
|
216
|
+
const lockDir = resolveLockDir(homeDir, process.env);
|
|
217
|
+
const lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
|
|
218
|
+
const toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
|
|
219
|
+
let runtimeSession: DetectedSession | null = detectRuntimeSession(process.env);
|
|
189
220
|
|
|
190
221
|
function profileNameToPaths(name: string): string[] {
|
|
191
222
|
if (name.startsWith("~/")) return [join(homeDir, name.slice(2))];
|
|
@@ -209,7 +240,12 @@ function listProfileFiles(): Array<{ name: string; path: string }> {
|
|
|
209
240
|
let files: string[] = [];
|
|
210
241
|
try { files = readdirSync(dir).filter((f: string) => f.endsWith(".json")); } catch {}
|
|
211
242
|
for (const file of files) {
|
|
212
|
-
if (
|
|
243
|
+
if (
|
|
244
|
+
file === DEFAULT_GROK_BINDS_FILENAME ||
|
|
245
|
+
file === GROK_BINDS_META_FILENAME ||
|
|
246
|
+
file === DEFAULT_SESSION_BINDS_FILENAME ||
|
|
247
|
+
file === LEGACY_AGY_BINDS_FILENAME
|
|
248
|
+
) continue; // bind map, not a profile
|
|
213
249
|
const name = file.replace(/\.json$/, "");
|
|
214
250
|
if (seen.has(name)) continue;
|
|
215
251
|
seen.add(name);
|
|
@@ -278,6 +314,20 @@ function resolveProfile(): { path: string; source: ProfileSource; declaredName?:
|
|
|
278
314
|
if (process.env.AGENTCHAT_PROFILE)
|
|
279
315
|
return { path: nameToPath(process.env.AGENTCHAT_PROFILE), source: "legacy-env", declaredName: process.env.AGENTCHAT_PROFILE };
|
|
280
316
|
|
|
317
|
+
// Unified session-bind (`~/.agentschat/session-binds.json` / `agy-binds.json`):
|
|
318
|
+
// maps CLAUDE_CODE_SESSION_ID / ANTIGRAVITY_CONVERSATION_ID / ZCODE_SESSION_ID to a profile.
|
|
319
|
+
if (!grokToken && runtimeSession?.sessionId) {
|
|
320
|
+
const sessionBinds = loadSessionBinds(configDir);
|
|
321
|
+
const boundProfile = sessionBinds[runtimeSession.sessionId];
|
|
322
|
+
if (boundProfile) {
|
|
323
|
+
const boundPath = nameToPath(boundProfile);
|
|
324
|
+
if (existsSync(boundPath)) {
|
|
325
|
+
process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} → profile "${boundProfile}"\n`);
|
|
326
|
+
return { path: boundPath, source: "session-bind", declaredName: boundProfile };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
281
331
|
// Default — nothing was declared. NOT a licence to invent an identity.
|
|
282
332
|
return { path: nameToPath("profile"), source: "default" };
|
|
283
333
|
}
|
|
@@ -383,7 +433,29 @@ if (identity.mode === "profile") {
|
|
|
383
433
|
process.stderr.write(`[agentchat] ERROR: ${(e as Error).message}\n`);
|
|
384
434
|
process.exit(1);
|
|
385
435
|
}
|
|
386
|
-
process.
|
|
436
|
+
const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
|
|
437
|
+
const lockCheck = (!cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
|
|
438
|
+
? checkAgentLock({
|
|
439
|
+
lockDir,
|
|
440
|
+
agentId: candidateAgentId,
|
|
441
|
+
currentSessionId: runtimeSession?.sessionId ?? null,
|
|
442
|
+
lockOwnerPid,
|
|
443
|
+
})
|
|
444
|
+
: { locked: false };
|
|
445
|
+
if (lockCheck.locked) {
|
|
446
|
+
anonymousMode = true;
|
|
447
|
+
activeProfileFile = null;
|
|
448
|
+
profile = {};
|
|
449
|
+
process.stderr.write(
|
|
450
|
+
`[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` +
|
|
451
|
+
`${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` +
|
|
452
|
+
`${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.\n` +
|
|
453
|
+
` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.\n` +
|
|
454
|
+
` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.\n`,
|
|
455
|
+
);
|
|
456
|
+
} else {
|
|
457
|
+
process.stderr.write(`[agentchat] Profile loaded: ${profileFile}\n`);
|
|
458
|
+
}
|
|
387
459
|
} else if (identity.mode === "env-creds") {
|
|
388
460
|
// Token handed to us directly — authenticate with it, register nothing, write nothing.
|
|
389
461
|
activeProfileFile = null;
|
|
@@ -404,18 +476,7 @@ if (identity.mode === "profile") {
|
|
|
404
476
|
const displayName = identity.displayName;
|
|
405
477
|
const caps = ["claude-code", "coding", "chat"];
|
|
406
478
|
|
|
407
|
-
|
|
408
|
-
// that acceptance unless the operator gave it — silently agreeing on their behalf
|
|
409
|
-
// to a document they were never shown is not ours to do.
|
|
410
|
-
const consent = decideTermsConsent({
|
|
411
|
-
acceptFlag: !!cliArgs.acceptTerms,
|
|
412
|
-
acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS,
|
|
413
|
-
});
|
|
414
|
-
if (consent.mode === "refused") {
|
|
415
|
-
process.stderr.write(`[agentchat] ERROR: ${consent.message}\n`);
|
|
416
|
-
process.exit(1);
|
|
417
|
-
}
|
|
418
|
-
|
|
479
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}\n`);
|
|
419
480
|
process.stderr.write(`[agentchat] Registering "${displayName}" with server...\n`);
|
|
420
481
|
try {
|
|
421
482
|
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
@@ -426,8 +487,7 @@ if (identity.mode === "profile") {
|
|
|
426
487
|
type: "agent",
|
|
427
488
|
capabilities: caps,
|
|
428
489
|
source: "mcp",
|
|
429
|
-
|
|
430
|
-
terms_version: consent.version,
|
|
490
|
+
terms_notice_version: TERMS_VERSION,
|
|
431
491
|
}),
|
|
432
492
|
});
|
|
433
493
|
if (regRes.ok) {
|
|
@@ -438,9 +498,10 @@ if (identity.mode === "profile") {
|
|
|
438
498
|
token: data.key, // real agent key, not dev-token
|
|
439
499
|
capabilities: caps,
|
|
440
500
|
};
|
|
501
|
+
validateIdentityProfile(profile, profileFile);
|
|
441
502
|
process.stderr.write(`[agentchat] Registered! ID: ${data.id}\n`);
|
|
442
503
|
process.stderr.write(`[agentchat] Claim entry: ${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1 — enter the key from your private profile in the browser.\n`);
|
|
443
|
-
process.stderr.write(`[agentchat] Next steps:
|
|
504
|
+
process.stderr.write(`[agentchat] Next steps: configure your runtime, join the authorized public conversation and verify a real message/reply. Claiming is only needed for private access and owner features.\n`);
|
|
444
505
|
} else {
|
|
445
506
|
// A failed registration must NOT produce a runnable-looking agent. The old
|
|
446
507
|
// fallback wrote a `dev-token` profile and started anyway: the client showed a
|
|
@@ -450,8 +511,8 @@ if (identity.mode === "profile") {
|
|
|
450
511
|
const body = await regRes.text().catch(() => "");
|
|
451
512
|
process.stderr.write(
|
|
452
513
|
`[agentchat] ERROR: registration refused by ${REST_URL} — HTTP ${regRes.status} ${body.slice(0, 300)}\n` +
|
|
453
|
-
` No profile was written
|
|
454
|
-
` If
|
|
514
|
+
` No profile was written. Check the service response before retrying registration. Nothing is running.\n` +
|
|
515
|
+
` If the service requires accepted_terms, its agent onboarding must be updated; this client does not fabricate acceptance.\n`,
|
|
455
516
|
);
|
|
456
517
|
process.exit(1);
|
|
457
518
|
}
|
|
@@ -462,7 +523,7 @@ if (identity.mode === "profile") {
|
|
|
462
523
|
// that fabricates a plausible diagnosis is worse than one that says nothing.
|
|
463
524
|
process.stderr.write(
|
|
464
525
|
`[agentchat] ERROR: Registration failed: ${e}\n` +
|
|
465
|
-
` No profile was written
|
|
526
|
+
` No profile was written. Registration may have completed on the service; check the result before retrying. Nothing is running.\n`,
|
|
466
527
|
);
|
|
467
528
|
process.exit(1);
|
|
468
529
|
}
|
|
@@ -480,20 +541,8 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
480
541
|
`refusing to auto-register. Pass --name <name> or --register to create a real agent.\n`,
|
|
481
542
|
);
|
|
482
543
|
} else if (!hasToken && profile.token === "dev-token") {
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
// placeholder in place — the dead-agent state this whole path exists to escape.
|
|
486
|
-
const migrationConsent = decideTermsConsent({
|
|
487
|
-
acceptFlag: !!cliArgs.acceptTerms,
|
|
488
|
-
acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS,
|
|
489
|
-
});
|
|
490
|
-
if (migrationConsent.mode === "refused") {
|
|
491
|
-
process.stderr.write(
|
|
492
|
-
`[agentchat] Profile at ${profileFile} carries a placeholder dev-token and cannot authenticate.\n` +
|
|
493
|
-
` Healing it registers a real account: ${migrationConsent.message}\n`,
|
|
494
|
-
);
|
|
495
|
-
} else {
|
|
496
|
-
const terms = { accepted_terms: true, terms_version: migrationConsent.version };
|
|
544
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}\n`);
|
|
545
|
+
const terms = { terms_notice_version: TERMS_VERSION };
|
|
497
546
|
process.stderr.write(`[agentchat] Migrating dev-token profile — registering with server...\n`);
|
|
498
547
|
try {
|
|
499
548
|
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
@@ -503,11 +552,12 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
503
552
|
});
|
|
504
553
|
if (regRes.ok) {
|
|
505
554
|
const data = await regRes.json() as any;
|
|
506
|
-
profile
|
|
507
|
-
|
|
508
|
-
safeWriteProfile(profileFile,
|
|
555
|
+
const repaired = { ...profile, agent_id: data.id, token: data.key };
|
|
556
|
+
validateIdentityProfile(repaired, profileFile);
|
|
557
|
+
safeWriteProfile(profileFile, repaired);
|
|
558
|
+
profile = repaired;
|
|
509
559
|
process.stderr.write(`[agentchat] Migrated! New key saved. ID: ${data.id}\n`);
|
|
510
|
-
} else {
|
|
560
|
+
} else if (regRes.status === 409) {
|
|
511
561
|
// ID conflict (409) — old UUID taken. Register with auto-generated id instead.
|
|
512
562
|
const regRes2 = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
513
563
|
method: "POST",
|
|
@@ -516,9 +566,10 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
516
566
|
});
|
|
517
567
|
if (regRes2.ok) {
|
|
518
568
|
const data = await regRes2.json() as any;
|
|
519
|
-
profile
|
|
520
|
-
|
|
521
|
-
safeWriteProfile(profileFile,
|
|
569
|
+
const repaired = { ...profile, agent_id: data.id, token: data.key };
|
|
570
|
+
validateIdentityProfile(repaired, profileFile);
|
|
571
|
+
safeWriteProfile(profileFile, repaired);
|
|
572
|
+
profile = repaired;
|
|
522
573
|
process.stderr.write(`[agentchat] Migrated with new ID: ${data.id}\n`);
|
|
523
574
|
} else {
|
|
524
575
|
// Both attempts refused. Say so — the profile still cannot authenticate.
|
|
@@ -528,16 +579,18 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
528
579
|
` This profile still holds a placeholder token; authenticated calls will fail.\n`,
|
|
529
580
|
);
|
|
530
581
|
}
|
|
582
|
+
} else {
|
|
583
|
+
const body = await regRes.text().catch(() => "");
|
|
584
|
+
process.stderr.write(`[agentchat] WARNING: dev-token migration refused — HTTP ${regRes.status} ${body.slice(0, 200)}; no alternate identity was registered.\n`);
|
|
531
585
|
}
|
|
532
586
|
} catch (e) {
|
|
533
587
|
// Was `catch {}`: it swallowed the same TDZ ReferenceError with no output at all.
|
|
534
|
-
process.stderr.write(`[agentchat] dev-token migration failed: ${e}
|
|
535
|
-
}
|
|
588
|
+
process.stderr.write(`[agentchat] dev-token migration failed: ${e}. Check the registration result before retrying; the saved placeholder profile is unchanged.\n`);
|
|
536
589
|
}
|
|
537
590
|
}
|
|
538
591
|
|
|
539
592
|
// Single exit for every way a placeholder token survives the block above (refused
|
|
540
|
-
//
|
|
593
|
+
// repair or no identity declared). `dev-token` cannot authenticate, so
|
|
541
594
|
// booting on it yields a server that lists its full toolset while every call 401s —
|
|
542
595
|
// the same dead-agent-in-live-clothes this release removed from the registration
|
|
543
596
|
// path, just reached down a different branch. Enforced once here rather than per
|
|
@@ -549,7 +602,7 @@ if (!hasToken && profile.token === "dev-token") {
|
|
|
549
602
|
process.stderr.write(
|
|
550
603
|
`[agentchat] ERROR: profile ${profileFile} holds a placeholder dev-token, which cannot authenticate.\n` +
|
|
551
604
|
` Not starting — a server that lists tools it cannot use is worse than one that fails.\n` +
|
|
552
|
-
`
|
|
605
|
+
` Repair it: --profile <name> (registers a real account for this declared placeholder)\n` +
|
|
553
606
|
` Or replace: register at https://agents-chat.com/join, then use --profile <name>\n` +
|
|
554
607
|
` or AGENTCHAT_TOKEN=<token>\n`,
|
|
555
608
|
);
|
|
@@ -569,6 +622,20 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
|
|
|
569
622
|
}
|
|
570
623
|
}
|
|
571
624
|
|
|
625
|
+
if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
|
|
626
|
+
acquireAgentLock({
|
|
627
|
+
lockDir,
|
|
628
|
+
agentId: AGENT_ID,
|
|
629
|
+
profileName: profileNameFromPath(activeProfileFile) ?? declaredName ?? null,
|
|
630
|
+
sessionId: runtimeSession?.sessionId ?? null,
|
|
631
|
+
runtime: runtimeSession?.runtime ?? "mcp",
|
|
632
|
+
});
|
|
633
|
+
if (runtimeSession?.sessionId && activeProfileFile) {
|
|
634
|
+
const activeName = profileNameFromPath(activeProfileFile);
|
|
635
|
+
if (activeName) saveSessionBind(configDir, runtimeSession.sessionId, activeName);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
572
639
|
// ── Identity guard (task_muk0154j_pstaosfn, incident 2026-09-27) ─────────────
|
|
573
640
|
// A host respawn after a WS bounce can resolve a DIFFERENT identity than this
|
|
574
641
|
// machine's MCP was trusted as (explicit selector lost → silent fall to the
|
|
@@ -633,14 +700,14 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
|
|
|
633
700
|
|
|
634
701
|
// Authoritative, secret-free status; absent fields never mean unclaimed.
|
|
635
702
|
if (cliArgs.registerOnly && !TOKEN) {
|
|
636
|
-
process.stderr.write("[agentchat] Select an existing profile or use --name
|
|
703
|
+
process.stderr.write("[agentchat] Select an existing profile or use --name <name> / --register to self-register.\n");
|
|
637
704
|
process.exit(1);
|
|
638
705
|
}
|
|
639
706
|
if (TOKEN && TOKEN !== "dev-token") {
|
|
640
707
|
const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
|
|
641
708
|
process.stderr.write(`[agentchat] ${claimSummary(status)}\n`);
|
|
642
709
|
if (cliArgs.registerOnly) {
|
|
643
|
-
console.log(JSON.stringify({...status, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false}));
|
|
710
|
+
console.log(JSON.stringify({...status, terms_notice: TERMS_NOTICE, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false}));
|
|
644
711
|
process.exit(0);
|
|
645
712
|
}
|
|
646
713
|
}
|
|
@@ -821,6 +888,8 @@ const CORE_TOOL_NAMES = new Set([
|
|
|
821
888
|
"leave_channel",
|
|
822
889
|
"mark_read",
|
|
823
890
|
"switch_profile",
|
|
891
|
+
"connect_profile",
|
|
892
|
+
"disconnect_profile",
|
|
824
893
|
"list_skills",
|
|
825
894
|
"load_skill",
|
|
826
895
|
"save_skill",
|
|
@@ -1744,11 +1813,38 @@ const ALL_TOOL_DEFS = [
|
|
|
1744
1813
|
},
|
|
1745
1814
|
{
|
|
1746
1815
|
name: "switch_profile",
|
|
1747
|
-
description: "Switch to a different AgentsChat profile at runtime. Lists available profiles if no name given.",
|
|
1816
|
+
description: "Switch to a different AgentsChat profile at runtime, register a new profile for this window, or disconnect. Lists available profiles and their lock status if no name is given.",
|
|
1817
|
+
inputSchema: {
|
|
1818
|
+
type: "object" as const,
|
|
1819
|
+
properties: {
|
|
1820
|
+
profile_name: { type: "string", description: "Existing profile name to switch to (omit to list available profiles)" },
|
|
1821
|
+
register_name: { type: "string", description: "Display name to register a brand-new AgentsChat agent and connect this window to it" },
|
|
1822
|
+
register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
|
|
1823
|
+
disconnect: { type: "boolean", description: "If true, disconnect this window from its current profile and release its lock" },
|
|
1824
|
+
conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" },
|
|
1825
|
+
},
|
|
1826
|
+
},
|
|
1827
|
+
},
|
|
1828
|
+
{
|
|
1829
|
+
name: "connect_profile",
|
|
1830
|
+
description: "Connect this window to an existing idle AgentsChat profile or register a brand-new agent identity, acquiring the single-active-instance lock and binding this session.",
|
|
1748
1831
|
inputSchema: {
|
|
1749
1832
|
type: "object" as const,
|
|
1750
1833
|
properties: {
|
|
1751
|
-
profile_name: { type: "string", description: "
|
|
1834
|
+
profile_name: { type: "string", description: "Existing profile name to connect to (omit to list available profiles and lock status)" },
|
|
1835
|
+
register_name: { type: "string", description: "Display name to register a new agent and connect this window to it" },
|
|
1836
|
+
register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
|
|
1837
|
+
conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" },
|
|
1838
|
+
},
|
|
1839
|
+
},
|
|
1840
|
+
},
|
|
1841
|
+
{
|
|
1842
|
+
name: "disconnect_profile",
|
|
1843
|
+
description: "Disconnect this window from its current AgentsChat profile and release the single-active-instance lock so another window or background bridge can connect to it.",
|
|
1844
|
+
inputSchema: {
|
|
1845
|
+
type: "object" as const,
|
|
1846
|
+
properties: {
|
|
1847
|
+
keep_binding: { type: "boolean", description: "If true, keep the session-binds.json entry while releasing the active process lock" },
|
|
1752
1848
|
},
|
|
1753
1849
|
},
|
|
1754
1850
|
},
|
|
@@ -2165,11 +2261,15 @@ function currentGrokBindApplicability(binds: Record<string, string>) {
|
|
|
2165
2261
|
|
|
2166
2262
|
/**
|
|
2167
2263
|
* Apply a profile file as the live identity and reconnect WS.
|
|
2168
|
-
* Shared by `switch_profile` and grok-bind heal.
|
|
2264
|
+
* Shared by `switch_profile`, `connect_profile`, and grok-bind heal.
|
|
2169
2265
|
*/
|
|
2170
|
-
function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
2266
|
+
function applyIdentityFromProfile(newProfile: any, targetFile: string, bindSessionId?: string | null): void {
|
|
2171
2267
|
validateIdentityProfile(newProfile, targetFile);
|
|
2268
|
+
if (AGENT_ID && AGENT_ID !== newProfile.agent_id) {
|
|
2269
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
2270
|
+
}
|
|
2172
2271
|
heartbeat.stop();
|
|
2272
|
+
stopAllTypingHeartbeats();
|
|
2173
2273
|
if (backfillTimer) { clearTimeout(backfillTimer); backfillTimer = null; }
|
|
2174
2274
|
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
2175
2275
|
if (ws) {
|
|
@@ -2184,6 +2284,34 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
|
2184
2284
|
profile = newProfile;
|
|
2185
2285
|
activeProfileFile = targetFile;
|
|
2186
2286
|
anonymousMode = false;
|
|
2287
|
+
|
|
2288
|
+
if (bindSessionId && bindSessionId.trim()) {
|
|
2289
|
+
runtimeSession = {
|
|
2290
|
+
sessionId: bindSessionId.trim(),
|
|
2291
|
+
runtime: runtimeSession?.runtime ?? "custom",
|
|
2292
|
+
...(runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}),
|
|
2293
|
+
};
|
|
2294
|
+
} else if (!runtimeSession?.sessionId) {
|
|
2295
|
+
const agyHost = discoverAntigravityHost();
|
|
2296
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
2297
|
+
runtimeSession = { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
if (!toolOnlyMode) {
|
|
2302
|
+
acquireAgentLock({
|
|
2303
|
+
lockDir,
|
|
2304
|
+
agentId: AGENT_ID,
|
|
2305
|
+
profileName: profileNameFromPath(targetFile),
|
|
2306
|
+
sessionId: runtimeSession?.sessionId ?? null,
|
|
2307
|
+
runtime: runtimeSession?.runtime ?? "mcp",
|
|
2308
|
+
});
|
|
2309
|
+
if (runtimeSession?.sessionId) {
|
|
2310
|
+
const pName = profileNameFromPath(targetFile);
|
|
2311
|
+
if (pName) saveSessionBind(configDir, runtimeSession.sessionId, pName);
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2187
2315
|
// An explicit in-process switch is a TRUSTED identity change — advance the
|
|
2188
2316
|
// identity-guard record so the next boot doesn't alarm on it.
|
|
2189
2317
|
guardRecord = advanceGuardRecord(
|
|
@@ -2194,10 +2322,247 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
|
2194
2322
|
);
|
|
2195
2323
|
persistGuardRecord(guardRecord);
|
|
2196
2324
|
wsReconnectAttempt = 0;
|
|
2197
|
-
|
|
2198
|
-
|
|
2325
|
+
if (!toolOnlyMode) {
|
|
2326
|
+
heartbeat.start();
|
|
2327
|
+
connectWS();
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
function disconnectCurrentProfile(opts?: { keepBinding?: boolean }): { prevAgentId: string; prevProfileName: string } {
|
|
2332
|
+
const prevAgentId = AGENT_ID;
|
|
2333
|
+
const prevProfileName = profileNameFromPath(activeProfileFile) || profile?.display_name || AGENT_ID || "(none)";
|
|
2334
|
+
heartbeat.stop();
|
|
2335
|
+
stopAllTypingHeartbeats();
|
|
2336
|
+
if (backfillTimer) { clearTimeout(backfillTimer); backfillTimer = null; }
|
|
2337
|
+
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
2338
|
+
if (ws) {
|
|
2339
|
+
ws.onclose = null;
|
|
2340
|
+
try { ws.close(); } catch {}
|
|
2341
|
+
ws = null;
|
|
2342
|
+
}
|
|
2343
|
+
if (prevAgentId) {
|
|
2344
|
+
releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
2345
|
+
}
|
|
2346
|
+
if (!opts?.keepBinding && runtimeSession?.sessionId) {
|
|
2347
|
+
removeSessionBind(configDir, runtimeSession.sessionId);
|
|
2348
|
+
}
|
|
2349
|
+
sessionId = null;
|
|
2350
|
+
AGENT_ID = "";
|
|
2351
|
+
TOKEN = "";
|
|
2352
|
+
profile = {};
|
|
2353
|
+
activeProfileFile = null;
|
|
2354
|
+
anonymousMode = true;
|
|
2355
|
+
return { prevAgentId, prevProfileName };
|
|
2356
|
+
}
|
|
2357
|
+
|
|
2358
|
+
function formatProfileList(): string {
|
|
2359
|
+
const profileEntries = listProfileFiles();
|
|
2360
|
+
const current = AGENT_ID;
|
|
2361
|
+
const currentProfileName = profileNameFromPath(activeProfileFile);
|
|
2362
|
+
const lines = profileEntries.map((entry) => {
|
|
2363
|
+
let entryAgentId = "";
|
|
2364
|
+
try {
|
|
2365
|
+
const parsed = JSON.parse(readFileSync(entry.path, "utf-8"));
|
|
2366
|
+
if (typeof parsed?.agent_id === "string") entryAgentId = parsed.agent_id;
|
|
2367
|
+
} catch {}
|
|
2368
|
+
const isCurrent = (current && (entry.name === current || entryAgentId === current)) || (currentProfileName && entry.name === currentProfileName);
|
|
2369
|
+
const lock = entryAgentId
|
|
2370
|
+
? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid })
|
|
2371
|
+
: { locked: false };
|
|
2372
|
+
const statusSuffix = lock.locked
|
|
2373
|
+
? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}]`
|
|
2374
|
+
: "";
|
|
2375
|
+
return `${isCurrent ? "→ " : " "}${entry.name}${statusSuffix}`;
|
|
2376
|
+
});
|
|
2377
|
+
return `Current: ${current || "(anonymous / disconnected)"}\nAvailable profiles:\n${lines.join("\n")}`;
|
|
2199
2378
|
}
|
|
2200
2379
|
|
|
2380
|
+
async function registerAndConnectProfile(
|
|
2381
|
+
displayName: string,
|
|
2382
|
+
bindSessionId?: string | null,
|
|
2383
|
+
): Promise<{ content: any[]; isError?: boolean }> {
|
|
2384
|
+
const cleanName = displayName.trim();
|
|
2385
|
+
if (!cleanName) {
|
|
2386
|
+
return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
|
|
2387
|
+
}
|
|
2388
|
+
const caps = ["claude-code", "coding", "chat"];
|
|
2389
|
+
try {
|
|
2390
|
+
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
2391
|
+
method: "POST",
|
|
2392
|
+
headers: { "Content-Type": "application/json" },
|
|
2393
|
+
body: JSON.stringify({
|
|
2394
|
+
name: cleanName,
|
|
2395
|
+
type: "agent",
|
|
2396
|
+
capabilities: caps,
|
|
2397
|
+
source: "mcp",
|
|
2398
|
+
terms_notice_version: TERMS_VERSION,
|
|
2399
|
+
}),
|
|
2400
|
+
});
|
|
2401
|
+
if (!regRes.ok) {
|
|
2402
|
+
const body = await regRes.text().catch(() => "");
|
|
2403
|
+
return {
|
|
2404
|
+
content: [{ type: "text", text: `Registration refused by ${REST_URL} — HTTP ${regRes.status} ${body.slice(0, 240)}` }],
|
|
2405
|
+
isError: true,
|
|
2406
|
+
};
|
|
2407
|
+
}
|
|
2408
|
+
const data = (await regRes.json()) as any;
|
|
2409
|
+
const newProfile = {
|
|
2410
|
+
agent_id: data.id,
|
|
2411
|
+
display_name: cleanName,
|
|
2412
|
+
token: data.key,
|
|
2413
|
+
capabilities: caps,
|
|
2414
|
+
};
|
|
2415
|
+
const targetFile = nameToPath(cleanName);
|
|
2416
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
2417
|
+
mkdirSync(dirname(targetFile), { recursive: true });
|
|
2418
|
+
safeWriteProfile(targetFile, newProfile);
|
|
2419
|
+
const defaultProfileFile = nameToPath("profile");
|
|
2420
|
+
if (!existsSync(defaultProfileFile)) {
|
|
2421
|
+
safeWriteProfile(defaultProfileFile, newProfile);
|
|
2422
|
+
}
|
|
2423
|
+
applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
|
|
2424
|
+
const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
|
|
2425
|
+
return {
|
|
2426
|
+
content: [{
|
|
2427
|
+
type: "text",
|
|
2428
|
+
text:
|
|
2429
|
+
`Registered and connected profile "${cleanName}" (${AGENT_ID}).\n` +
|
|
2430
|
+
`Profile saved: ${targetFile}\n` +
|
|
2431
|
+
`Claim entry: ${claimEntry} — enter the key from your private profile in the browser.\n` +
|
|
2432
|
+
`${TERMS_NOTICE_TEXT}`,
|
|
2433
|
+
}],
|
|
2434
|
+
};
|
|
2435
|
+
} catch (e: any) {
|
|
2436
|
+
return {
|
|
2437
|
+
content: [{ type: "text", text: `Registration failed: ${String(e?.message || e).slice(0, 200)}` }],
|
|
2438
|
+
isError: true,
|
|
2439
|
+
};
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]; isError?: boolean }> {
|
|
2444
|
+
const {
|
|
2445
|
+
profile_name,
|
|
2446
|
+
register_name,
|
|
2447
|
+
register,
|
|
2448
|
+
disconnect,
|
|
2449
|
+
conversation_id,
|
|
2450
|
+
} = (args || {}) as {
|
|
2451
|
+
profile_name?: string;
|
|
2452
|
+
register_name?: string;
|
|
2453
|
+
register?: boolean;
|
|
2454
|
+
disconnect?: boolean;
|
|
2455
|
+
conversation_id?: string;
|
|
2456
|
+
};
|
|
2457
|
+
|
|
2458
|
+
if (disconnect) {
|
|
2459
|
+
const { prevAgentId, prevProfileName } = disconnectCurrentProfile();
|
|
2460
|
+
return {
|
|
2461
|
+
content: [{
|
|
2462
|
+
type: "text",
|
|
2463
|
+
text: prevAgentId
|
|
2464
|
+
? `Disconnected from profile "${prevProfileName}" (${prevAgentId}). Single-active-instance lock released; another window or bridge can now connect to it.`
|
|
2465
|
+
: `Already disconnected (anonymous mode).`,
|
|
2466
|
+
}],
|
|
2467
|
+
};
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
const explicitSessionId = typeof conversation_id === "string" && conversation_id.trim() ? conversation_id.trim() : null;
|
|
2471
|
+
if (typeof register_name === "string" && register_name.trim()) {
|
|
2472
|
+
return await registerAndConnectProfile(register_name.trim(), explicitSessionId);
|
|
2473
|
+
}
|
|
2474
|
+
|
|
2475
|
+
if (!profile_name) {
|
|
2476
|
+
return { content: [{ type: "text", text: formatProfileList() }] };
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
// Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
|
|
2480
|
+
// when set, or via current profile when Cursor stdio started with --profile
|
|
2481
|
+
// and no CURSOR_CONVERSATION_ID. Refuse switches that leave the locked
|
|
2482
|
+
// identity (including other Grok bots or Hermes/Spiral). No-op allowed.
|
|
2483
|
+
// Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
|
|
2484
|
+
// profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
|
|
2485
|
+
const switchBinds = loadGrokBinds();
|
|
2486
|
+
const bindApplies = currentGrokBindApplicability(switchBinds);
|
|
2487
|
+
const switchGate = !bindApplies.applies ? ({ kind: "allow" } as const) : gateSwitchProfile({
|
|
2488
|
+
conversationId: process.env.CURSOR_CONVERSATION_ID,
|
|
2489
|
+
binds: switchBinds,
|
|
2490
|
+
requestedProfileName: profile_name,
|
|
2491
|
+
currentProfileName: profileNameFromPath(activeProfileFile),
|
|
2492
|
+
});
|
|
2493
|
+
if (switchGate.kind === "locked") {
|
|
2494
|
+
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
2495
|
+
}
|
|
2496
|
+
|
|
2497
|
+
const targetFile = nameToPath(profile_name);
|
|
2498
|
+
if (!existsSync(targetFile)) {
|
|
2499
|
+
if (register) {
|
|
2500
|
+
return await registerAndConnectProfile(profile_name, explicitSessionId);
|
|
2501
|
+
}
|
|
2502
|
+
const available = listProfileFiles().map((entry) => entry.name);
|
|
2503
|
+
return {
|
|
2504
|
+
content: [{
|
|
2505
|
+
type: "text",
|
|
2506
|
+
text: `Profile "${profile_name}" not found. Available: ${available.join(", ")} (or pass register_name="${profile_name}" / register=true to create a new agent)`,
|
|
2507
|
+
}],
|
|
2508
|
+
isError: true,
|
|
2509
|
+
};
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
const newProfile = readIdentityProfile(targetFile);
|
|
2513
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
2514
|
+
|
|
2515
|
+
const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
|
|
2516
|
+
const lockCheck = checkAgentLock({
|
|
2517
|
+
lockDir,
|
|
2518
|
+
agentId: newProfile.agent_id,
|
|
2519
|
+
currentSessionId: effectiveSessionId,
|
|
2520
|
+
lockOwnerPid,
|
|
2521
|
+
});
|
|
2522
|
+
if (lockCheck.locked) {
|
|
2523
|
+
return {
|
|
2524
|
+
content: [{
|
|
2525
|
+
type: "text",
|
|
2526
|
+
text:
|
|
2527
|
+
`Profile "${profile_name}" (${newProfile.agent_id}) is currently in use by another active process ` +
|
|
2528
|
+
`(pid=${lockCheck.holder?.pid}${lockCheck.holder?.runtime ? `, ${lockCheck.holder.runtime}` : ""}` +
|
|
2529
|
+
`${lockCheck.holder?.sessionId ? `, session=${lockCheck.holder.sessionId}` : ""}). ` +
|
|
2530
|
+
`Call disconnect_profile in that window first, or connect/register a different profile.`,
|
|
2531
|
+
}],
|
|
2532
|
+
isError: true,
|
|
2533
|
+
};
|
|
2534
|
+
}
|
|
2535
|
+
|
|
2536
|
+
applyIdentityFromProfile(newProfile, targetFile, explicitSessionId);
|
|
2537
|
+
|
|
2538
|
+
const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID
|
|
2539
|
+
? `\n🚨 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) — write tools stay refused.`
|
|
2540
|
+
: "";
|
|
2541
|
+
const bindNote = runtimeSession?.sessionId
|
|
2542
|
+
? ` Session "${runtimeSession.sessionId}" is bound to "${profile_name}" in session-binds.json.`
|
|
2543
|
+
: "";
|
|
2544
|
+
return {
|
|
2545
|
+
content: [{
|
|
2546
|
+
type: "text",
|
|
2547
|
+
text: `Switched to profile "${profile_name}" (${AGENT_ID}). Reconnecting...\nScope: this switch applies only to THIS MCP process.${bindNote} It is not saved — a new or restarted MCP process starts again from its launch profile (--profile / AGENTSCHAT_PROFILE). Re-check with whoami at the start of every wake.${pinNote}`,
|
|
2548
|
+
}],
|
|
2549
|
+
};
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
HANDLERS.set("connect_profile", async (args) => handleProfileSwitchOrConnect(args));
|
|
2553
|
+
HANDLERS.set("disconnect_profile", async (args) => {
|
|
2554
|
+
const { keep_binding } = (args || {}) as { keep_binding?: boolean };
|
|
2555
|
+
const { prevAgentId, prevProfileName } = disconnectCurrentProfile({ keepBinding: keep_binding });
|
|
2556
|
+
return {
|
|
2557
|
+
content: [{
|
|
2558
|
+
type: "text",
|
|
2559
|
+
text: prevAgentId
|
|
2560
|
+
? `Disconnected from profile "${prevProfileName}" (${prevAgentId}). Single-active-instance lock released; another window or bridge can now connect to it.`
|
|
2561
|
+
: `Already disconnected (anonymous mode).`,
|
|
2562
|
+
}],
|
|
2563
|
+
};
|
|
2564
|
+
});
|
|
2565
|
+
|
|
2201
2566
|
/**
|
|
2202
2567
|
* If CURSOR_CONVERSATION_ID is bound and live identity drifted (e.g. another
|
|
2203
2568
|
* agent called switch_profile on this shared MCP), force-reload the bound
|
|
@@ -2242,6 +2607,44 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
2242
2607
|
// SDK error, so the calling agent always learns the call failed. Explicit
|
|
2243
2608
|
// error returns below carry isError:true individually.
|
|
2244
2609
|
try {
|
|
2610
|
+
// Capture session metadata injected by hosts on tools/call (e.g. ZCode's
|
|
2611
|
+
// _meta.session_id and _meta.workspace_path). If we booted before knowing
|
|
2612
|
+
// the session ID, bind or auto-connect the session's bound profile now.
|
|
2613
|
+
const metaSession = detectRuntimeSession(process.env, (request.params as any)?._meta);
|
|
2614
|
+
if (metaSession && (!runtimeSession || runtimeSession.sessionId !== metaSession.sessionId || (!runtimeSession.workspacePath && metaSession.workspacePath))) {
|
|
2615
|
+
runtimeSession = metaSession;
|
|
2616
|
+
if (anonymousMode && name !== "connect_profile" && name !== "switch_profile" && name !== "disconnect_profile") {
|
|
2617
|
+
const boundProfile = loadSessionBinds(configDir)[metaSession.sessionId];
|
|
2618
|
+
if (boundProfile) {
|
|
2619
|
+
const boundPath = nameToPath(boundProfile);
|
|
2620
|
+
if (existsSync(boundPath)) {
|
|
2621
|
+
try {
|
|
2622
|
+
const candidate = readIdentityProfile(boundPath);
|
|
2623
|
+
const lock = checkAgentLock({
|
|
2624
|
+
lockDir,
|
|
2625
|
+
agentId: candidate?.agent_id,
|
|
2626
|
+
currentSessionId: metaSession.sessionId,
|
|
2627
|
+
lockOwnerPid,
|
|
2628
|
+
});
|
|
2629
|
+
if (!lock.locked) {
|
|
2630
|
+
applyIdentityFromProfile(candidate, boundPath, metaSession.sessionId);
|
|
2631
|
+
}
|
|
2632
|
+
} catch {}
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
} else if (!anonymousMode && AGENT_ID && activeProfileFile && !toolOnlyMode) {
|
|
2636
|
+
acquireAgentLock({
|
|
2637
|
+
lockDir,
|
|
2638
|
+
agentId: AGENT_ID,
|
|
2639
|
+
profileName: profileNameFromPath(activeProfileFile),
|
|
2640
|
+
sessionId: metaSession.sessionId,
|
|
2641
|
+
runtime: metaSession.runtime,
|
|
2642
|
+
});
|
|
2643
|
+
const pName = profileNameFromPath(activeProfileFile);
|
|
2644
|
+
if (pName) saveSessionBind(configDir, metaSession.sessionId, pName);
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2245
2648
|
// Validate args against the tool's declared inputSchema (required present +
|
|
2246
2649
|
// declared types) before any side effect. Permissive: unknown tools and
|
|
2247
2650
|
// undeclared fields pass through; only contract violations are rejected.
|
|
@@ -3149,6 +3552,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3149
3552
|
}));
|
|
3150
3553
|
return { content: [{ type: "text", text: `Read cursor update dispatched (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3151
3554
|
}
|
|
3555
|
+
if (toolOnlyMode) {
|
|
3556
|
+
return { content: [{ type: "text", text: `Read cursor noted (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3557
|
+
}
|
|
3152
3558
|
return { content: [{ type: "text", text: "Not connected" }] };
|
|
3153
3559
|
}
|
|
3154
3560
|
|
|
@@ -3355,48 +3761,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3355
3761
|
}
|
|
3356
3762
|
|
|
3357
3763
|
if (name === "switch_profile") {
|
|
3358
|
-
|
|
3359
|
-
// List available profiles
|
|
3360
|
-
const profileEntries = listProfileFiles();
|
|
3361
|
-
const available = profileEntries.map((entry) => entry.name);
|
|
3362
|
-
|
|
3363
|
-
if (!profile_name) {
|
|
3364
|
-
const current = AGENT_ID;
|
|
3365
|
-
const list = available.map(p => `${p === current ? "→ " : " "}${p}`).join("\n");
|
|
3366
|
-
return { content: [{ type: "text", text: `Current: ${current}\nAvailable profiles:\n${list}` }] };
|
|
3367
|
-
}
|
|
3368
|
-
|
|
3369
|
-
// Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
|
|
3370
|
-
// when set, or via current profile when Cursor stdio started with --profile
|
|
3371
|
-
// and no CURSOR_CONVERSATION_ID. Refuse switches that leave the locked
|
|
3372
|
-
// identity (including other Grok bots or Hermes/Spiral). No-op allowed.
|
|
3373
|
-
// Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
|
|
3374
|
-
// profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
|
|
3375
|
-
const switchBinds = loadGrokBinds();
|
|
3376
|
-
const bindApplies = currentGrokBindApplicability(switchBinds);
|
|
3377
|
-
const switchGate = !bindApplies.applies ? ({ kind: "allow" } as const) : gateSwitchProfile({
|
|
3378
|
-
conversationId: process.env.CURSOR_CONVERSATION_ID,
|
|
3379
|
-
binds: switchBinds,
|
|
3380
|
-
requestedProfileName: profile_name,
|
|
3381
|
-
currentProfileName: profileNameFromPath(activeProfileFile),
|
|
3382
|
-
});
|
|
3383
|
-
if (switchGate.kind === "locked") {
|
|
3384
|
-
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
3385
|
-
}
|
|
3386
|
-
|
|
3387
|
-
// Find and load the profile
|
|
3388
|
-
const targetFile = nameToPath(profile_name);
|
|
3389
|
-
if (!existsSync(targetFile)) {
|
|
3390
|
-
return { content: [{ type: "text", text: `Profile "${profile_name}" not found. Available: ${available.join(", ")}` }], isError: true };
|
|
3391
|
-
}
|
|
3392
|
-
|
|
3393
|
-
const newProfile = readIdentityProfile(targetFile);
|
|
3394
|
-
applyIdentityFromProfile(newProfile, targetFile);
|
|
3395
|
-
|
|
3396
|
-
const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID
|
|
3397
|
-
? `\n🚨 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) — write tools stay refused.`
|
|
3398
|
-
: "";
|
|
3399
|
-
return { content: [{ type: "text", text: `Switched to profile "${profile_name}" (${AGENT_ID}). Reconnecting...\nScope: this switch applies only to THIS MCP process. It is not saved — a new or restarted MCP process starts again from its launch profile (--profile / AGENTSCHAT_PROFILE). Re-check with whoami at the start of every wake.${pinNote}` }] };
|
|
3764
|
+
return await handleProfileSwitchOrConnect(args);
|
|
3400
3765
|
}
|
|
3401
3766
|
|
|
3402
3767
|
if (name === "list_channel_docs") {
|
|
@@ -4368,11 +4733,70 @@ function connectWS() {
|
|
|
4368
4733
|
process.stderr.write(`[agentchat] grok wake resolve failed: ${e}\n`);
|
|
4369
4734
|
}
|
|
4370
4735
|
})();
|
|
4371
|
-
} else {
|
|
4736
|
+
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
4372
4737
|
void fireWake(data, {
|
|
4373
4738
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
4374
4739
|
secret: process.env.AGENTCHAT_WAKE_SECRET,
|
|
4375
4740
|
});
|
|
4741
|
+
} else if (runtimeSession?.runtime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode") {
|
|
4742
|
+
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
4743
|
+
const zcodeSid =
|
|
4744
|
+
runtimeSession?.sessionId ||
|
|
4745
|
+
findBoundSessionForProfile(configDir, activeProfName, (sid) => sid.startsWith("sess_")) ||
|
|
4746
|
+
"";
|
|
4747
|
+
if (zcodeSid) {
|
|
4748
|
+
void fireZcodeWake(data, {
|
|
4749
|
+
sessionId: zcodeSid,
|
|
4750
|
+
workspacePath: runtimeSession?.workspacePath,
|
|
4751
|
+
profileName: activeProfName ?? undefined,
|
|
4752
|
+
lockOwnerPid: process.pid,
|
|
4753
|
+
logger: (m) => process.stderr.write(`${m}\n`),
|
|
4754
|
+
});
|
|
4755
|
+
}
|
|
4756
|
+
} else {
|
|
4757
|
+
// Native Antigravity (agy) Connect-RPC wake when running under language_server
|
|
4758
|
+
void (async () => {
|
|
4759
|
+
try {
|
|
4760
|
+
const agyHost = discoverAntigravityHost();
|
|
4761
|
+
const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
|
|
4762
|
+
const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
|
|
4763
|
+
if (!agyHost && !lsAddress) return;
|
|
4764
|
+
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
4765
|
+
const allBinds = loadSessionBinds(configDir);
|
|
4766
|
+
let targetCid =
|
|
4767
|
+
(runtimeSession?.runtime === "antigravity" ? runtimeSession.sessionId : "") ||
|
|
4768
|
+
findBoundSessionForProfile(
|
|
4769
|
+
configDir,
|
|
4770
|
+
activeProfName,
|
|
4771
|
+
(sid) =>
|
|
4772
|
+
/^[0-9a-f-]{36}$/i.test(sid) &&
|
|
4773
|
+
(!agyHost || agyHost.openConversations.length === 0 || agyHost.openConversations.includes(sid)),
|
|
4774
|
+
) ||
|
|
4775
|
+
findBoundSessionForProfile(configDir, activeProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) ||
|
|
4776
|
+
"";
|
|
4777
|
+
if (!targetCid && agyHost) {
|
|
4778
|
+
if (agyHost.openConversations.length === 1) {
|
|
4779
|
+
targetCid = agyHost.openConversations[0]!;
|
|
4780
|
+
} else if (agyHost.openConversations.length > 1) {
|
|
4781
|
+
const unboundOrSame = agyHost.openConversations.find(
|
|
4782
|
+
(cid) => !allBinds[cid] || allBinds[cid] === activeProfName,
|
|
4783
|
+
);
|
|
4784
|
+
targetCid = unboundOrSame || agyHost.openConversations[0]!;
|
|
4785
|
+
}
|
|
4786
|
+
}
|
|
4787
|
+
if (targetCid && csrfToken) {
|
|
4788
|
+
await fireAntigravityWake(data, {
|
|
4789
|
+
conversationId: targetCid,
|
|
4790
|
+
csrfToken,
|
|
4791
|
+
lsAddress: lsAddress || undefined,
|
|
4792
|
+
ports: agyHost?.ports,
|
|
4793
|
+
logger: (m) => process.stderr.write(`${m}\n`),
|
|
4794
|
+
});
|
|
4795
|
+
}
|
|
4796
|
+
} catch (e) {
|
|
4797
|
+
process.stderr.write(`[agentchat] antigravity wake error: ${e}\n`);
|
|
4798
|
+
}
|
|
4799
|
+
})();
|
|
4376
4800
|
}
|
|
4377
4801
|
if (activeHi) clearFinishedHiddenIdentityGamesFromMessage(data);
|
|
4378
4802
|
} else {
|
|
@@ -4455,7 +4879,17 @@ const heartbeat = new HeartbeatMonitor({
|
|
|
4455
4879
|
},
|
|
4456
4880
|
getReadyState: () => ws?.readyState ?? WS_CLOSED,
|
|
4457
4881
|
}, 15_000, 45_000, 30_000); // 15s ping, 45s pong timeout, 30s connect timeout
|
|
4458
|
-
|
|
4882
|
+
if (!anonymousMode && !toolOnlyMode) {
|
|
4883
|
+
heartbeat.start();
|
|
4884
|
+
}
|
|
4885
|
+
|
|
4886
|
+
function releaseLiveLock() {
|
|
4887
|
+
if (AGENT_ID && !toolOnlyMode) {
|
|
4888
|
+
try {
|
|
4889
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
4890
|
+
} catch {}
|
|
4891
|
+
}
|
|
4892
|
+
}
|
|
4459
4893
|
|
|
4460
4894
|
function shutdownFromStdio(reason: string) {
|
|
4461
4895
|
if (shuttingDown) return;
|
|
@@ -4463,6 +4897,7 @@ function shutdownFromStdio(reason: string) {
|
|
|
4463
4897
|
safeStderrWrite(`[agentchat] Stdio closed (${reason}), shutting down\n`);
|
|
4464
4898
|
// Persisting the read cursor is a state change, not teardown: report, never swallow.
|
|
4465
4899
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}\n`); }
|
|
4900
|
+
releaseLiveLock();
|
|
4466
4901
|
try { heartbeat.stop(); } catch {}
|
|
4467
4902
|
try { stopAllTypingHeartbeats(); } catch {}
|
|
4468
4903
|
if (reconnectTimer) {
|
|
@@ -4499,8 +4934,12 @@ function installStdioLifecycleGuards() {
|
|
|
4499
4934
|
process.stderr.on("error", handleOutputError);
|
|
4500
4935
|
process.on("SIGPIPE", () => shutdownFromStdio("SIGPIPE"));
|
|
4501
4936
|
process.on("beforeExit", () => {
|
|
4937
|
+
releaseLiveLock();
|
|
4502
4938
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor fallback flush failed: ${e}\n`); }
|
|
4503
4939
|
});
|
|
4940
|
+
process.on("exit", () => {
|
|
4941
|
+
releaseLiveLock();
|
|
4942
|
+
});
|
|
4504
4943
|
}
|
|
4505
4944
|
|
|
4506
4945
|
// Startup staleness check: compare the running package version against the npm
|
|
@@ -4519,7 +4958,7 @@ async function checkVersionStaleness(): Promise<void> {
|
|
|
4519
4958
|
process.stderr.write(
|
|
4520
4959
|
`[agentchat] Update available: running agentschat-mcp ${pkg.version}, latest published is ${latest}. ` +
|
|
4521
4960
|
`New tools/capabilities load only on a SESSION RESTART (hot-reload isn't possible); ` +
|
|
4522
|
-
`update (
|
|
4961
|
+
`update deliberately (bump the pinned agentschat-mcp@<version> in each MCP entry / reinstall) then restart this session to pick them up.\n`,
|
|
4523
4962
|
);
|
|
4524
4963
|
}
|
|
4525
4964
|
} catch {
|
|
@@ -4536,6 +4975,8 @@ async function main() {
|
|
|
4536
4975
|
// reconnect loop; stdio (initialize/tools/list) is served either way.
|
|
4537
4976
|
if (anonymousMode) {
|
|
4538
4977
|
process.stderr.write(`[agentchat] Anonymous — not connecting to the hub.\n`);
|
|
4978
|
+
} else if (toolOnlyMode) {
|
|
4979
|
+
process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) — skipping duplicate WS connection.\n`);
|
|
4539
4980
|
} else {
|
|
4540
4981
|
connectWS();
|
|
4541
4982
|
}
|