agentschat-mcp 0.36.23 → 0.36.24

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/src/server.ts CHANGED
@@ -123,17 +123,33 @@ import {
123
123
  } from "./identity-guard.ts";
124
124
  // Read-cursor persistence: a state change that merely *lives* in the teardown path.
125
125
  import { flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
126
+ import { CURSOR_INIT_KEY, joinChannelRest, parseMaxIdleMs, sendRestMessage, wakeOnce } from "./rest-cli.ts";
126
127
  import { randomUUID } from "crypto";
127
128
 
128
129
  function parseArgs() {
129
130
  const args = process.argv.slice(2);
130
131
  const parsed: Record<string, string> = {};
131
- const values = new Set(["name", "id", "url", "token", "caps", "profile"]);
132
+ const values = new Set([
133
+ "name",
134
+ "id",
135
+ "url",
136
+ "token",
137
+ "caps",
138
+ "profile",
139
+ "join",
140
+ "send",
141
+ "text",
142
+ "reply-to",
143
+ "channel",
144
+ "timeout",
145
+ "max-idle",
146
+ ]);
132
147
  for (let i = 0; i < args.length; i++) {
133
148
  const arg = args[i];
134
149
  if (arg === "--help" || arg === "-h") continue;
135
150
  if (arg === "--register") { parsed.register = "1"; continue; }
136
151
  if (arg === "--register-only") { parsed.registerOnly = "1"; continue; }
152
+ if (arg === "--wake-once") { parsed.wakeOnce = "1"; continue; }
137
153
  if (arg === "--accept-terms") continue; // Legacy compatibility; no consent is recorded.
138
154
  const equal = arg.indexOf("=");
139
155
  const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
@@ -142,7 +158,7 @@ function parseArgs() {
142
158
  process.exit(1);
143
159
  }
144
160
  const value = equal < 0 ? args[++i] : arg.slice(equal + 1);
145
- if (!value?.trim() || value.startsWith("-")) {
161
+ if (!value?.trim() || (key !== "text" && value.startsWith("-"))) {
146
162
  process.stderr.write(`[agentchat] ERROR: missing value for --${key}. See --help.\n`);
147
163
  process.exit(1);
148
164
  }
@@ -152,6 +168,7 @@ function parseArgs() {
152
168
  }
153
169
 
154
170
  const cliArgs = parseArgs();
171
+ const isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
155
172
 
156
173
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
157
174
  const localOnboardingPath = join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
@@ -176,6 +193,14 @@ Options:
176
193
  --profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
177
194
  --register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
178
195
  --register Explicitly opt in to registering a new agent (implied by --name)
196
+ --join <channel> Join a public channel via REST (e.g. --join welcome) and exit (or combine with --send / --wake-once).
197
+ --send <channel> Send a message to <channel> via REST (--text <msg> [--reply-to <msg_id>]), advance read cursor, and exit.
198
+ --text <msg> Message content for --send.
199
+ --reply-to <id> Optional target message ID for --send.
200
+ --wake-once Wait via HTTPS SSE + REST cursor for the next @mention or DM, print wake JSON + prompt, advance per-channel cursor, and exit 0.
201
+ --channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
202
+ --timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
203
+ --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
179
204
  --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
180
205
  No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
181
206
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
@@ -222,6 +247,25 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
222
247
 
223
248
  // Explicit CLI selection > project binding > runtime binding > environment > default.
224
249
  // Onboarding resolves ambiguous unbound candidates with the user; never scan-and-pick.
250
+ // A dedicated Codex bridge is the identity authority for all inherited MCP entries.
251
+ // No credentials in this envelope; read the existing private profile.
252
+ const codexIdentity = process.env.AGENTSCHAT_CODEX_IDENTITY
253
+ ? JSON.parse(process.env.AGENTSCHAT_CODEX_IDENTITY) as { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }
254
+ : undefined;
255
+ if (codexIdentity) {
256
+ if (process.env.AGENTSCHAT_TOOL_ONLY !== "1" ||
257
+ [codexIdentity.profileFile, codexIdentity.agentId, codexIdentity.apiUrl, codexIdentity.wsUrl].some(v => typeof v !== "string" || !v.trim())) {
258
+ throw new Error("Invalid Codex tool identity");
259
+ }
260
+ // Override inherited CLI/project/env selectors; they may belong to another bot.
261
+ cliArgs.profile = codexIdentity.profileFile;
262
+ cliArgs.id = codexIdentity.agentId;
263
+ cliArgs.url = codexIdentity.apiUrl;
264
+ delete cliArgs.token;
265
+ delete cliArgs.name;
266
+ delete process.env.AGENTCHAT_TOKEN;
267
+ process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
268
+ }
225
269
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
226
270
  const configDir = join(homeDir, ".agentschat");
227
271
  const legacyConfigDir = join(homeDir, ".agentchat");
@@ -229,7 +273,15 @@ const profileDirs = [configDir, legacyConfigDir];
229
273
  const lockDir = resolveLockDir(homeDir, process.env);
230
274
  const lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
231
275
  const toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
232
- let runtimeSession: DetectedSession | null = detectRuntimeSession(process.env);
276
+ let runtimeSessionComputed = false;
277
+ let runtimeSession: DetectedSession | null = null;
278
+ function ensureRuntimeSession(): DetectedSession | null {
279
+ if (!runtimeSessionComputed) {
280
+ runtimeSessionComputed = true;
281
+ runtimeSession = detectRuntimeSession(process.env);
282
+ }
283
+ return runtimeSession;
284
+ }
233
285
  /** One-shot notice when DSH is detected but no session can be resolved (see the DSH branch). */
234
286
  let dshRouteWarned = false;
235
287
 
@@ -331,13 +383,14 @@ function resolveProfile(): { path: string; source: ProfileSource; declaredName?:
331
383
 
332
384
  // Unified session-bind (`~/.agentschat/session-binds.json` / `agy-binds.json`):
333
385
  // maps CLAUDE_CODE_SESSION_ID / ANTIGRAVITY_CONVERSATION_ID / ZCODE_SESSION_ID to a profile.
334
- if (!grokToken && runtimeSession?.sessionId) {
386
+ const bootSession = !grokToken ? ensureRuntimeSession() : null;
387
+ if (!grokToken && bootSession?.sessionId) {
335
388
  const sessionBinds = loadSessionBinds(configDir);
336
- const boundProfile = sessionBinds[runtimeSession.sessionId];
389
+ const boundProfile = sessionBinds[bootSession.sessionId];
337
390
  if (boundProfile) {
338
391
  const boundPath = nameToPath(boundProfile);
339
392
  if (existsSync(boundPath)) {
340
- process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} → profile "${boundProfile}"\n`);
393
+ process.stderr.write(`[agentchat] session-bind (${bootSession.runtime}): ${bootSession.sessionId} → profile "${boundProfile}"\n`);
341
394
  return { path: boundPath, source: "session-bind", declaredName: boundProfile };
342
395
  }
343
396
  }
@@ -454,6 +507,9 @@ if (identity.mode === "profile") {
454
507
  } else {
455
508
  try {
456
509
  profile = readIdentityProfile(profileFile);
510
+ if (codexIdentity && profile.agent_id !== codexIdentity.agentId) {
511
+ throw new Error("Codex tool profile identity mismatch");
512
+ }
457
513
  if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
458
514
  throw new Error("Project agent_id does not match selected profile");
459
515
  }
@@ -468,7 +524,8 @@ if (identity.mode === "profile") {
468
524
  process.exit(1);
469
525
  }
470
526
  const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
471
- const lockCheck = (!cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
527
+ if (!isOneShotCli && !toolOnlyMode) ensureRuntimeSession();
528
+ const lockCheck = (!isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
472
529
  ? checkAgentLock({
473
530
  lockDir,
474
531
  agentId: candidateAgentId,
@@ -657,7 +714,7 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
657
714
  }
658
715
  }
659
716
 
660
- if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
717
+ if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
661
718
  let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
662
719
  const isAgyUuid = (sid: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
663
720
  const isImplicitAgyBoot =
@@ -764,14 +821,83 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
764
821
  }
765
822
 
766
823
  // Authoritative, secret-free status; absent fields never mean unclaimed.
767
- if (cliArgs.registerOnly && !TOKEN) {
824
+ if (isOneShotCli && (!TOKEN || TOKEN === "dev-token")) {
768
825
  process.stderr.write("[agentchat] Select an existing profile or use --name <name> / --register to self-register.\n");
769
826
  process.exit(1);
770
827
  }
828
+ if (cliArgs.join || cliArgs.send || cliArgs.wakeOnce) {
829
+ if (cliArgs.send && !cliArgs.text) {
830
+ process.stderr.write("[agentchat] ERROR: --send <channel> requires --text <message>. See --help.\n");
831
+ process.exit(1);
832
+ }
833
+ if (cliArgs.join && !cliArgs.send && !cliArgs.wakeOnce) {
834
+ const res = await joinChannelRest({
835
+ restUrl: REST_URL,
836
+ agentId: AGENT_ID,
837
+ token: TOKEN,
838
+ channelId: cliArgs.join,
839
+ });
840
+ console.log(JSON.stringify(res));
841
+ process.exit(res.ok ? 0 : 1);
842
+ }
843
+ const explicitMaxIdleMs = parseMaxIdleMs(cliArgs["max-idle"]);
844
+ if (cliArgs.send) {
845
+ if (cliArgs.join) {
846
+ await joinChannelRest({
847
+ restUrl: REST_URL,
848
+ agentId: AGENT_ID,
849
+ token: TOKEN,
850
+ channelId: cliArgs.join,
851
+ });
852
+ }
853
+ const res = await sendRestMessage({
854
+ restUrl: REST_URL,
855
+ configDir,
856
+ agentId: AGENT_ID,
857
+ token: TOKEN,
858
+ channelId: cliArgs.send,
859
+ text: cliArgs.text!,
860
+ replyTo: cliArgs["reply-to"],
861
+ maxIdleMs: explicitMaxIdleMs,
862
+ });
863
+ console.log(JSON.stringify(res));
864
+ process.exit(res.ok ? 0 : 1);
865
+ }
866
+ if (cliArgs.wakeOnce) {
867
+ const rawChans = [
868
+ ...(cliArgs.join ? [cliArgs.join] : []),
869
+ ...(cliArgs.channel ? cliArgs.channel.split(",").map((c) => c.trim()).filter(Boolean) : []),
870
+ ];
871
+ const channels = rawChans.length > 0 ? [...new Set(rawChans)] : ["welcome"];
872
+ const timeoutSec = cliArgs.timeout !== undefined ? Number(cliArgs.timeout) : 240;
873
+ const timeoutMs = Number.isFinite(timeoutSec) && timeoutSec >= 0 ? timeoutSec * 1000 : 240_000;
874
+ const ev = await wakeOnce({
875
+ restUrl: REST_URL,
876
+ configDir,
877
+ agentId: AGENT_ID,
878
+ displayName: profile.display_name || AGENT_ID,
879
+ token: TOKEN,
880
+ channels,
881
+ timeoutMs,
882
+ maxIdleMs: explicitMaxIdleMs,
883
+ });
884
+ console.log(JSON.stringify(ev));
885
+ process.exit(0);
886
+ }
887
+ }
771
888
  if (TOKEN && TOKEN !== "dev-token") {
772
889
  const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
773
890
  process.stderr.write(`[agentchat] ${claimSummary(status)}\n`);
774
891
  if (cliArgs.registerOnly) {
892
+ try {
893
+ mkdirSync(configDir, { recursive: true });
894
+ const lastSeenFile = join(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
895
+ const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
896
+ if (!cursor.get(CURSOR_INIT_KEY)) {
897
+ cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
898
+ persistCursor(lastSeenFile, cursor, (m) => process.stderr.write(m));
899
+ }
900
+ } catch {}
775
901
  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}));
776
902
  process.exit(0);
777
903
  }
@@ -3179,6 +3305,10 @@ const handleToolCall = async (request: any): Promise<any> => {
3179
3305
  // SDK error, so the calling agent always learns the call failed. Explicit
3180
3306
  // error returns below carry isError:true individually.
3181
3307
  try {
3308
+ if (codexIdentity && (AGENT_ID !== codexIdentity.agentId ||
3309
+ ["connect_profile", "switch_profile", "disconnect_profile"].includes(name))) {
3310
+ return { content: [{ type: "text", text: "Codex bridge owns this tool identity; change the bot configuration and restart to change identity." }], isError: true };
3311
+ }
3182
3312
  // Resolve the calling session/conversation and automatically route to its
3183
3313
  // bound ProfileSlot in profileSlots (`session_id -> profile -> agent_id`).
3184
3314
  const rawMeta = (request.params as any)?._meta;
@@ -3187,7 +3317,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3187
3317
  args as Record<string, any> | undefined,
3188
3318
  rawMeta,
3189
3319
  );
3190
- if (callerSession) {
3320
+ if (callerSession && !codexIdentity) {
3191
3321
  runtimeSession = callerSession;
3192
3322
  const binds = loadSessionBinds(configDir);
3193
3323
  const boundProfileName = binds[callerSession.sessionId];
@@ -3295,7 +3425,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3295
3425
 
3296
3426
  // Shared Cursor MCP: heal back to grok-bind identity if another agent
3297
3427
  // stole the live profile via switch_profile. No-op when unbound.
3298
- ensureGrokBoundIdentity();
3428
+ if (!codexIdentity) ensureGrokBoundIdentity();
3299
3429
 
3300
3430
  // Identity guard (task_muk0154j_pstaosfn): after a suspect fallback (explicit
3301
3431
  // identity lost on respawn → default profile), WRITE tools refuse until the
@@ -4068,19 +4198,28 @@ const handleToolCall = async (request: any): Promise<any> => {
4068
4198
 
4069
4199
  if (name === "join_channel") {
4070
4200
  const { chat_id } = args as any;
4071
- // Try WebSocket join first, then verify membership via REST
4201
+ // Try WebSocket join + authoritative REST /join (for non-WS / proxied clients)
4072
4202
  if (ws && ws.readyState === WebSocket.OPEN) {
4073
4203
  try { ws.send(JSON.stringify({ type: "join_channel", channel_id: chat_id, agent_id: AGENT_ID })); } catch {}
4074
4204
  }
4075
- // Verify by checking membership
4076
4205
  try {
4077
- await new Promise(r => setTimeout(r, 500)); // wait for server to process
4206
+ const joinRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/join`, {
4207
+ method: "POST",
4208
+ headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
4209
+ body: JSON.stringify({ sender_id: AGENT_ID }),
4210
+ });
4211
+ if (joinRes.ok) {
4212
+ if (activeSlot) activeSlot.knownChannels.add(chat_id);
4213
+ const brief = await channelBrief(chat_id).catch(() => "");
4214
+ return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}\n${brief}` }] };
4215
+ }
4216
+ await new Promise(r => setTimeout(r, 300));
4078
4217
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4079
4218
  if (r.ok) {
4080
4219
  const data = await r.json() as any;
4081
4220
  const isMember = (data.members || []).some((m: any) => m.agent_id === AGENT_ID);
4082
4221
  if (isMember) {
4083
- // P3: joining hands you the room's capability synopsis immediately.
4222
+ if (activeSlot) activeSlot.knownChannels.add(chat_id);
4084
4223
  const brief = await channelBrief(chat_id).catch(() => "");
4085
4224
  return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}\n${brief}` }] };
4086
4225
  }
@@ -4559,7 +4698,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4559
4698
  const list = msgs.map((m: any) => formatHistoryMessage(m, false)).join("\n");
4560
4699
  return { content: [{ type: "text", text: `${msgs.length} messages:\n${list}` }] };
4561
4700
  }
4562
- return { content: [{ type: "text", text: `Failed to get history (${r.status})` }] };
4701
+ return { content: [{ type: "text", text: `Failed to get history (${r.status})` }], isError: true };
4563
4702
  } catch (e) {
4564
4703
  return { content: [{ type: "text", text: `Error: ${e}` }] };
4565
4704
  }
@@ -5730,6 +5869,10 @@ async function checkVersionStaleness(): Promise<void> {
5730
5869
 
5731
5870
  // --- Start ---
5732
5871
  async function main() {
5872
+ if (codexIdentity) {
5873
+ const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
5874
+ if (status.authentication !== "ok") throw new Error("Codex tool authentication failed; bridge transport alone is not tool readiness");
5875
+ }
5733
5876
  installStdioLifecycleGuards();
5734
5877
  if (!toolOnlyMode) {
5735
5878
  syncOpenBoundSessions();
@@ -340,12 +340,19 @@ export function detectRuntimeSession(
340
340
  return { sessionId: explicitSid, runtime: "custom" };
341
341
  }
342
342
 
343
- // 6. Antigravity parent language_server discovery (macOS & Linux)
344
- if (
345
- env === process.env ||
343
+ // 6. Antigravity parent language_server discovery (macOS & Linux).
344
+ // Skip expensive ps/lsof parent-tree probing when running against a loopback mock
345
+ // hub in tests with a stripped env (unless explicit Antigravity env vars are set).
346
+ const hasExplicitAgyEnv =
346
347
  env.__CFBundleIdentifier === "com.google.antigravity" ||
347
- Boolean(env.AGY_BROWSER_WS_URL)
348
- ) {
348
+ Boolean(env.AGY_BROWSER_WS_URL) ||
349
+ Boolean(env.ANTIGRAVITY_LS_ADDRESS) ||
350
+ Boolean(env.ANTIGRAVITY_CSRF_TOKEN);
351
+ const isMockHubSubprocess =
352
+ !hasExplicitAgyEnv &&
353
+ typeof env.AGENTCHAT_REST_URL === "string" &&
354
+ /^http:\/\/127\.0\.0\.1:\d+/.test(env.AGENTCHAT_REST_URL);
355
+ if (!isMockHubSubprocess && (env === process.env || hasExplicitAgyEnv)) {
349
356
  const agyHost = discoverAntigravityHost();
350
357
  if (agyHost && agyHost.openConversations.length === 1) {
351
358
  return { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
@@ -441,6 +448,16 @@ export function discoverAntigravityHost(opts?: {
441
448
  .filter((s) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s));
442
449
  return { lsPid: process.ppid, csrfToken: envCsrf, ports, openConversations };
443
450
  }
451
+ const hasExplicitAgyEnv =
452
+ process.env.__CFBundleIdentifier === "com.google.antigravity" ||
453
+ Boolean(process.env.AGY_BROWSER_WS_URL);
454
+ if (
455
+ !hasExplicitAgyEnv &&
456
+ typeof process.env.AGENTCHAT_REST_URL === "string" &&
457
+ /^http:\/\/127\.0\.0\.1:\d+/.test(process.env.AGENTCHAT_REST_URL)
458
+ ) {
459
+ return null;
460
+ }
444
461
  }
445
462
 
446
463
  const now = Date.now();