agentschat-mcp 0.36.13 → 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 +15 -0
- package/README.md +63 -45
- 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-bots.js +419 -512
- package/dist/codex-bridge.js +609 -567
- package/dist/connector.js +5 -5
- package/dist/server.js +1019 -174
- package/package.json +2 -1
- package/skills/grok-wake-keepalive.md +1 -1
- package/skills/onboarding.md +184 -108
- 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 +540 -102
- 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)) {
|
|
@@ -139,8 +163,8 @@ Options:
|
|
|
139
163
|
--profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
|
|
140
164
|
--register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
|
|
141
165
|
--register Explicitly opt in to registering a new agent (implied by --name)
|
|
142
|
-
--accept-terms
|
|
143
|
-
|
|
166
|
+
--accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
|
|
167
|
+
No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
|
|
144
168
|
--id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
|
|
145
169
|
--url <url> Server URL (default: production)
|
|
146
170
|
--token <token> Auth token (or AGENTCHAT_TOKEN); requires its paired ID or an
|
|
@@ -189,6 +213,10 @@ const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
|
189
213
|
const configDir = join(homeDir, ".agentschat");
|
|
190
214
|
const legacyConfigDir = join(homeDir, ".agentchat");
|
|
191
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);
|
|
192
220
|
|
|
193
221
|
function profileNameToPaths(name: string): string[] {
|
|
194
222
|
if (name.startsWith("~/")) return [join(homeDir, name.slice(2))];
|
|
@@ -212,7 +240,12 @@ function listProfileFiles(): Array<{ name: string; path: string }> {
|
|
|
212
240
|
let files: string[] = [];
|
|
213
241
|
try { files = readdirSync(dir).filter((f: string) => f.endsWith(".json")); } catch {}
|
|
214
242
|
for (const file of files) {
|
|
215
|
-
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
|
|
216
249
|
const name = file.replace(/\.json$/, "");
|
|
217
250
|
if (seen.has(name)) continue;
|
|
218
251
|
seen.add(name);
|
|
@@ -281,6 +314,20 @@ function resolveProfile(): { path: string; source: ProfileSource; declaredName?:
|
|
|
281
314
|
if (process.env.AGENTCHAT_PROFILE)
|
|
282
315
|
return { path: nameToPath(process.env.AGENTCHAT_PROFILE), source: "legacy-env", declaredName: process.env.AGENTCHAT_PROFILE };
|
|
283
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
|
+
|
|
284
331
|
// Default — nothing was declared. NOT a licence to invent an identity.
|
|
285
332
|
return { path: nameToPath("profile"), source: "default" };
|
|
286
333
|
}
|
|
@@ -386,7 +433,29 @@ if (identity.mode === "profile") {
|
|
|
386
433
|
process.stderr.write(`[agentchat] ERROR: ${(e as Error).message}\n`);
|
|
387
434
|
process.exit(1);
|
|
388
435
|
}
|
|
389
|
-
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
|
+
}
|
|
390
459
|
} else if (identity.mode === "env-creds") {
|
|
391
460
|
// Token handed to us directly — authenticate with it, register nothing, write nothing.
|
|
392
461
|
activeProfileFile = null;
|
|
@@ -407,18 +476,7 @@ if (identity.mode === "profile") {
|
|
|
407
476
|
const displayName = identity.displayName;
|
|
408
477
|
const caps = ["claude-code", "coding", "chat"];
|
|
409
478
|
|
|
410
|
-
|
|
411
|
-
// that acceptance unless the operator gave it — silently agreeing on their behalf
|
|
412
|
-
// to a document they were never shown is not ours to do.
|
|
413
|
-
const consent = decideTermsConsent({
|
|
414
|
-
acceptFlag: !!cliArgs.acceptTerms,
|
|
415
|
-
acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS,
|
|
416
|
-
});
|
|
417
|
-
if (consent.mode === "refused") {
|
|
418
|
-
process.stderr.write(`[agentchat] ERROR: ${consent.message}\n`);
|
|
419
|
-
process.exit(1);
|
|
420
|
-
}
|
|
421
|
-
|
|
479
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}\n`);
|
|
422
480
|
process.stderr.write(`[agentchat] Registering "${displayName}" with server...\n`);
|
|
423
481
|
try {
|
|
424
482
|
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
@@ -429,8 +487,7 @@ if (identity.mode === "profile") {
|
|
|
429
487
|
type: "agent",
|
|
430
488
|
capabilities: caps,
|
|
431
489
|
source: "mcp",
|
|
432
|
-
|
|
433
|
-
terms_version: consent.version,
|
|
490
|
+
terms_notice_version: TERMS_VERSION,
|
|
434
491
|
}),
|
|
435
492
|
});
|
|
436
493
|
if (regRes.ok) {
|
|
@@ -441,9 +498,10 @@ if (identity.mode === "profile") {
|
|
|
441
498
|
token: data.key, // real agent key, not dev-token
|
|
442
499
|
capabilities: caps,
|
|
443
500
|
};
|
|
501
|
+
validateIdentityProfile(profile, profileFile);
|
|
444
502
|
process.stderr.write(`[agentchat] Registered! ID: ${data.id}\n`);
|
|
445
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`);
|
|
446
|
-
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`);
|
|
447
505
|
} else {
|
|
448
506
|
// A failed registration must NOT produce a runnable-looking agent. The old
|
|
449
507
|
// fallback wrote a `dev-token` profile and started anyway: the client showed a
|
|
@@ -453,8 +511,8 @@ if (identity.mode === "profile") {
|
|
|
453
511
|
const body = await regRes.text().catch(() => "");
|
|
454
512
|
process.stderr.write(
|
|
455
513
|
`[agentchat] ERROR: registration refused by ${REST_URL} — HTTP ${regRes.status} ${body.slice(0, 300)}\n` +
|
|
456
|
-
` No profile was written
|
|
457
|
-
` 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`,
|
|
458
516
|
);
|
|
459
517
|
process.exit(1);
|
|
460
518
|
}
|
|
@@ -465,7 +523,7 @@ if (identity.mode === "profile") {
|
|
|
465
523
|
// that fabricates a plausible diagnosis is worse than one that says nothing.
|
|
466
524
|
process.stderr.write(
|
|
467
525
|
`[agentchat] ERROR: Registration failed: ${e}\n` +
|
|
468
|
-
` 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`,
|
|
469
527
|
);
|
|
470
528
|
process.exit(1);
|
|
471
529
|
}
|
|
@@ -483,20 +541,8 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
483
541
|
`refusing to auto-register. Pass --name <name> or --register to create a real agent.\n`,
|
|
484
542
|
);
|
|
485
543
|
} else if (!hasToken && profile.token === "dev-token") {
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
// placeholder in place — the dead-agent state this whole path exists to escape.
|
|
489
|
-
const migrationConsent = decideTermsConsent({
|
|
490
|
-
acceptFlag: !!cliArgs.acceptTerms,
|
|
491
|
-
acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS,
|
|
492
|
-
});
|
|
493
|
-
if (migrationConsent.mode === "refused") {
|
|
494
|
-
process.stderr.write(
|
|
495
|
-
`[agentchat] Profile at ${profileFile} carries a placeholder dev-token and cannot authenticate.\n` +
|
|
496
|
-
` Healing it registers a real account: ${migrationConsent.message}\n`,
|
|
497
|
-
);
|
|
498
|
-
} else {
|
|
499
|
-
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 };
|
|
500
546
|
process.stderr.write(`[agentchat] Migrating dev-token profile — registering with server...\n`);
|
|
501
547
|
try {
|
|
502
548
|
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
@@ -506,11 +552,12 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
506
552
|
});
|
|
507
553
|
if (regRes.ok) {
|
|
508
554
|
const data = await regRes.json() as any;
|
|
509
|
-
profile
|
|
510
|
-
|
|
511
|
-
safeWriteProfile(profileFile,
|
|
555
|
+
const repaired = { ...profile, agent_id: data.id, token: data.key };
|
|
556
|
+
validateIdentityProfile(repaired, profileFile);
|
|
557
|
+
safeWriteProfile(profileFile, repaired);
|
|
558
|
+
profile = repaired;
|
|
512
559
|
process.stderr.write(`[agentchat] Migrated! New key saved. ID: ${data.id}\n`);
|
|
513
|
-
} else {
|
|
560
|
+
} else if (regRes.status === 409) {
|
|
514
561
|
// ID conflict (409) — old UUID taken. Register with auto-generated id instead.
|
|
515
562
|
const regRes2 = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
516
563
|
method: "POST",
|
|
@@ -519,9 +566,10 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
519
566
|
});
|
|
520
567
|
if (regRes2.ok) {
|
|
521
568
|
const data = await regRes2.json() as any;
|
|
522
|
-
profile
|
|
523
|
-
|
|
524
|
-
safeWriteProfile(profileFile,
|
|
569
|
+
const repaired = { ...profile, agent_id: data.id, token: data.key };
|
|
570
|
+
validateIdentityProfile(repaired, profileFile);
|
|
571
|
+
safeWriteProfile(profileFile, repaired);
|
|
572
|
+
profile = repaired;
|
|
525
573
|
process.stderr.write(`[agentchat] Migrated with new ID: ${data.id}\n`);
|
|
526
574
|
} else {
|
|
527
575
|
// Both attempts refused. Say so — the profile still cannot authenticate.
|
|
@@ -531,16 +579,18 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
531
579
|
` This profile still holds a placeholder token; authenticated calls will fail.\n`,
|
|
532
580
|
);
|
|
533
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`);
|
|
534
585
|
}
|
|
535
586
|
} catch (e) {
|
|
536
587
|
// Was `catch {}`: it swallowed the same TDZ ReferenceError with no output at all.
|
|
537
|
-
process.stderr.write(`[agentchat] dev-token migration failed: ${e}
|
|
538
|
-
}
|
|
588
|
+
process.stderr.write(`[agentchat] dev-token migration failed: ${e}. Check the registration result before retrying; the saved placeholder profile is unchanged.\n`);
|
|
539
589
|
}
|
|
540
590
|
}
|
|
541
591
|
|
|
542
592
|
// Single exit for every way a placeholder token survives the block above (refused
|
|
543
|
-
//
|
|
593
|
+
// repair or no identity declared). `dev-token` cannot authenticate, so
|
|
544
594
|
// booting on it yields a server that lists its full toolset while every call 401s —
|
|
545
595
|
// the same dead-agent-in-live-clothes this release removed from the registration
|
|
546
596
|
// path, just reached down a different branch. Enforced once here rather than per
|
|
@@ -552,7 +602,7 @@ if (!hasToken && profile.token === "dev-token") {
|
|
|
552
602
|
process.stderr.write(
|
|
553
603
|
`[agentchat] ERROR: profile ${profileFile} holds a placeholder dev-token, which cannot authenticate.\n` +
|
|
554
604
|
` Not starting — a server that lists tools it cannot use is worse than one that fails.\n` +
|
|
555
|
-
`
|
|
605
|
+
` Repair it: --profile <name> (registers a real account for this declared placeholder)\n` +
|
|
556
606
|
` Or replace: register at https://agents-chat.com/join, then use --profile <name>\n` +
|
|
557
607
|
` or AGENTCHAT_TOKEN=<token>\n`,
|
|
558
608
|
);
|
|
@@ -572,6 +622,20 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
|
|
|
572
622
|
}
|
|
573
623
|
}
|
|
574
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
|
+
|
|
575
639
|
// ── Identity guard (task_muk0154j_pstaosfn, incident 2026-09-27) ─────────────
|
|
576
640
|
// A host respawn after a WS bounce can resolve a DIFFERENT identity than this
|
|
577
641
|
// machine's MCP was trusted as (explicit selector lost → silent fall to the
|
|
@@ -636,14 +700,14 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
|
|
|
636
700
|
|
|
637
701
|
// Authoritative, secret-free status; absent fields never mean unclaimed.
|
|
638
702
|
if (cliArgs.registerOnly && !TOKEN) {
|
|
639
|
-
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");
|
|
640
704
|
process.exit(1);
|
|
641
705
|
}
|
|
642
706
|
if (TOKEN && TOKEN !== "dev-token") {
|
|
643
707
|
const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
|
|
644
708
|
process.stderr.write(`[agentchat] ${claimSummary(status)}\n`);
|
|
645
709
|
if (cliArgs.registerOnly) {
|
|
646
|
-
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}));
|
|
647
711
|
process.exit(0);
|
|
648
712
|
}
|
|
649
713
|
}
|
|
@@ -824,6 +888,8 @@ const CORE_TOOL_NAMES = new Set([
|
|
|
824
888
|
"leave_channel",
|
|
825
889
|
"mark_read",
|
|
826
890
|
"switch_profile",
|
|
891
|
+
"connect_profile",
|
|
892
|
+
"disconnect_profile",
|
|
827
893
|
"list_skills",
|
|
828
894
|
"load_skill",
|
|
829
895
|
"save_skill",
|
|
@@ -1747,11 +1813,38 @@ const ALL_TOOL_DEFS = [
|
|
|
1747
1813
|
},
|
|
1748
1814
|
{
|
|
1749
1815
|
name: "switch_profile",
|
|
1750
|
-
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.",
|
|
1751
1831
|
inputSchema: {
|
|
1752
1832
|
type: "object" as const,
|
|
1753
1833
|
properties: {
|
|
1754
|
-
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" },
|
|
1755
1848
|
},
|
|
1756
1849
|
},
|
|
1757
1850
|
},
|
|
@@ -2168,11 +2261,15 @@ function currentGrokBindApplicability(binds: Record<string, string>) {
|
|
|
2168
2261
|
|
|
2169
2262
|
/**
|
|
2170
2263
|
* Apply a profile file as the live identity and reconnect WS.
|
|
2171
|
-
* Shared by `switch_profile` and grok-bind heal.
|
|
2264
|
+
* Shared by `switch_profile`, `connect_profile`, and grok-bind heal.
|
|
2172
2265
|
*/
|
|
2173
|
-
function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
2266
|
+
function applyIdentityFromProfile(newProfile: any, targetFile: string, bindSessionId?: string | null): void {
|
|
2174
2267
|
validateIdentityProfile(newProfile, targetFile);
|
|
2268
|
+
if (AGENT_ID && AGENT_ID !== newProfile.agent_id) {
|
|
2269
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
2270
|
+
}
|
|
2175
2271
|
heartbeat.stop();
|
|
2272
|
+
stopAllTypingHeartbeats();
|
|
2176
2273
|
if (backfillTimer) { clearTimeout(backfillTimer); backfillTimer = null; }
|
|
2177
2274
|
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
2178
2275
|
if (ws) {
|
|
@@ -2187,6 +2284,34 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
|
2187
2284
|
profile = newProfile;
|
|
2188
2285
|
activeProfileFile = targetFile;
|
|
2189
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
|
+
|
|
2190
2315
|
// An explicit in-process switch is a TRUSTED identity change — advance the
|
|
2191
2316
|
// identity-guard record so the next boot doesn't alarm on it.
|
|
2192
2317
|
guardRecord = advanceGuardRecord(
|
|
@@ -2197,10 +2322,247 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
|
2197
2322
|
);
|
|
2198
2323
|
persistGuardRecord(guardRecord);
|
|
2199
2324
|
wsReconnectAttempt = 0;
|
|
2200
|
-
|
|
2201
|
-
|
|
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")}`;
|
|
2202
2378
|
}
|
|
2203
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
|
+
|
|
2204
2566
|
/**
|
|
2205
2567
|
* If CURSOR_CONVERSATION_ID is bound and live identity drifted (e.g. another
|
|
2206
2568
|
* agent called switch_profile on this shared MCP), force-reload the bound
|
|
@@ -2245,6 +2607,44 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
2245
2607
|
// SDK error, so the calling agent always learns the call failed. Explicit
|
|
2246
2608
|
// error returns below carry isError:true individually.
|
|
2247
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
|
+
|
|
2248
2648
|
// Validate args against the tool's declared inputSchema (required present +
|
|
2249
2649
|
// declared types) before any side effect. Permissive: unknown tools and
|
|
2250
2650
|
// undeclared fields pass through; only contract violations are rejected.
|
|
@@ -3152,6 +3552,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3152
3552
|
}));
|
|
3153
3553
|
return { content: [{ type: "text", text: `Read cursor update dispatched (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3154
3554
|
}
|
|
3555
|
+
if (toolOnlyMode) {
|
|
3556
|
+
return { content: [{ type: "text", text: `Read cursor noted (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3557
|
+
}
|
|
3155
3558
|
return { content: [{ type: "text", text: "Not connected" }] };
|
|
3156
3559
|
}
|
|
3157
3560
|
|
|
@@ -3358,48 +3761,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3358
3761
|
}
|
|
3359
3762
|
|
|
3360
3763
|
if (name === "switch_profile") {
|
|
3361
|
-
|
|
3362
|
-
// List available profiles
|
|
3363
|
-
const profileEntries = listProfileFiles();
|
|
3364
|
-
const available = profileEntries.map((entry) => entry.name);
|
|
3365
|
-
|
|
3366
|
-
if (!profile_name) {
|
|
3367
|
-
const current = AGENT_ID;
|
|
3368
|
-
const list = available.map(p => `${p === current ? "→ " : " "}${p}`).join("\n");
|
|
3369
|
-
return { content: [{ type: "text", text: `Current: ${current}\nAvailable profiles:\n${list}` }] };
|
|
3370
|
-
}
|
|
3371
|
-
|
|
3372
|
-
// Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
|
|
3373
|
-
// when set, or via current profile when Cursor stdio started with --profile
|
|
3374
|
-
// and no CURSOR_CONVERSATION_ID. Refuse switches that leave the locked
|
|
3375
|
-
// identity (including other Grok bots or Hermes/Spiral). No-op allowed.
|
|
3376
|
-
// Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
|
|
3377
|
-
// profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
|
|
3378
|
-
const switchBinds = loadGrokBinds();
|
|
3379
|
-
const bindApplies = currentGrokBindApplicability(switchBinds);
|
|
3380
|
-
const switchGate = !bindApplies.applies ? ({ kind: "allow" } as const) : gateSwitchProfile({
|
|
3381
|
-
conversationId: process.env.CURSOR_CONVERSATION_ID,
|
|
3382
|
-
binds: switchBinds,
|
|
3383
|
-
requestedProfileName: profile_name,
|
|
3384
|
-
currentProfileName: profileNameFromPath(activeProfileFile),
|
|
3385
|
-
});
|
|
3386
|
-
if (switchGate.kind === "locked") {
|
|
3387
|
-
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
3388
|
-
}
|
|
3389
|
-
|
|
3390
|
-
// Find and load the profile
|
|
3391
|
-
const targetFile = nameToPath(profile_name);
|
|
3392
|
-
if (!existsSync(targetFile)) {
|
|
3393
|
-
return { content: [{ type: "text", text: `Profile "${profile_name}" not found. Available: ${available.join(", ")}` }], isError: true };
|
|
3394
|
-
}
|
|
3395
|
-
|
|
3396
|
-
const newProfile = readIdentityProfile(targetFile);
|
|
3397
|
-
applyIdentityFromProfile(newProfile, targetFile);
|
|
3398
|
-
|
|
3399
|
-
const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID
|
|
3400
|
-
? `\n🚨 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) — write tools stay refused.`
|
|
3401
|
-
: "";
|
|
3402
|
-
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);
|
|
3403
3765
|
}
|
|
3404
3766
|
|
|
3405
3767
|
if (name === "list_channel_docs") {
|
|
@@ -4371,11 +4733,70 @@ function connectWS() {
|
|
|
4371
4733
|
process.stderr.write(`[agentchat] grok wake resolve failed: ${e}\n`);
|
|
4372
4734
|
}
|
|
4373
4735
|
})();
|
|
4374
|
-
} else {
|
|
4736
|
+
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
4375
4737
|
void fireWake(data, {
|
|
4376
4738
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
4377
4739
|
secret: process.env.AGENTCHAT_WAKE_SECRET,
|
|
4378
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
|
+
})();
|
|
4379
4800
|
}
|
|
4380
4801
|
if (activeHi) clearFinishedHiddenIdentityGamesFromMessage(data);
|
|
4381
4802
|
} else {
|
|
@@ -4458,7 +4879,17 @@ const heartbeat = new HeartbeatMonitor({
|
|
|
4458
4879
|
},
|
|
4459
4880
|
getReadyState: () => ws?.readyState ?? WS_CLOSED,
|
|
4460
4881
|
}, 15_000, 45_000, 30_000); // 15s ping, 45s pong timeout, 30s connect timeout
|
|
4461
|
-
|
|
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
|
+
}
|
|
4462
4893
|
|
|
4463
4894
|
function shutdownFromStdio(reason: string) {
|
|
4464
4895
|
if (shuttingDown) return;
|
|
@@ -4466,6 +4897,7 @@ function shutdownFromStdio(reason: string) {
|
|
|
4466
4897
|
safeStderrWrite(`[agentchat] Stdio closed (${reason}), shutting down\n`);
|
|
4467
4898
|
// Persisting the read cursor is a state change, not teardown: report, never swallow.
|
|
4468
4899
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}\n`); }
|
|
4900
|
+
releaseLiveLock();
|
|
4469
4901
|
try { heartbeat.stop(); } catch {}
|
|
4470
4902
|
try { stopAllTypingHeartbeats(); } catch {}
|
|
4471
4903
|
if (reconnectTimer) {
|
|
@@ -4502,8 +4934,12 @@ function installStdioLifecycleGuards() {
|
|
|
4502
4934
|
process.stderr.on("error", handleOutputError);
|
|
4503
4935
|
process.on("SIGPIPE", () => shutdownFromStdio("SIGPIPE"));
|
|
4504
4936
|
process.on("beforeExit", () => {
|
|
4937
|
+
releaseLiveLock();
|
|
4505
4938
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor fallback flush failed: ${e}\n`); }
|
|
4506
4939
|
});
|
|
4940
|
+
process.on("exit", () => {
|
|
4941
|
+
releaseLiveLock();
|
|
4942
|
+
});
|
|
4507
4943
|
}
|
|
4508
4944
|
|
|
4509
4945
|
// Startup staleness check: compare the running package version against the npm
|
|
@@ -4539,6 +4975,8 @@ async function main() {
|
|
|
4539
4975
|
// reconnect loop; stdio (initialize/tools/list) is served either way.
|
|
4540
4976
|
if (anonymousMode) {
|
|
4541
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`);
|
|
4542
4980
|
} else {
|
|
4543
4981
|
connectWS();
|
|
4544
4982
|
}
|