agentschat-mcp 0.36.13 → 0.36.16
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 +7 -7
- package/dist/codex-bridge.js +197 -62
- package/dist/connector.js +5 -5
- package/dist/server.js +1096 -203
- 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 +614 -129
- package/src/session-bind.ts +388 -0
- package/src/terms.ts +10 -65
- package/src/tool-annotations.ts +2 -0
- package/src/wake.ts +237 -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",
|
|
@@ -1523,12 +1589,13 @@ const ALL_TOOL_DEFS = [
|
|
|
1523
1589
|
},
|
|
1524
1590
|
{
|
|
1525
1591
|
name: "get_history",
|
|
1526
|
-
description: "Get recent message history from a channel.",
|
|
1592
|
+
description: "Get recent message history from a channel, or pass message_id to fetch a single message in full.",
|
|
1527
1593
|
inputSchema: {
|
|
1528
1594
|
type: "object" as const,
|
|
1529
1595
|
properties: {
|
|
1530
1596
|
chat_id: { type: "string", description: "The channel_id" },
|
|
1531
1597
|
limit: { type: "number", description: "Max messages (default 20, max 100)" },
|
|
1598
|
+
message_id: { type: "string", description: "Optional exact message_id to read a single message in full without truncation" },
|
|
1532
1599
|
},
|
|
1533
1600
|
required: ["chat_id"],
|
|
1534
1601
|
},
|
|
@@ -1747,11 +1814,38 @@ const ALL_TOOL_DEFS = [
|
|
|
1747
1814
|
},
|
|
1748
1815
|
{
|
|
1749
1816
|
name: "switch_profile",
|
|
1750
|
-
description: "Switch to a different AgentsChat profile at runtime. Lists available profiles if no name given.",
|
|
1817
|
+
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.",
|
|
1751
1818
|
inputSchema: {
|
|
1752
1819
|
type: "object" as const,
|
|
1753
1820
|
properties: {
|
|
1754
|
-
profile_name: { type: "string", description: "
|
|
1821
|
+
profile_name: { type: "string", description: "Existing profile name to switch to (omit to list available profiles)" },
|
|
1822
|
+
register_name: { type: "string", description: "Display name to register a brand-new AgentsChat agent and connect this window to it" },
|
|
1823
|
+
register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
|
|
1824
|
+
disconnect: { type: "boolean", description: "If true, disconnect this window from its current profile and release its lock" },
|
|
1825
|
+
conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" },
|
|
1826
|
+
},
|
|
1827
|
+
},
|
|
1828
|
+
},
|
|
1829
|
+
{
|
|
1830
|
+
name: "connect_profile",
|
|
1831
|
+
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.",
|
|
1832
|
+
inputSchema: {
|
|
1833
|
+
type: "object" as const,
|
|
1834
|
+
properties: {
|
|
1835
|
+
profile_name: { type: "string", description: "Existing profile name to connect to (omit to list available profiles and lock status)" },
|
|
1836
|
+
register_name: { type: "string", description: "Display name to register a new agent and connect this window to it" },
|
|
1837
|
+
register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
|
|
1838
|
+
conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" },
|
|
1839
|
+
},
|
|
1840
|
+
},
|
|
1841
|
+
},
|
|
1842
|
+
{
|
|
1843
|
+
name: "disconnect_profile",
|
|
1844
|
+
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.",
|
|
1845
|
+
inputSchema: {
|
|
1846
|
+
type: "object" as const,
|
|
1847
|
+
properties: {
|
|
1848
|
+
keep_binding: { type: "boolean", description: "If true, keep the session-binds.json entry while releasing the active process lock" },
|
|
1755
1849
|
},
|
|
1756
1850
|
},
|
|
1757
1851
|
},
|
|
@@ -2168,11 +2262,15 @@ function currentGrokBindApplicability(binds: Record<string, string>) {
|
|
|
2168
2262
|
|
|
2169
2263
|
/**
|
|
2170
2264
|
* Apply a profile file as the live identity and reconnect WS.
|
|
2171
|
-
* Shared by `switch_profile` and grok-bind heal.
|
|
2265
|
+
* Shared by `switch_profile`, `connect_profile`, and grok-bind heal.
|
|
2172
2266
|
*/
|
|
2173
|
-
function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
2267
|
+
function applyIdentityFromProfile(newProfile: any, targetFile: string, bindSessionId?: string | null): void {
|
|
2174
2268
|
validateIdentityProfile(newProfile, targetFile);
|
|
2269
|
+
if (AGENT_ID && AGENT_ID !== newProfile.agent_id) {
|
|
2270
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
2271
|
+
}
|
|
2175
2272
|
heartbeat.stop();
|
|
2273
|
+
stopAllTypingHeartbeats();
|
|
2176
2274
|
if (backfillTimer) { clearTimeout(backfillTimer); backfillTimer = null; }
|
|
2177
2275
|
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
2178
2276
|
if (ws) {
|
|
@@ -2187,6 +2285,34 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
|
2187
2285
|
profile = newProfile;
|
|
2188
2286
|
activeProfileFile = targetFile;
|
|
2189
2287
|
anonymousMode = false;
|
|
2288
|
+
|
|
2289
|
+
if (bindSessionId && bindSessionId.trim()) {
|
|
2290
|
+
runtimeSession = {
|
|
2291
|
+
sessionId: bindSessionId.trim(),
|
|
2292
|
+
runtime: runtimeSession?.runtime ?? "custom",
|
|
2293
|
+
...(runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}),
|
|
2294
|
+
};
|
|
2295
|
+
} else if (!runtimeSession?.sessionId) {
|
|
2296
|
+
const agyHost = discoverAntigravityHost();
|
|
2297
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
2298
|
+
runtimeSession = { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
if (!toolOnlyMode) {
|
|
2303
|
+
acquireAgentLock({
|
|
2304
|
+
lockDir,
|
|
2305
|
+
agentId: AGENT_ID,
|
|
2306
|
+
profileName: profileNameFromPath(targetFile),
|
|
2307
|
+
sessionId: runtimeSession?.sessionId ?? null,
|
|
2308
|
+
runtime: runtimeSession?.runtime ?? "mcp",
|
|
2309
|
+
});
|
|
2310
|
+
if (runtimeSession?.sessionId) {
|
|
2311
|
+
const pName = profileNameFromPath(targetFile);
|
|
2312
|
+
if (pName) saveSessionBind(configDir, runtimeSession.sessionId, pName);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2190
2316
|
// An explicit in-process switch is a TRUSTED identity change — advance the
|
|
2191
2317
|
// identity-guard record so the next boot doesn't alarm on it.
|
|
2192
2318
|
guardRecord = advanceGuardRecord(
|
|
@@ -2197,10 +2323,247 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string): void {
|
|
|
2197
2323
|
);
|
|
2198
2324
|
persistGuardRecord(guardRecord);
|
|
2199
2325
|
wsReconnectAttempt = 0;
|
|
2200
|
-
|
|
2201
|
-
|
|
2326
|
+
if (!toolOnlyMode) {
|
|
2327
|
+
heartbeat.start();
|
|
2328
|
+
connectWS();
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
function disconnectCurrentProfile(opts?: { keepBinding?: boolean }): { prevAgentId: string; prevProfileName: string } {
|
|
2333
|
+
const prevAgentId = AGENT_ID;
|
|
2334
|
+
const prevProfileName = profileNameFromPath(activeProfileFile) || profile?.display_name || AGENT_ID || "(none)";
|
|
2335
|
+
heartbeat.stop();
|
|
2336
|
+
stopAllTypingHeartbeats();
|
|
2337
|
+
if (backfillTimer) { clearTimeout(backfillTimer); backfillTimer = null; }
|
|
2338
|
+
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
2339
|
+
if (ws) {
|
|
2340
|
+
ws.onclose = null;
|
|
2341
|
+
try { ws.close(); } catch {}
|
|
2342
|
+
ws = null;
|
|
2343
|
+
}
|
|
2344
|
+
if (prevAgentId) {
|
|
2345
|
+
releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
2346
|
+
}
|
|
2347
|
+
if (!opts?.keepBinding && runtimeSession?.sessionId) {
|
|
2348
|
+
removeSessionBind(configDir, runtimeSession.sessionId);
|
|
2349
|
+
}
|
|
2350
|
+
sessionId = null;
|
|
2351
|
+
AGENT_ID = "";
|
|
2352
|
+
TOKEN = "";
|
|
2353
|
+
profile = {};
|
|
2354
|
+
activeProfileFile = null;
|
|
2355
|
+
anonymousMode = true;
|
|
2356
|
+
return { prevAgentId, prevProfileName };
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
function formatProfileList(): string {
|
|
2360
|
+
const profileEntries = listProfileFiles();
|
|
2361
|
+
const current = AGENT_ID;
|
|
2362
|
+
const currentProfileName = profileNameFromPath(activeProfileFile);
|
|
2363
|
+
const lines = profileEntries.map((entry) => {
|
|
2364
|
+
let entryAgentId = "";
|
|
2365
|
+
try {
|
|
2366
|
+
const parsed = JSON.parse(readFileSync(entry.path, "utf-8"));
|
|
2367
|
+
if (typeof parsed?.agent_id === "string") entryAgentId = parsed.agent_id;
|
|
2368
|
+
} catch {}
|
|
2369
|
+
const isCurrent = (current && (entry.name === current || entryAgentId === current)) || (currentProfileName && entry.name === currentProfileName);
|
|
2370
|
+
const lock = entryAgentId
|
|
2371
|
+
? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid })
|
|
2372
|
+
: { locked: false };
|
|
2373
|
+
const statusSuffix = lock.locked
|
|
2374
|
+
? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}]`
|
|
2375
|
+
: "";
|
|
2376
|
+
return `${isCurrent ? "→ " : " "}${entry.name}${statusSuffix}`;
|
|
2377
|
+
});
|
|
2378
|
+
return `Current: ${current || "(anonymous / disconnected)"}\nAvailable profiles:\n${lines.join("\n")}`;
|
|
2202
2379
|
}
|
|
2203
2380
|
|
|
2381
|
+
async function registerAndConnectProfile(
|
|
2382
|
+
displayName: string,
|
|
2383
|
+
bindSessionId?: string | null,
|
|
2384
|
+
): Promise<{ content: any[]; isError?: boolean }> {
|
|
2385
|
+
const cleanName = displayName.trim();
|
|
2386
|
+
if (!cleanName) {
|
|
2387
|
+
return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
|
|
2388
|
+
}
|
|
2389
|
+
const caps = ["claude-code", "coding", "chat"];
|
|
2390
|
+
try {
|
|
2391
|
+
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
2392
|
+
method: "POST",
|
|
2393
|
+
headers: { "Content-Type": "application/json" },
|
|
2394
|
+
body: JSON.stringify({
|
|
2395
|
+
name: cleanName,
|
|
2396
|
+
type: "agent",
|
|
2397
|
+
capabilities: caps,
|
|
2398
|
+
source: "mcp",
|
|
2399
|
+
terms_notice_version: TERMS_VERSION,
|
|
2400
|
+
}),
|
|
2401
|
+
});
|
|
2402
|
+
if (!regRes.ok) {
|
|
2403
|
+
const body = await regRes.text().catch(() => "");
|
|
2404
|
+
return {
|
|
2405
|
+
content: [{ type: "text", text: `Registration refused by ${REST_URL} — HTTP ${regRes.status} ${body.slice(0, 240)}` }],
|
|
2406
|
+
isError: true,
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2409
|
+
const data = (await regRes.json()) as any;
|
|
2410
|
+
const newProfile = {
|
|
2411
|
+
agent_id: data.id,
|
|
2412
|
+
display_name: cleanName,
|
|
2413
|
+
token: data.key,
|
|
2414
|
+
capabilities: caps,
|
|
2415
|
+
};
|
|
2416
|
+
const targetFile = nameToPath(cleanName);
|
|
2417
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
2418
|
+
mkdirSync(dirname(targetFile), { recursive: true });
|
|
2419
|
+
safeWriteProfile(targetFile, newProfile);
|
|
2420
|
+
const defaultProfileFile = nameToPath("profile");
|
|
2421
|
+
if (!existsSync(defaultProfileFile)) {
|
|
2422
|
+
safeWriteProfile(defaultProfileFile, newProfile);
|
|
2423
|
+
}
|
|
2424
|
+
applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
|
|
2425
|
+
const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
|
|
2426
|
+
return {
|
|
2427
|
+
content: [{
|
|
2428
|
+
type: "text",
|
|
2429
|
+
text:
|
|
2430
|
+
`Registered and connected profile "${cleanName}" (${AGENT_ID}).\n` +
|
|
2431
|
+
`Profile saved: ${targetFile}\n` +
|
|
2432
|
+
`Claim entry: ${claimEntry} — enter the key from your private profile in the browser.\n` +
|
|
2433
|
+
`${TERMS_NOTICE_TEXT}`,
|
|
2434
|
+
}],
|
|
2435
|
+
};
|
|
2436
|
+
} catch (e: any) {
|
|
2437
|
+
return {
|
|
2438
|
+
content: [{ type: "text", text: `Registration failed: ${String(e?.message || e).slice(0, 200)}` }],
|
|
2439
|
+
isError: true,
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
|
|
2444
|
+
async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]; isError?: boolean }> {
|
|
2445
|
+
const {
|
|
2446
|
+
profile_name,
|
|
2447
|
+
register_name,
|
|
2448
|
+
register,
|
|
2449
|
+
disconnect,
|
|
2450
|
+
conversation_id,
|
|
2451
|
+
} = (args || {}) as {
|
|
2452
|
+
profile_name?: string;
|
|
2453
|
+
register_name?: string;
|
|
2454
|
+
register?: boolean;
|
|
2455
|
+
disconnect?: boolean;
|
|
2456
|
+
conversation_id?: string;
|
|
2457
|
+
};
|
|
2458
|
+
|
|
2459
|
+
if (disconnect) {
|
|
2460
|
+
const { prevAgentId, prevProfileName } = disconnectCurrentProfile();
|
|
2461
|
+
return {
|
|
2462
|
+
content: [{
|
|
2463
|
+
type: "text",
|
|
2464
|
+
text: prevAgentId
|
|
2465
|
+
? `Disconnected from profile "${prevProfileName}" (${prevAgentId}). Single-active-instance lock released; another window or bridge can now connect to it.`
|
|
2466
|
+
: `Already disconnected (anonymous mode).`,
|
|
2467
|
+
}],
|
|
2468
|
+
};
|
|
2469
|
+
}
|
|
2470
|
+
|
|
2471
|
+
const explicitSessionId = typeof conversation_id === "string" && conversation_id.trim() ? conversation_id.trim() : null;
|
|
2472
|
+
if (typeof register_name === "string" && register_name.trim()) {
|
|
2473
|
+
return await registerAndConnectProfile(register_name.trim(), explicitSessionId);
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
if (!profile_name) {
|
|
2477
|
+
return { content: [{ type: "text", text: formatProfileList() }] };
|
|
2478
|
+
}
|
|
2479
|
+
|
|
2480
|
+
// Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
|
|
2481
|
+
// when set, or via current profile when Cursor stdio started with --profile
|
|
2482
|
+
// and no CURSOR_CONVERSATION_ID. Refuse switches that leave the locked
|
|
2483
|
+
// identity (including other Grok bots or Hermes/Spiral). No-op allowed.
|
|
2484
|
+
// Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
|
|
2485
|
+
// profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
|
|
2486
|
+
const switchBinds = loadGrokBinds();
|
|
2487
|
+
const bindApplies = currentGrokBindApplicability(switchBinds);
|
|
2488
|
+
const switchGate = !bindApplies.applies ? ({ kind: "allow" } as const) : gateSwitchProfile({
|
|
2489
|
+
conversationId: process.env.CURSOR_CONVERSATION_ID,
|
|
2490
|
+
binds: switchBinds,
|
|
2491
|
+
requestedProfileName: profile_name,
|
|
2492
|
+
currentProfileName: profileNameFromPath(activeProfileFile),
|
|
2493
|
+
});
|
|
2494
|
+
if (switchGate.kind === "locked") {
|
|
2495
|
+
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
const targetFile = nameToPath(profile_name);
|
|
2499
|
+
if (!existsSync(targetFile)) {
|
|
2500
|
+
if (register) {
|
|
2501
|
+
return await registerAndConnectProfile(profile_name, explicitSessionId);
|
|
2502
|
+
}
|
|
2503
|
+
const available = listProfileFiles().map((entry) => entry.name);
|
|
2504
|
+
return {
|
|
2505
|
+
content: [{
|
|
2506
|
+
type: "text",
|
|
2507
|
+
text: `Profile "${profile_name}" not found. Available: ${available.join(", ")} (or pass register_name="${profile_name}" / register=true to create a new agent)`,
|
|
2508
|
+
}],
|
|
2509
|
+
isError: true,
|
|
2510
|
+
};
|
|
2511
|
+
}
|
|
2512
|
+
|
|
2513
|
+
const newProfile = readIdentityProfile(targetFile);
|
|
2514
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
2515
|
+
|
|
2516
|
+
const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
|
|
2517
|
+
const lockCheck = checkAgentLock({
|
|
2518
|
+
lockDir,
|
|
2519
|
+
agentId: newProfile.agent_id,
|
|
2520
|
+
currentSessionId: effectiveSessionId,
|
|
2521
|
+
lockOwnerPid,
|
|
2522
|
+
});
|
|
2523
|
+
if (lockCheck.locked) {
|
|
2524
|
+
return {
|
|
2525
|
+
content: [{
|
|
2526
|
+
type: "text",
|
|
2527
|
+
text:
|
|
2528
|
+
`Profile "${profile_name}" (${newProfile.agent_id}) is currently in use by another active process ` +
|
|
2529
|
+
`(pid=${lockCheck.holder?.pid}${lockCheck.holder?.runtime ? `, ${lockCheck.holder.runtime}` : ""}` +
|
|
2530
|
+
`${lockCheck.holder?.sessionId ? `, session=${lockCheck.holder.sessionId}` : ""}). ` +
|
|
2531
|
+
`Call disconnect_profile in that window first, or connect/register a different profile.`,
|
|
2532
|
+
}],
|
|
2533
|
+
isError: true,
|
|
2534
|
+
};
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
applyIdentityFromProfile(newProfile, targetFile, explicitSessionId);
|
|
2538
|
+
|
|
2539
|
+
const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID
|
|
2540
|
+
? `\n🚨 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) — write tools stay refused.`
|
|
2541
|
+
: "";
|
|
2542
|
+
const bindNote = runtimeSession?.sessionId
|
|
2543
|
+
? ` Session "${runtimeSession.sessionId}" is bound to "${profile_name}" in session-binds.json.`
|
|
2544
|
+
: "";
|
|
2545
|
+
return {
|
|
2546
|
+
content: [{
|
|
2547
|
+
type: "text",
|
|
2548
|
+
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}`,
|
|
2549
|
+
}],
|
|
2550
|
+
};
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
HANDLERS.set("connect_profile", async (args) => handleProfileSwitchOrConnect(args));
|
|
2554
|
+
HANDLERS.set("disconnect_profile", async (args) => {
|
|
2555
|
+
const { keep_binding } = (args || {}) as { keep_binding?: boolean };
|
|
2556
|
+
const { prevAgentId, prevProfileName } = disconnectCurrentProfile({ keepBinding: keep_binding });
|
|
2557
|
+
return {
|
|
2558
|
+
content: [{
|
|
2559
|
+
type: "text",
|
|
2560
|
+
text: prevAgentId
|
|
2561
|
+
? `Disconnected from profile "${prevProfileName}" (${prevAgentId}). Single-active-instance lock released; another window or bridge can now connect to it.`
|
|
2562
|
+
: `Already disconnected (anonymous mode).`,
|
|
2563
|
+
}],
|
|
2564
|
+
};
|
|
2565
|
+
});
|
|
2566
|
+
|
|
2204
2567
|
/**
|
|
2205
2568
|
* If CURSOR_CONVERSATION_ID is bound and live identity drifted (e.g. another
|
|
2206
2569
|
* agent called switch_profile on this shared MCP), force-reload the bound
|
|
@@ -2245,6 +2608,44 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
2245
2608
|
// SDK error, so the calling agent always learns the call failed. Explicit
|
|
2246
2609
|
// error returns below carry isError:true individually.
|
|
2247
2610
|
try {
|
|
2611
|
+
// Capture session metadata injected by hosts on tools/call (e.g. ZCode's
|
|
2612
|
+
// _meta.session_id and _meta.workspace_path). If we booted before knowing
|
|
2613
|
+
// the session ID, bind or auto-connect the session's bound profile now.
|
|
2614
|
+
const metaSession = detectRuntimeSession(process.env, (request.params as any)?._meta);
|
|
2615
|
+
if (metaSession && (!runtimeSession || runtimeSession.sessionId !== metaSession.sessionId || (!runtimeSession.workspacePath && metaSession.workspacePath))) {
|
|
2616
|
+
runtimeSession = metaSession;
|
|
2617
|
+
if (anonymousMode && name !== "connect_profile" && name !== "switch_profile" && name !== "disconnect_profile") {
|
|
2618
|
+
const boundProfile = loadSessionBinds(configDir)[metaSession.sessionId];
|
|
2619
|
+
if (boundProfile) {
|
|
2620
|
+
const boundPath = nameToPath(boundProfile);
|
|
2621
|
+
if (existsSync(boundPath)) {
|
|
2622
|
+
try {
|
|
2623
|
+
const candidate = readIdentityProfile(boundPath);
|
|
2624
|
+
const lock = checkAgentLock({
|
|
2625
|
+
lockDir,
|
|
2626
|
+
agentId: candidate?.agent_id,
|
|
2627
|
+
currentSessionId: metaSession.sessionId,
|
|
2628
|
+
lockOwnerPid,
|
|
2629
|
+
});
|
|
2630
|
+
if (!lock.locked) {
|
|
2631
|
+
applyIdentityFromProfile(candidate, boundPath, metaSession.sessionId);
|
|
2632
|
+
}
|
|
2633
|
+
} catch {}
|
|
2634
|
+
}
|
|
2635
|
+
}
|
|
2636
|
+
} else if (!anonymousMode && AGENT_ID && activeProfileFile && !toolOnlyMode) {
|
|
2637
|
+
acquireAgentLock({
|
|
2638
|
+
lockDir,
|
|
2639
|
+
agentId: AGENT_ID,
|
|
2640
|
+
profileName: profileNameFromPath(activeProfileFile),
|
|
2641
|
+
sessionId: metaSession.sessionId,
|
|
2642
|
+
runtime: metaSession.runtime,
|
|
2643
|
+
});
|
|
2644
|
+
const pName = profileNameFromPath(activeProfileFile);
|
|
2645
|
+
if (pName) saveSessionBind(configDir, metaSession.sessionId, pName);
|
|
2646
|
+
}
|
|
2647
|
+
}
|
|
2648
|
+
|
|
2248
2649
|
// Validate args against the tool's declared inputSchema (required present +
|
|
2249
2650
|
// declared types) before any side effect. Permissive: unknown tools and
|
|
2250
2651
|
// undeclared fields pass through; only contract violations are rejected.
|
|
@@ -3152,6 +3553,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3152
3553
|
}));
|
|
3153
3554
|
return { content: [{ type: "text", text: `Read cursor update dispatched (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3154
3555
|
}
|
|
3556
|
+
if (toolOnlyMode) {
|
|
3557
|
+
return { content: [{ type: "text", text: `Read cursor noted (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3558
|
+
}
|
|
3155
3559
|
return { content: [{ type: "text", text: "Not connected" }] };
|
|
3156
3560
|
}
|
|
3157
3561
|
|
|
@@ -3318,37 +3722,83 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3318
3722
|
}
|
|
3319
3723
|
|
|
3320
3724
|
if (name === "get_history") {
|
|
3321
|
-
const { chat_id, limit = 20 } = args as any;
|
|
3725
|
+
const { chat_id, limit = 20, message_id } = args as any;
|
|
3726
|
+
const targetMsgId = typeof message_id === "string" && message_id.trim() ? message_id.trim() : null;
|
|
3727
|
+
const MAX_HISTORY_MESSAGE_CHARS = 4000;
|
|
3728
|
+
const formatHistoryMessage = (m: any, full = false): string => {
|
|
3729
|
+
const time = m.timestamp ? new Date(m.timestamp).toLocaleString() : "?";
|
|
3730
|
+
const rawContent = String(m.content ?? "");
|
|
3731
|
+
const body =
|
|
3732
|
+
full || rawContent.length <= MAX_HISTORY_MESSAGE_CHARS
|
|
3733
|
+
? rawContent
|
|
3734
|
+
: `${rawContent.slice(0, MAX_HISTORY_MESSAGE_CHARS)}… [truncated ${rawContent.length - MAX_HISTORY_MESSAGE_CHARS} chars; pass message_id="${m.id || ""}" to get_history for full text]`;
|
|
3735
|
+
let line = `[${time}] ${m.sender_id?.slice(0, 12)}: ${body}`;
|
|
3736
|
+
// Surface media attachments so an agent can perceive voice/image messages,
|
|
3737
|
+
// not just their text caption. Audio: show any server transcript inline
|
|
3738
|
+
// (agent reads it directly); otherwise point at transcribe(url).
|
|
3739
|
+
const atts = Array.isArray(m.attachments) ? m.attachments : [];
|
|
3740
|
+
for (const a of atts) {
|
|
3741
|
+
if (!a?.url) continue;
|
|
3742
|
+
if (a.type === "audio") {
|
|
3743
|
+
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
3744
|
+
line += `\n 🔊 audio${dur}: ${a.url}`;
|
|
3745
|
+
line += a.transcript
|
|
3746
|
+
? `\n transcript: "${String(a.transcript).slice(0, 400)}"`
|
|
3747
|
+
: `\n (no transcript — call transcribe(url) to read what was said)`;
|
|
3748
|
+
} else if (a.type === "image") {
|
|
3749
|
+
const dim = a.width && a.height ? ` ${a.width}×${a.height}` : "";
|
|
3750
|
+
line += `\n 🖼 image${dim}: ${a.url}`;
|
|
3751
|
+
} else {
|
|
3752
|
+
line += `\n 📎 ${a.type || "file"}: ${a.url}`;
|
|
3753
|
+
}
|
|
3754
|
+
}
|
|
3755
|
+
return line;
|
|
3756
|
+
};
|
|
3322
3757
|
try {
|
|
3323
|
-
const
|
|
3758
|
+
const fetchLimit = targetMsgId ? 100 : Math.max(1, Math.min(Number(limit) || 20, 100));
|
|
3759
|
+
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages?limit=${fetchLimit}`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
|
|
3324
3760
|
if (r.ok) {
|
|
3325
3761
|
const data = await r.json() as any;
|
|
3326
3762
|
const msgs = (data.messages || []).filter((m: any) => m.content !== "__typing__");
|
|
3327
|
-
if (
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3763
|
+
if (targetMsgId) {
|
|
3764
|
+
let exact = msgs.find((m: any) => m.id === targetMsgId);
|
|
3765
|
+
if (!exact) {
|
|
3766
|
+
try {
|
|
3767
|
+
const mcpRes = await apiFetch(`${REST_URL}/mcp`, {
|
|
3768
|
+
method: "POST",
|
|
3769
|
+
headers: {
|
|
3770
|
+
"Authorization": `Bearer ${TOKEN}`,
|
|
3771
|
+
"Content-Type": "application/json",
|
|
3772
|
+
...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
|
|
3773
|
+
},
|
|
3774
|
+
body: JSON.stringify({
|
|
3775
|
+
jsonrpc: "2.0",
|
|
3776
|
+
id: 1,
|
|
3777
|
+
method: "tools/call",
|
|
3778
|
+
params: {
|
|
3779
|
+
name: "agentschat_read_messages",
|
|
3780
|
+
arguments: { channel_id: chat_id, message_id: targetMsgId },
|
|
3781
|
+
},
|
|
3782
|
+
}),
|
|
3783
|
+
});
|
|
3784
|
+
if (mcpRes.ok) {
|
|
3785
|
+
const rpcData = await mcpRes.json() as any;
|
|
3786
|
+
const structured = rpcData?.result?.structuredContent;
|
|
3787
|
+
const textPayload = rpcData?.result?.content?.[0]?.text;
|
|
3788
|
+
const parsed = structured || (typeof textPayload === "string" ? JSON.parse(textPayload) : null);
|
|
3789
|
+
if (Array.isArray(parsed?.messages) && parsed.messages.length > 0) {
|
|
3790
|
+
exact = parsed.messages[0];
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
} catch {}
|
|
3794
|
+
}
|
|
3795
|
+
if (!exact) {
|
|
3796
|
+
return { content: [{ type: "text", text: `Message ${targetMsgId} not found in channel ${chat_id}.` }], isError: true };
|
|
3349
3797
|
}
|
|
3350
|
-
return
|
|
3351
|
-
}
|
|
3798
|
+
return { content: [{ type: "text", text: `1 message (id=${exact.id}):\n${formatHistoryMessage(exact, true)}` }] };
|
|
3799
|
+
}
|
|
3800
|
+
if (msgs.length === 0) return { content: [{ type: "text", text: "No messages in this channel." }] };
|
|
3801
|
+
const list = msgs.map((m: any) => formatHistoryMessage(m, false)).join("\n");
|
|
3352
3802
|
return { content: [{ type: "text", text: `${msgs.length} messages:\n${list}` }] };
|
|
3353
3803
|
}
|
|
3354
3804
|
return { content: [{ type: "text", text: `Failed to get history (${r.status})` }] };
|
|
@@ -3358,48 +3808,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3358
3808
|
}
|
|
3359
3809
|
|
|
3360
3810
|
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}` }] };
|
|
3811
|
+
return await handleProfileSwitchOrConnect(args);
|
|
3403
3812
|
}
|
|
3404
3813
|
|
|
3405
3814
|
if (name === "list_channel_docs") {
|
|
@@ -4371,11 +4780,70 @@ function connectWS() {
|
|
|
4371
4780
|
process.stderr.write(`[agentchat] grok wake resolve failed: ${e}\n`);
|
|
4372
4781
|
}
|
|
4373
4782
|
})();
|
|
4374
|
-
} else {
|
|
4783
|
+
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
4375
4784
|
void fireWake(data, {
|
|
4376
4785
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
4377
4786
|
secret: process.env.AGENTCHAT_WAKE_SECRET,
|
|
4378
4787
|
});
|
|
4788
|
+
} else if (runtimeSession?.runtime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode") {
|
|
4789
|
+
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
4790
|
+
const zcodeSid =
|
|
4791
|
+
runtimeSession?.sessionId ||
|
|
4792
|
+
findBoundSessionForProfile(configDir, activeProfName, (sid) => sid.startsWith("sess_")) ||
|
|
4793
|
+
"";
|
|
4794
|
+
if (zcodeSid) {
|
|
4795
|
+
void fireZcodeWake(data, {
|
|
4796
|
+
sessionId: zcodeSid,
|
|
4797
|
+
workspacePath: runtimeSession?.workspacePath,
|
|
4798
|
+
profileName: activeProfName ?? undefined,
|
|
4799
|
+
lockOwnerPid: process.pid,
|
|
4800
|
+
logger: (m) => process.stderr.write(`${m}\n`),
|
|
4801
|
+
});
|
|
4802
|
+
}
|
|
4803
|
+
} else {
|
|
4804
|
+
// Native Antigravity (agy) Connect-RPC wake when running under language_server
|
|
4805
|
+
void (async () => {
|
|
4806
|
+
try {
|
|
4807
|
+
const agyHost = discoverAntigravityHost();
|
|
4808
|
+
const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
|
|
4809
|
+
const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
|
|
4810
|
+
if (!agyHost && !lsAddress) return;
|
|
4811
|
+
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
4812
|
+
const allBinds = loadSessionBinds(configDir);
|
|
4813
|
+
let targetCid =
|
|
4814
|
+
(runtimeSession?.runtime === "antigravity" ? runtimeSession.sessionId : "") ||
|
|
4815
|
+
findBoundSessionForProfile(
|
|
4816
|
+
configDir,
|
|
4817
|
+
activeProfName,
|
|
4818
|
+
(sid) =>
|
|
4819
|
+
/^[0-9a-f-]{36}$/i.test(sid) &&
|
|
4820
|
+
(!agyHost || agyHost.openConversations.length === 0 || agyHost.openConversations.includes(sid)),
|
|
4821
|
+
) ||
|
|
4822
|
+
findBoundSessionForProfile(configDir, activeProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) ||
|
|
4823
|
+
"";
|
|
4824
|
+
if (!targetCid && agyHost) {
|
|
4825
|
+
if (agyHost.openConversations.length === 1) {
|
|
4826
|
+
targetCid = agyHost.openConversations[0]!;
|
|
4827
|
+
} else if (agyHost.openConversations.length > 1) {
|
|
4828
|
+
const unboundOrSame = agyHost.openConversations.find(
|
|
4829
|
+
(cid) => !allBinds[cid] || allBinds[cid] === activeProfName,
|
|
4830
|
+
);
|
|
4831
|
+
targetCid = unboundOrSame || agyHost.openConversations[0]!;
|
|
4832
|
+
}
|
|
4833
|
+
}
|
|
4834
|
+
if (targetCid && csrfToken) {
|
|
4835
|
+
await fireAntigravityWake(data, {
|
|
4836
|
+
conversationId: targetCid,
|
|
4837
|
+
csrfToken,
|
|
4838
|
+
lsAddress: lsAddress || undefined,
|
|
4839
|
+
ports: agyHost?.ports,
|
|
4840
|
+
logger: (m) => process.stderr.write(`${m}\n`),
|
|
4841
|
+
});
|
|
4842
|
+
}
|
|
4843
|
+
} catch (e) {
|
|
4844
|
+
process.stderr.write(`[agentchat] antigravity wake error: ${e}\n`);
|
|
4845
|
+
}
|
|
4846
|
+
})();
|
|
4379
4847
|
}
|
|
4380
4848
|
if (activeHi) clearFinishedHiddenIdentityGamesFromMessage(data);
|
|
4381
4849
|
} else {
|
|
@@ -4458,7 +4926,17 @@ const heartbeat = new HeartbeatMonitor({
|
|
|
4458
4926
|
},
|
|
4459
4927
|
getReadyState: () => ws?.readyState ?? WS_CLOSED,
|
|
4460
4928
|
}, 15_000, 45_000, 30_000); // 15s ping, 45s pong timeout, 30s connect timeout
|
|
4461
|
-
|
|
4929
|
+
if (!anonymousMode && !toolOnlyMode) {
|
|
4930
|
+
heartbeat.start();
|
|
4931
|
+
}
|
|
4932
|
+
|
|
4933
|
+
function releaseLiveLock() {
|
|
4934
|
+
if (AGENT_ID && !toolOnlyMode) {
|
|
4935
|
+
try {
|
|
4936
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
4937
|
+
} catch {}
|
|
4938
|
+
}
|
|
4939
|
+
}
|
|
4462
4940
|
|
|
4463
4941
|
function shutdownFromStdio(reason: string) {
|
|
4464
4942
|
if (shuttingDown) return;
|
|
@@ -4466,6 +4944,7 @@ function shutdownFromStdio(reason: string) {
|
|
|
4466
4944
|
safeStderrWrite(`[agentchat] Stdio closed (${reason}), shutting down\n`);
|
|
4467
4945
|
// Persisting the read cursor is a state change, not teardown: report, never swallow.
|
|
4468
4946
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}\n`); }
|
|
4947
|
+
releaseLiveLock();
|
|
4469
4948
|
try { heartbeat.stop(); } catch {}
|
|
4470
4949
|
try { stopAllTypingHeartbeats(); } catch {}
|
|
4471
4950
|
if (reconnectTimer) {
|
|
@@ -4502,8 +4981,12 @@ function installStdioLifecycleGuards() {
|
|
|
4502
4981
|
process.stderr.on("error", handleOutputError);
|
|
4503
4982
|
process.on("SIGPIPE", () => shutdownFromStdio("SIGPIPE"));
|
|
4504
4983
|
process.on("beforeExit", () => {
|
|
4984
|
+
releaseLiveLock();
|
|
4505
4985
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor fallback flush failed: ${e}\n`); }
|
|
4506
4986
|
});
|
|
4987
|
+
process.on("exit", () => {
|
|
4988
|
+
releaseLiveLock();
|
|
4989
|
+
});
|
|
4507
4990
|
}
|
|
4508
4991
|
|
|
4509
4992
|
// Startup staleness check: compare the running package version against the npm
|
|
@@ -4539,6 +5022,8 @@ async function main() {
|
|
|
4539
5022
|
// reconnect loop; stdio (initialize/tools/list) is served either way.
|
|
4540
5023
|
if (anonymousMode) {
|
|
4541
5024
|
process.stderr.write(`[agentchat] Anonymous — not connecting to the hub.\n`);
|
|
5025
|
+
} else if (toolOnlyMode) {
|
|
5026
|
+
process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) — skipping duplicate WS connection.\n`);
|
|
4542
5027
|
} else {
|
|
4543
5028
|
connectWS();
|
|
4544
5029
|
}
|