aismemory 0.8.3 → 0.8.6
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/README.md +163 -5
- package/dist/__tests__/agent-archive.test.js +1 -0
- package/dist/__tests__/agent-archive.test.js.map +1 -1
- package/dist/__tests__/agent-key-mode.test.js +52 -5
- package/dist/__tests__/agent-key-mode.test.js.map +1 -1
- package/dist/__tests__/agent-load-persistence.test.js +12 -4
- package/dist/__tests__/agent-load-persistence.test.js.map +1 -1
- package/dist/__tests__/agent-load-session-override-e2e.test.js +1 -1
- package/dist/__tests__/agent-load-session-override-e2e.test.js.map +1 -1
- package/dist/__tests__/agentmemory.test.js +16 -3
- package/dist/__tests__/agentmemory.test.js.map +1 -1
- package/dist/__tests__/ais-http.test.js +102 -1
- package/dist/__tests__/ais-http.test.js.map +1 -1
- package/dist/__tests__/auto-enroll-key.test.js +20 -1
- package/dist/__tests__/auto-enroll-key.test.js.map +1 -1
- package/dist/__tests__/auto-handoff-identity-gate.test.d.ts +1 -0
- package/dist/__tests__/auto-handoff-identity-gate.test.js +64 -0
- package/dist/__tests__/auto-handoff-identity-gate.test.js.map +1 -0
- package/dist/__tests__/cli-info.test.js +8 -4
- package/dist/__tests__/cli-info.test.js.map +1 -1
- package/dist/__tests__/client-credential-expiry.test.d.ts +1 -0
- package/dist/__tests__/client-credential-expiry.test.js +319 -0
- package/dist/__tests__/client-credential-expiry.test.js.map +1 -0
- package/dist/__tests__/declared-agent.test.d.ts +1 -0
- package/dist/__tests__/declared-agent.test.js +60 -0
- package/dist/__tests__/declared-agent.test.js.map +1 -0
- package/dist/__tests__/delegated-read-args.test.js +1 -1
- package/dist/__tests__/delegated-read-args.test.js.map +1 -1
- package/dist/__tests__/device-flow-gate-e2e.test.js +1 -1
- package/dist/__tests__/device-flow-gate-e2e.test.js.map +1 -1
- package/dist/__tests__/disk-bearer-host-binding-e2e.test.d.ts +1 -0
- package/dist/__tests__/disk-bearer-host-binding-e2e.test.js +235 -0
- package/dist/__tests__/disk-bearer-host-binding-e2e.test.js.map +1 -0
- package/dist/__tests__/doctor-bin-insecure-ais-url.test.d.ts +1 -0
- package/dist/__tests__/doctor-bin-insecure-ais-url.test.js +29 -0
- package/dist/__tests__/doctor-bin-insecure-ais-url.test.js.map +1 -0
- package/dist/__tests__/doctor.test.js +65 -6
- package/dist/__tests__/doctor.test.js.map +1 -1
- package/dist/__tests__/dream-poll.test.d.ts +1 -0
- package/dist/__tests__/dream-poll.test.js +130 -0
- package/dist/__tests__/dream-poll.test.js.map +1 -0
- package/dist/__tests__/enable-key-auth.test.d.ts +1 -0
- package/dist/__tests__/enable-key-auth.test.js +212 -0
- package/dist/__tests__/enable-key-auth.test.js.map +1 -0
- package/dist/__tests__/existing-hashes.test.js +3 -6
- package/dist/__tests__/existing-hashes.test.js.map +1 -1
- package/dist/__tests__/full-context-view-forwarding.test.js +72 -5
- package/dist/__tests__/full-context-view-forwarding.test.js.map +1 -1
- package/dist/__tests__/helpers/setup-credential-source.d.ts +3 -0
- package/dist/__tests__/helpers/setup-credential-source.js +43 -0
- package/dist/__tests__/helpers/setup-credential-source.js.map +1 -0
- package/dist/__tests__/hooks.test.d.ts +1 -0
- package/dist/__tests__/hooks.test.js +476 -0
- package/dist/__tests__/hooks.test.js.map +1 -0
- package/dist/__tests__/hydration.test.js +2 -0
- package/dist/__tests__/hydration.test.js.map +1 -1
- package/dist/__tests__/install.test.js +45 -1
- package/dist/__tests__/install.test.js.map +1 -1
- package/dist/__tests__/invite-accept.test.js +167 -3
- package/dist/__tests__/invite-accept.test.js.map +1 -1
- package/dist/__tests__/key-auth-host-binding.test.d.ts +1 -0
- package/dist/__tests__/key-auth-host-binding.test.js +120 -0
- package/dist/__tests__/key-auth-host-binding.test.js.map +1 -0
- package/dist/__tests__/key-auth.test.js +35 -27
- package/dist/__tests__/key-auth.test.js.map +1 -1
- package/dist/__tests__/keyauth-error-surface-e2e.test.js +1 -1
- package/dist/__tests__/keyauth-error-surface-e2e.test.js.map +1 -1
- package/dist/__tests__/list-all-agents.test.js +17 -15
- package/dist/__tests__/list-all-agents.test.js.map +1 -1
- package/dist/__tests__/mcp-init-no-auth.test.js +1 -1
- package/dist/__tests__/mcp-init-no-auth.test.js.map +1 -1
- package/dist/__tests__/mcp-instructions.test.d.ts +1 -0
- package/dist/__tests__/mcp-instructions.test.js +26 -0
- package/dist/__tests__/mcp-instructions.test.js.map +1 -0
- package/dist/__tests__/mcp-tools.test.js +157 -2
- package/dist/__tests__/mcp-tools.test.js.map +1 -1
- package/dist/__tests__/memory-export.test.d.ts +1 -0
- package/dist/__tests__/memory-export.test.js +78 -0
- package/dist/__tests__/memory-export.test.js.map +1 -0
- package/dist/__tests__/memory-get.test.d.ts +1 -0
- package/dist/__tests__/memory-get.test.js +178 -0
- package/dist/__tests__/memory-get.test.js.map +1 -0
- package/dist/__tests__/memory-write-failure.test.js +1 -1
- package/dist/__tests__/memory-write-failure.test.js.map +1 -1
- package/dist/__tests__/no-registered-keys-disk-bearer-fallback.test.js +1 -1
- package/dist/__tests__/no-registered-keys-disk-bearer-fallback.test.js.map +1 -1
- package/dist/__tests__/oauth-credentials.test.js +9 -0
- package/dist/__tests__/oauth-credentials.test.js.map +1 -1
- package/dist/__tests__/operating-layer-put.test.d.ts +1 -0
- package/dist/__tests__/operating-layer-put.test.js +159 -0
- package/dist/__tests__/operating-layer-put.test.js.map +1 -0
- package/dist/__tests__/owner-credentials.test.d.ts +1 -0
- package/dist/__tests__/owner-credentials.test.js +266 -0
- package/dist/__tests__/owner-credentials.test.js.map +1 -0
- package/dist/__tests__/owner-keychain-agent-load.test.d.ts +1 -0
- package/dist/__tests__/owner-keychain-agent-load.test.js +57 -0
- package/dist/__tests__/owner-keychain-agent-load.test.js.map +1 -0
- package/dist/__tests__/recall-order-by.test.d.ts +1 -0
- package/dist/__tests__/recall-order-by.test.js +115 -0
- package/dist/__tests__/recall-order-by.test.js.map +1 -0
- package/dist/__tests__/reconnect-survival-e2e.test.js +264 -0
- package/dist/__tests__/reconnect-survival-e2e.test.js.map +1 -1
- package/dist/__tests__/remember-duplicate-truth.test.js +11 -0
- package/dist/__tests__/remember-duplicate-truth.test.js.map +1 -1
- package/dist/__tests__/remember-expires-in.test.d.ts +1 -0
- package/dist/__tests__/remember-expires-in.test.js +125 -0
- package/dist/__tests__/remember-expires-in.test.js.map +1 -0
- package/dist/__tests__/resolve-agent-preference-e2e.test.js +2 -1
- package/dist/__tests__/resolve-agent-preference-e2e.test.js.map +1 -1
- package/dist/__tests__/resolve-agent-preference.test.js +19 -8
- package/dist/__tests__/resolve-agent-preference.test.js.map +1 -1
- package/dist/__tests__/session-identity.test.js +23 -1
- package/dist/__tests__/session-identity.test.js.map +1 -1
- package/dist/__tests__/session-start.test.d.ts +1 -0
- package/dist/__tests__/session-start.test.js +179 -0
- package/dist/__tests__/session-start.test.js.map +1 -0
- package/dist/__tests__/setup-codex-get.test.d.ts +1 -0
- package/dist/__tests__/setup-codex-get.test.js +101 -0
- package/dist/__tests__/setup-codex-get.test.js.map +1 -0
- package/dist/__tests__/setup-links.test.d.ts +1 -0
- package/dist/__tests__/setup-links.test.js +37 -0
- package/dist/__tests__/setup-links.test.js.map +1 -0
- package/dist/__tests__/setup-orientation-codex.test.d.ts +1 -0
- package/dist/__tests__/setup-orientation-codex.test.js +76 -0
- package/dist/__tests__/setup-orientation-codex.test.js.map +1 -0
- package/dist/__tests__/setup-remove-cli.test.d.ts +1 -0
- package/dist/__tests__/setup-remove-cli.test.js +327 -0
- package/dist/__tests__/setup-remove-cli.test.js.map +1 -0
- package/dist/__tests__/setup-signed-in.test.d.ts +1 -0
- package/dist/__tests__/setup-signed-in.test.js +506 -0
- package/dist/__tests__/setup-signed-in.test.js.map +1 -0
- package/dist/__tests__/setup.test.d.ts +1 -0
- package/dist/__tests__/setup.test.js +1253 -0
- package/dist/__tests__/setup.test.js.map +1 -0
- package/dist/__tests__/signin-keychain.test.d.ts +1 -0
- package/dist/__tests__/signin-keychain.test.js +79 -0
- package/dist/__tests__/signin-keychain.test.js.map +1 -0
- package/dist/__tests__/silent-renewal-e2e.test.js +1 -1
- package/dist/__tests__/silent-renewal-e2e.test.js.map +1 -1
- package/dist/__tests__/split-brain-upgrade-e2e.test.js +1 -1
- package/dist/__tests__/split-brain-upgrade-e2e.test.js.map +1 -1
- package/dist/__tests__/startup-credential-warning-e2e.test.js +13 -7
- package/dist/__tests__/startup-credential-warning-e2e.test.js.map +1 -1
- package/dist/__tests__/startup-identity.test.d.ts +1 -0
- package/dist/__tests__/startup-identity.test.js +252 -0
- package/dist/__tests__/startup-identity.test.js.map +1 -0
- package/dist/__tests__/startup-insecure-ais-url.test.d.ts +1 -0
- package/dist/__tests__/startup-insecure-ais-url.test.js +36 -0
- package/dist/__tests__/startup-insecure-ais-url.test.js.map +1 -0
- package/dist/__tests__/sync-auth.test.d.ts +1 -0
- package/dist/__tests__/sync-auth.test.js +69 -0
- package/dist/__tests__/sync-auth.test.js.map +1 -0
- package/dist/__tests__/sync-doc.test.d.ts +1 -0
- package/dist/__tests__/sync-doc.test.js +13 -0
- package/dist/__tests__/sync-doc.test.js.map +1 -0
- package/dist/__tests__/sync-memory-cli.test.js +1 -1
- package/dist/__tests__/sync-memory-cli.test.js.map +1 -1
- package/dist/__tests__/test-home-isolation.test.d.ts +1 -0
- package/dist/__tests__/test-home-isolation.test.js +29 -0
- package/dist/__tests__/test-home-isolation.test.js.map +1 -0
- package/dist/__tests__/token-expiry-reauth.test.js +1 -1
- package/dist/__tests__/token-expiry-reauth.test.js.map +1 -1
- package/dist/__tests__/token-manager-permanent-failures.test.d.ts +1 -0
- package/dist/__tests__/token-manager-permanent-failures.test.js +162 -0
- package/dist/__tests__/token-manager-permanent-failures.test.js.map +1 -0
- package/dist/__tests__/token-rejection-reauth-e2e.test.js +1 -1
- package/dist/__tests__/token-rejection-reauth-e2e.test.js.map +1 -1
- package/dist/__tests__/tool-args.test.js +12 -0
- package/dist/__tests__/tool-args.test.js.map +1 -1
- package/dist/__tests__/workspace-key-mode.test.js +5 -1
- package/dist/__tests__/workspace-key-mode.test.js.map +1 -1
- package/dist/agent-key-mode.d.ts +1 -0
- package/dist/agent-key-mode.js +57 -28
- package/dist/agent-key-mode.js.map +1 -1
- package/dist/agent-preference.d.ts +12 -0
- package/dist/agent-preference.js +10 -1
- package/dist/agent-preference.js.map +1 -1
- package/dist/ais-http-error.d.ts +5 -0
- package/dist/ais-http-error.js +10 -0
- package/dist/ais-http-error.js.map +1 -1
- package/dist/ais-http.d.ts +4 -0
- package/dist/ais-http.js +28 -9
- package/dist/ais-http.js.map +1 -1
- package/dist/auto-handoff.js +2 -1
- package/dist/auto-handoff.js.map +1 -1
- package/dist/cli/doctor.d.ts +8 -0
- package/dist/cli/doctor.js +22 -2
- package/dist/cli/doctor.js.map +1 -1
- package/dist/cli/enable-key-auth.js +41 -20
- package/dist/cli/enable-key-auth.js.map +1 -1
- package/dist/cli/export-harness.d.ts +13 -0
- package/dist/cli/export-harness.js +110 -0
- package/dist/cli/export-harness.js.map +1 -0
- package/dist/cli/hooks.d.ts +95 -0
- package/dist/cli/hooks.js +665 -0
- package/dist/cli/hooks.js.map +1 -0
- package/dist/cli/install.d.ts +4 -0
- package/dist/cli/install.js +47 -5
- package/dist/cli/install.js.map +1 -1
- package/dist/cli/invite-accept.d.ts +36 -1
- package/dist/cli/invite-accept.js +137 -3
- package/dist/cli/invite-accept.js.map +1 -1
- package/dist/cli/owner-credentials.d.ts +52 -0
- package/dist/cli/owner-credentials.js +387 -0
- package/dist/cli/owner-credentials.js.map +1 -0
- package/dist/cli/pull-memory.js +2 -2
- package/dist/cli/pull-memory.js.map +1 -1
- package/dist/cli/setup-core.d.ts +220 -0
- package/dist/cli/setup-core.js +2381 -0
- package/dist/cli/setup-core.js.map +1 -0
- package/dist/cli/setup.d.ts +59 -0
- package/dist/cli/setup.js +407 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/cli/sync-memory.js +7 -9
- package/dist/cli/sync-memory.js.map +1 -1
- package/dist/cli-info.js +6 -1
- package/dist/cli-info.js.map +1 -1
- package/dist/credential-expiry.d.ts +10 -0
- package/dist/credential-expiry.js +41 -0
- package/dist/credential-expiry.js.map +1 -0
- package/dist/declared-agent.d.ts +20 -0
- package/dist/declared-agent.js +40 -0
- package/dist/declared-agent.js.map +1 -0
- package/dist/device-poll.d.ts +1 -0
- package/dist/device-poll.js.map +1 -1
- package/dist/dream-poll.d.ts +19 -0
- package/dist/dream-poll.js +93 -0
- package/dist/dream-poll.js.map +1 -0
- package/dist/env-agent.d.ts +6 -1
- package/dist/env-agent.js +18 -5
- package/dist/env-agent.js.map +1 -1
- package/dist/hydration.js +2 -1
- package/dist/hydration.js.map +1 -1
- package/dist/index.js +199 -27
- package/dist/index.js.map +1 -1
- package/dist/key-auth.d.ts +49 -3
- package/dist/key-auth.js +175 -7
- package/dist/key-auth.js.map +1 -1
- package/dist/mcp/tools.d.ts +2 -0
- package/dist/mcp/tools.js +79 -35
- package/dist/mcp/tools.js.map +1 -1
- package/dist/mcp-instructions.d.ts +6 -0
- package/dist/mcp-instructions.js +7 -0
- package/dist/mcp-instructions.js.map +1 -0
- package/dist/memory-export.d.ts +30 -0
- package/dist/memory-export.js +116 -0
- package/dist/memory-export.js.map +1 -0
- package/dist/oauth-credentials.d.ts +1 -1
- package/dist/oauth-credentials.js +3 -3
- package/dist/oauth-credentials.js.map +1 -1
- package/dist/operating-layer-write.d.ts +134 -0
- package/dist/operating-layer-write.js +224 -0
- package/dist/operating-layer-write.js.map +1 -0
- package/dist/pipeline/bulk-store.d.ts +2 -5
- package/dist/pipeline/bulk-store.js +2 -4
- package/dist/pipeline/bulk-store.js.map +1 -1
- package/dist/pipeline/existing-hashes.d.ts +2 -5
- package/dist/pipeline/existing-hashes.js +1 -2
- package/dist/pipeline/existing-hashes.js.map +1 -1
- package/dist/pipeline/sync-auth.d.ts +12 -0
- package/dist/pipeline/sync-auth.js +64 -0
- package/dist/pipeline/sync-auth.js.map +1 -0
- package/dist/refresh.js +2 -1
- package/dist/refresh.js.map +1 -1
- package/dist/run-pass-mode.js +15 -19
- package/dist/run-pass-mode.js.map +1 -1
- package/dist/session-identity.d.ts +32 -0
- package/dist/session-identity.js +73 -1
- package/dist/session-identity.js.map +1 -1
- package/dist/session-start.d.ts +68 -0
- package/dist/session-start.js +176 -0
- package/dist/session-start.js.map +1 -0
- package/dist/signin-keychain.d.ts +54 -0
- package/dist/signin-keychain.js +200 -0
- package/dist/signin-keychain.js.map +1 -0
- package/dist/startup-identity.d.ts +71 -0
- package/dist/startup-identity.js +233 -0
- package/dist/startup-identity.js.map +1 -0
- package/dist/token-manager.d.ts +14 -0
- package/dist/token-manager.js +68 -6
- package/dist/token-manager.js.map +1 -1
- package/dist/tool-args.d.ts +64 -1
- package/dist/tool-args.js +184 -1
- package/dist/tool-args.js.map +1 -1
- package/dist/types.d.ts +8 -0
- package/dist/workspace-key-mode.d.ts +2 -0
- package/dist/workspace-key-mode.js +28 -26
- package/dist/workspace-key-mode.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,2381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `aismemory setup` — plan and apply portable harness files (CORBOT-664C9203).
|
|
3
|
+
* Pure file/plan logic; network and prompts live in setup.ts.
|
|
4
|
+
*/
|
|
5
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
6
|
+
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
7
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { AgentApiKeyConfigError, loadAgentApiKeyConfig } from '../agent-key-mode.js';
|
|
10
|
+
import { hasEnrolledKey } from '../key-auth.js';
|
|
11
|
+
import { credentialsFilePath } from '../oauth-credentials.js';
|
|
12
|
+
import { loadRunPassConfig, RunPassConfigError } from '../run-pass-mode.js';
|
|
13
|
+
import { loadSessionIdentity } from '../session-identity.js';
|
|
14
|
+
import { loadWorkspaceKeyConfig, WorkspaceKeyConfigError } from '../workspace-key-mode.js';
|
|
15
|
+
import { renderEntryInstructions } from './install.js';
|
|
16
|
+
import { backupFileOnce, HookFailure, inline, NO_CREDENTIAL_HINT, resolveHookClient, stripInvisibles, writeTextFileAtomic, } from './hooks.js';
|
|
17
|
+
import { readPackageVersion } from '../version-check.js';
|
|
18
|
+
export const SETUP_NEW_WARNING = 'This is new and has not been checked end to end on a fresh machine yet.';
|
|
19
|
+
/** Prefix for setup-owned MCP connections (distinct from `aismemory` install). */
|
|
20
|
+
export const SETUP_MCP_NAME_PREFIX = 'aismemory-setup-';
|
|
21
|
+
export const CURSOR_SETUP_FILE_MARKER = '# made by aismemory setup';
|
|
22
|
+
export function setupMcpServerName(agentId) {
|
|
23
|
+
const hex = agentId.replace(/-/g, '').replace(/[^a-f0-9]/gi, '').slice(0, 8).toLowerCase();
|
|
24
|
+
return `${SETUP_MCP_NAME_PREFIX}${hex}`;
|
|
25
|
+
}
|
|
26
|
+
export function configReadErrorMessage(path) {
|
|
27
|
+
return `could not read ${path}; it was left as it is`;
|
|
28
|
+
}
|
|
29
|
+
const operatingLayerRuleSchema = z.object({
|
|
30
|
+
id: z.string().optional(),
|
|
31
|
+
description: z.string(),
|
|
32
|
+
authoredBy: z.string().optional(),
|
|
33
|
+
tier: z.string().optional(),
|
|
34
|
+
}).passthrough();
|
|
35
|
+
const setupContextSchema = z.object({
|
|
36
|
+
success: z.literal(true),
|
|
37
|
+
data: z.object({
|
|
38
|
+
operatingLayer: z.object({
|
|
39
|
+
rules: z.array(operatingLayerRuleSchema),
|
|
40
|
+
}).passthrough().optional(),
|
|
41
|
+
}).passthrough(),
|
|
42
|
+
}).passthrough();
|
|
43
|
+
const MARKER_BEGIN = /^<!-- aismemory:setup:begin agent=([^\s]+) id=([^\s]+) -->$/;
|
|
44
|
+
const MARKER_END = /^<!-- aismemory:setup:end agent=([^\s]+) id=([^\s]+) -->$/;
|
|
45
|
+
const TOML_MARKER_BEGIN = /^# aismemory:setup:begin agent=([^\s]+) id=([^\s]+)$/;
|
|
46
|
+
const TOML_MARKER_END = /^# aismemory:setup:end agent=([^\s]+) id=([^\s]+)$/;
|
|
47
|
+
const BLOCK_ID_PATTERN = /^[a-f0-9]{16}$/;
|
|
48
|
+
export function setupRulesFileName(agentId) {
|
|
49
|
+
return `aismemory-${agentId}.mdc`;
|
|
50
|
+
}
|
|
51
|
+
export function setupBeginMarker(agentId, blockId) {
|
|
52
|
+
return `<!-- aismemory:setup:begin agent=${agentId} id=${blockId} -->`;
|
|
53
|
+
}
|
|
54
|
+
export function setupEndMarker(agentId, blockId) {
|
|
55
|
+
return `<!-- aismemory:setup:end agent=${agentId} id=${blockId} -->`;
|
|
56
|
+
}
|
|
57
|
+
function tomBeginMarker(agentId, blockId) {
|
|
58
|
+
return `# aismemory:setup:begin agent=${agentId} id=${blockId}`;
|
|
59
|
+
}
|
|
60
|
+
function tomEndMarker(agentId, blockId) {
|
|
61
|
+
return `# aismemory:setup:end agent=${agentId} id=${blockId}`;
|
|
62
|
+
}
|
|
63
|
+
const SETUP_MAX_ACCOUNT_RULES = 200;
|
|
64
|
+
const SETUP_MAX_RULE_BYTES = 600;
|
|
65
|
+
export const UNRECOGNISED_CONTEXT_MSG = 'the service answer was not understood; nothing was changed';
|
|
66
|
+
function isAccountRule(rule) {
|
|
67
|
+
return rule.authoredBy === 'owner';
|
|
68
|
+
}
|
|
69
|
+
function isOwnRule(rule) {
|
|
70
|
+
return !isAccountRule(rule);
|
|
71
|
+
}
|
|
72
|
+
export function sanitizeForTerminal(text) {
|
|
73
|
+
const base = inline(text);
|
|
74
|
+
return base.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x1b]/g, '');
|
|
75
|
+
}
|
|
76
|
+
const SERVICE_STRING_TERMINAL_MAX = 80;
|
|
77
|
+
/** Service-supplied text for banners and refusals: strip controls and cap length; ids are not passed through this. */
|
|
78
|
+
export function displayServiceStringForTerminal(text) {
|
|
79
|
+
const clean = sanitizeForTerminal(text);
|
|
80
|
+
if (clean.length <= SERVICE_STRING_TERMINAL_MAX)
|
|
81
|
+
return clean;
|
|
82
|
+
return `${clean.slice(0, SERVICE_STRING_TERMINAL_MAX - 1)}…`;
|
|
83
|
+
}
|
|
84
|
+
export function splitOperatingLayerRules(raw) {
|
|
85
|
+
const parsed = setupContextSchema.safeParse(raw);
|
|
86
|
+
if (!parsed.success) {
|
|
87
|
+
throw new Error(UNRECOGNISED_CONTEXT_MSG);
|
|
88
|
+
}
|
|
89
|
+
const rules = parsed.data.data.operatingLayer?.rules ?? [];
|
|
90
|
+
const accountRules = [];
|
|
91
|
+
const ownNotes = [];
|
|
92
|
+
let rulesOmitted = 0;
|
|
93
|
+
for (const rule of rules) {
|
|
94
|
+
if (!isOwnRule(rule)) {
|
|
95
|
+
if (accountRules.length >= SETUP_MAX_ACCOUNT_RULES) {
|
|
96
|
+
rulesOmitted += 1;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const line = formatSetupRuleLine(rule.description);
|
|
100
|
+
if (line !== null) {
|
|
101
|
+
const trimmed = Buffer.from(line, 'utf8').length > SETUP_MAX_RULE_BYTES
|
|
102
|
+
? `${line.slice(0, SETUP_MAX_RULE_BYTES)}…`
|
|
103
|
+
: line;
|
|
104
|
+
accountRules.push(trimmed);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
ownNotes.push(sanitizeForTerminal(rule.description));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (rules.length > accountRules.length + ownNotes.length + rulesOmitted) {
|
|
112
|
+
// dropped hostile lines do not count toward omit message
|
|
113
|
+
}
|
|
114
|
+
return { accountRules, ownNotes, rulesOmitted };
|
|
115
|
+
}
|
|
116
|
+
/** Refuse or neutralise hostile rule text; null means drop the rule. */
|
|
117
|
+
export function formatSetupRuleLine(description) {
|
|
118
|
+
if (/[\r\n]/.test(description))
|
|
119
|
+
return null;
|
|
120
|
+
const stripped = stripInvisibles(description);
|
|
121
|
+
if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\x80-\x9F]/.test(stripped))
|
|
122
|
+
return null;
|
|
123
|
+
const line = inline(description);
|
|
124
|
+
if (line.includes('\n') || line.includes('\r'))
|
|
125
|
+
return null;
|
|
126
|
+
if (/aismemory:setup/i.test(line))
|
|
127
|
+
return null;
|
|
128
|
+
return line;
|
|
129
|
+
}
|
|
130
|
+
export function buildInstructionBlock(agentId, blockId, entryInstructions, ruleLines, setDate) {
|
|
131
|
+
const lines = [
|
|
132
|
+
setupBeginMarker(agentId, blockId),
|
|
133
|
+
entryInstructions.trimEnd(),
|
|
134
|
+
];
|
|
135
|
+
if (ruleLines.length > 0) {
|
|
136
|
+
const heading = `## Rules from your account (set ${setDate})`;
|
|
137
|
+
lines.push('', heading, ...ruleLines.map((rule) => `- ${rule}`));
|
|
138
|
+
}
|
|
139
|
+
lines.push(setupEndMarker(agentId, blockId));
|
|
140
|
+
return `${lines.join('\n')}\n`;
|
|
141
|
+
}
|
|
142
|
+
export function buildCursorRulesFile(agentId, blockId, entryInstructions, ruleLines, setDate, includeFrontMatter) {
|
|
143
|
+
const block = buildInstructionBlock(agentId, blockId, entryInstructions, ruleLines, setDate);
|
|
144
|
+
if (!includeFrontMatter)
|
|
145
|
+
return block.endsWith('\n') ? block : `${block}\n`;
|
|
146
|
+
const frontMatter = [
|
|
147
|
+
'---',
|
|
148
|
+
'alwaysApply: true',
|
|
149
|
+
`description: AIS Memory portable setup for agent ${agentId}`,
|
|
150
|
+
CURSOR_SETUP_FILE_MARKER,
|
|
151
|
+
'---',
|
|
152
|
+
'',
|
|
153
|
+
].join('\n');
|
|
154
|
+
return `${frontMatter}${block}`;
|
|
155
|
+
}
|
|
156
|
+
export function cursorFileCreatedBySetup(content) {
|
|
157
|
+
return content.includes(CURSOR_SETUP_FILE_MARKER);
|
|
158
|
+
}
|
|
159
|
+
export function contentIsOnlySetupCursorShell(content, agentId) {
|
|
160
|
+
const trimmed = content.trimEnd();
|
|
161
|
+
if (!cursorFileCreatedBySetup(content))
|
|
162
|
+
return false;
|
|
163
|
+
const withoutBlock = removeInstructionBlock(trimmed, agentId, false);
|
|
164
|
+
const shell = withoutBlock.trim();
|
|
165
|
+
if (shell.length === 0)
|
|
166
|
+
return true;
|
|
167
|
+
const lines = shell.split('\n').map((l) => l.trim());
|
|
168
|
+
const allowed = new Set([
|
|
169
|
+
'---',
|
|
170
|
+
'alwaysApply: true',
|
|
171
|
+
CURSOR_SETUP_FILE_MARKER,
|
|
172
|
+
`description: AIS Memory portable setup for agent ${agentId}`,
|
|
173
|
+
]);
|
|
174
|
+
return lines.every((line) => allowed.has(line));
|
|
175
|
+
}
|
|
176
|
+
export function readBlockIdFromFile(content, agentId) {
|
|
177
|
+
const lines = content.split('\n');
|
|
178
|
+
for (const line of lines) {
|
|
179
|
+
const match = MARKER_BEGIN.exec(line.trim());
|
|
180
|
+
if (match?.[1] === agentId && BLOCK_ID_PATTERN.test(match[2] ?? ''))
|
|
181
|
+
return match[2] ?? null;
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
export function hasDamagedSetupMarker(content, agentId) {
|
|
186
|
+
const lines = content.split('\n');
|
|
187
|
+
let openAgent = null;
|
|
188
|
+
let openId = null;
|
|
189
|
+
for (const line of lines) {
|
|
190
|
+
const begin = MARKER_BEGIN.exec(line.trim());
|
|
191
|
+
if (begin !== null) {
|
|
192
|
+
if (openAgent !== null)
|
|
193
|
+
return true;
|
|
194
|
+
openAgent = begin[1] ?? null;
|
|
195
|
+
openId = begin[2] ?? null;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const end = MARKER_END.exec(line.trim());
|
|
199
|
+
if (end !== null) {
|
|
200
|
+
if (openAgent === null)
|
|
201
|
+
return true;
|
|
202
|
+
if ((end[1] ?? '') !== openAgent || (end[2] ?? '') !== (openId ?? ''))
|
|
203
|
+
return true;
|
|
204
|
+
openAgent = null;
|
|
205
|
+
openId = null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return openAgent === agentId;
|
|
209
|
+
}
|
|
210
|
+
export function blockIdForPlan(existingContent, agentId) {
|
|
211
|
+
if (existingContent !== null) {
|
|
212
|
+
if (hasDamagedSetupMarker(existingContent, agentId)) {
|
|
213
|
+
throw new Error('Refusing to change instructions: setup marker block is damaged; fix it and run setup again.');
|
|
214
|
+
}
|
|
215
|
+
const fromFile = readBlockIdFromFile(existingContent, agentId);
|
|
216
|
+
if (fromFile !== null)
|
|
217
|
+
return fromFile;
|
|
218
|
+
}
|
|
219
|
+
return randomBytes(8).toString('hex');
|
|
220
|
+
}
|
|
221
|
+
export function applyInstructionBlock(existing, block, agentId) {
|
|
222
|
+
if (existing === null) {
|
|
223
|
+
return block.endsWith('\n') ? block : `${block}\n`;
|
|
224
|
+
}
|
|
225
|
+
const lines = existing.split('\n');
|
|
226
|
+
const beginIdx = lines.findIndex((line) => {
|
|
227
|
+
const match = MARKER_BEGIN.exec(line.trim());
|
|
228
|
+
return match?.[1] === agentId;
|
|
229
|
+
});
|
|
230
|
+
if (beginIdx === -1) {
|
|
231
|
+
if (existing.length === 0)
|
|
232
|
+
return block.endsWith('\n') ? block : `${block}\n`;
|
|
233
|
+
const sep = existing.endsWith('\n') ? '' : '\n';
|
|
234
|
+
return `${existing}${sep}${block}`;
|
|
235
|
+
}
|
|
236
|
+
let endIdx = -1;
|
|
237
|
+
let blockId = '';
|
|
238
|
+
for (let i = beginIdx; i < lines.length; i += 1) {
|
|
239
|
+
const match = MARKER_END.exec(lines[i]?.trim() ?? '');
|
|
240
|
+
if (match?.[1] === agentId) {
|
|
241
|
+
blockId = match[2] ?? '';
|
|
242
|
+
endIdx = i;
|
|
243
|
+
break;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (endIdx === -1 || blockId === '')
|
|
247
|
+
return existing;
|
|
248
|
+
const before = lines.slice(0, beginIdx).join('\n');
|
|
249
|
+
const after = lines.slice(endIdx + 1).join('\n');
|
|
250
|
+
const mid = block.trimEnd();
|
|
251
|
+
const head = before.length > 0 ? `${before}\n` : '';
|
|
252
|
+
const tail = after.length > 0 ? `\n${after}` : (before.length > 0 ? '\n' : '');
|
|
253
|
+
return `${head}${mid}${tail}`;
|
|
254
|
+
}
|
|
255
|
+
export function removeInstructionBlock(content, agentId, requireBlockId) {
|
|
256
|
+
const hadTrailingNewline = content.endsWith('\n');
|
|
257
|
+
const lines = content.split('\n');
|
|
258
|
+
const beginIdx = lines.findIndex((line) => {
|
|
259
|
+
const match = MARKER_BEGIN.exec(line.trim());
|
|
260
|
+
return match?.[1] === agentId;
|
|
261
|
+
});
|
|
262
|
+
if (beginIdx === -1)
|
|
263
|
+
return content;
|
|
264
|
+
let endIdx = -1;
|
|
265
|
+
let beginId = '';
|
|
266
|
+
for (let i = beginIdx; i < lines.length; i += 1) {
|
|
267
|
+
const endMatch = MARKER_END.exec(lines[i]?.trim() ?? '');
|
|
268
|
+
if (endMatch?.[1] === agentId) {
|
|
269
|
+
beginId = MARKER_BEGIN.exec(lines[beginIdx]?.trim() ?? '')?.[2] ?? '';
|
|
270
|
+
endIdx = i;
|
|
271
|
+
if (requireBlockId && (endMatch[2] ?? '') !== beginId) {
|
|
272
|
+
throw new Error('Refusing to remove setup block: end marker id does not match begin marker id.');
|
|
273
|
+
}
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (endIdx === -1)
|
|
278
|
+
return content;
|
|
279
|
+
const before = lines.slice(0, beginIdx).join('\n');
|
|
280
|
+
const after = lines.slice(endIdx + 1).join('\n');
|
|
281
|
+
let result;
|
|
282
|
+
if (before.length === 0)
|
|
283
|
+
result = after;
|
|
284
|
+
else if (after.length === 0)
|
|
285
|
+
result = before;
|
|
286
|
+
else
|
|
287
|
+
result = `${before}\n${after}`;
|
|
288
|
+
if (hadTrailingNewline && !result.endsWith('\n'))
|
|
289
|
+
return `${result}\n`;
|
|
290
|
+
if (!hadTrailingNewline && result.endsWith('\n'))
|
|
291
|
+
return result.replace(/\n$/, '');
|
|
292
|
+
return result;
|
|
293
|
+
}
|
|
294
|
+
function isDirectory(path) {
|
|
295
|
+
try {
|
|
296
|
+
const st = lstatSync(path);
|
|
297
|
+
return st.isDirectory() || st.isSymbolicLink();
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
function isFile(path) {
|
|
304
|
+
try {
|
|
305
|
+
const st = lstatSync(path);
|
|
306
|
+
return st.isFile() || st.isSymbolicLink();
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
function resolvedRootDir(root) {
|
|
313
|
+
const normalized = resolve(root);
|
|
314
|
+
try {
|
|
315
|
+
return existsSync(normalized) ? realpathSync(normalized) : normalized;
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return normalized;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function pathContainedInRoot(root, absolutePath) {
|
|
322
|
+
const rootReal = resolvedRootDir(root);
|
|
323
|
+
const candidate = resolve(absolutePath);
|
|
324
|
+
return candidate === rootReal || candidate.startsWith(`${rootReal}/`);
|
|
325
|
+
}
|
|
326
|
+
function isPathUnderRoot(rootNorm, path) {
|
|
327
|
+
const p = resolve(path);
|
|
328
|
+
return p === rootNorm || p.startsWith(`${rootNorm}/`);
|
|
329
|
+
}
|
|
330
|
+
/** Under --project, refuse any symlink on the path to `targetPath` inside the project tree. */
|
|
331
|
+
function refuseSymlinkInProject(projectRoot, targetPath) {
|
|
332
|
+
const rootNorm = resolve(projectRoot);
|
|
333
|
+
let current = resolve(targetPath);
|
|
334
|
+
while (isPathUnderRoot(rootNorm, current)) {
|
|
335
|
+
try {
|
|
336
|
+
if (lstatSync(current).isSymbolicLink()) {
|
|
337
|
+
return `refusing to write through a link inside the project: ${current}`;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
// skip missing segments
|
|
342
|
+
}
|
|
343
|
+
if (current === rootNorm)
|
|
344
|
+
break;
|
|
345
|
+
const parent = dirname(current);
|
|
346
|
+
if (parent === current)
|
|
347
|
+
break;
|
|
348
|
+
current = parent;
|
|
349
|
+
}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
function projectRootFromRoots(roots) {
|
|
353
|
+
if (roots.length < 2)
|
|
354
|
+
return undefined;
|
|
355
|
+
return resolve(roots[1]);
|
|
356
|
+
}
|
|
357
|
+
function matchedRootIsProject(roots, matchedRoot) {
|
|
358
|
+
const project = projectRootFromRoots(roots);
|
|
359
|
+
return project !== undefined && resolve(matchedRoot) === project;
|
|
360
|
+
}
|
|
361
|
+
/** Refuse when a symlink on the path to `targetPath` resolves outside `root`. */
|
|
362
|
+
export function refuseSymlinkWrite(root, targetPath) {
|
|
363
|
+
const rootNorm = resolve(root);
|
|
364
|
+
let current = resolve(targetPath);
|
|
365
|
+
while (isPathUnderRoot(rootNorm, current)) {
|
|
366
|
+
// lstat, not existsSync: existsSync follows the link, so a broken link would be skipped and the
|
|
367
|
+
// write would create its target, which may lie outside the root.
|
|
368
|
+
let isLink = false;
|
|
369
|
+
try {
|
|
370
|
+
isLink = lstatSync(current).isSymbolicLink();
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
isLink = false;
|
|
374
|
+
}
|
|
375
|
+
try {
|
|
376
|
+
if (isLink) {
|
|
377
|
+
let linkReal;
|
|
378
|
+
try {
|
|
379
|
+
linkReal = realpathSync(current);
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return `refusing to write through a link that points outside ${rootNorm}: ${current}`;
|
|
383
|
+
}
|
|
384
|
+
if (!pathContainedInRoot(root, linkReal)) {
|
|
385
|
+
return `refusing to write through a link that points outside ${rootNorm}: ${current}`;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
// skip missing segments
|
|
391
|
+
}
|
|
392
|
+
if (current === rootNorm)
|
|
393
|
+
break;
|
|
394
|
+
const parent = dirname(current);
|
|
395
|
+
if (parent === current)
|
|
396
|
+
break;
|
|
397
|
+
current = parent;
|
|
398
|
+
}
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
function existingRealPath(path) {
|
|
402
|
+
if (!existsSync(path))
|
|
403
|
+
return resolve(path);
|
|
404
|
+
return realpathSync(path);
|
|
405
|
+
}
|
|
406
|
+
export function detectSetupTool(home, tool) {
|
|
407
|
+
switch (tool) {
|
|
408
|
+
case 'claude-code':
|
|
409
|
+
return isDirectory(join(home, '.claude')) || isFile(join(home, '.claude.json'));
|
|
410
|
+
case 'cursor':
|
|
411
|
+
return isDirectory(join(home, '.cursor'));
|
|
412
|
+
case 'codex':
|
|
413
|
+
return isDirectory(join(home, '.codex'));
|
|
414
|
+
default:
|
|
415
|
+
return false;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function claudeInstructionPath(home, project) {
|
|
419
|
+
if (project !== undefined)
|
|
420
|
+
return join(project, 'CLAUDE.md');
|
|
421
|
+
return join(home, '.claude', 'CLAUDE.md');
|
|
422
|
+
}
|
|
423
|
+
function cursorInstructionPath(project, agentId) {
|
|
424
|
+
if (project === undefined)
|
|
425
|
+
return null;
|
|
426
|
+
return join(project, '.cursor', 'rules', setupRulesFileName(agentId));
|
|
427
|
+
}
|
|
428
|
+
function codexInstructionPath(home, project) {
|
|
429
|
+
if (project !== undefined)
|
|
430
|
+
return join(project, 'AGENTS.md');
|
|
431
|
+
return join(home, '.codex', 'AGENTS.md');
|
|
432
|
+
}
|
|
433
|
+
function readTextFile(path) {
|
|
434
|
+
if (!existsSync(path))
|
|
435
|
+
return null;
|
|
436
|
+
try {
|
|
437
|
+
return readFileSync(path, 'utf8');
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
throw new Error(configReadErrorMessage(path));
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
function parseJsonFile(path, raw) {
|
|
444
|
+
try {
|
|
445
|
+
const parsed = JSON.parse(raw);
|
|
446
|
+
if (!isJsonObject(parsed)) {
|
|
447
|
+
throw new Error('Refusing to change MCP config: root is not a JSON object.');
|
|
448
|
+
}
|
|
449
|
+
return parsed;
|
|
450
|
+
}
|
|
451
|
+
catch (err) {
|
|
452
|
+
if (err instanceof Error && err.message.startsWith('Refusing'))
|
|
453
|
+
throw err;
|
|
454
|
+
throw new Error(configReadErrorMessage(path));
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
export function mcpEntryAgentId(entry) {
|
|
458
|
+
const env = entry['env'];
|
|
459
|
+
if (!isJsonObject(env))
|
|
460
|
+
return null;
|
|
461
|
+
const id = env['AIS_AGENT_ID'];
|
|
462
|
+
return typeof id === 'string' ? id : null;
|
|
463
|
+
}
|
|
464
|
+
export function otherAismemoryConnectionNames(servers, ourName) {
|
|
465
|
+
const names = [];
|
|
466
|
+
for (const key of Object.keys(servers)) {
|
|
467
|
+
if (key === ourName)
|
|
468
|
+
continue;
|
|
469
|
+
if (key.startsWith('aismemory'))
|
|
470
|
+
names.push(key);
|
|
471
|
+
}
|
|
472
|
+
return names.sort();
|
|
473
|
+
}
|
|
474
|
+
function mcpEntryVersionMatches(entry, version) {
|
|
475
|
+
const args = entry['args'];
|
|
476
|
+
if (!Array.isArray(args))
|
|
477
|
+
return false;
|
|
478
|
+
const want = `aismemory@${version}`;
|
|
479
|
+
return args.some((a) => a === want);
|
|
480
|
+
}
|
|
481
|
+
const MCP_AGENT_ID_LINE = /^\s*AIS_AGENT_ID=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\s*$/im;
|
|
482
|
+
const UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
483
|
+
function isRecordValue(value) {
|
|
484
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* `codex mcp get <name> --json` (its plain output masks env values as *****).
|
|
488
|
+
* Reads transport.env.AIS_AGENT_ID only; anything else is null (UNKNOWN to the caller).
|
|
489
|
+
*/
|
|
490
|
+
function agentIdFromCodexJson(text) {
|
|
491
|
+
const start = text.indexOf('{');
|
|
492
|
+
const end = text.lastIndexOf('}');
|
|
493
|
+
if (start < 0 || end <= start)
|
|
494
|
+
return null;
|
|
495
|
+
let parsed;
|
|
496
|
+
try {
|
|
497
|
+
parsed = JSON.parse(text.slice(start, end + 1));
|
|
498
|
+
}
|
|
499
|
+
catch {
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
if (!isRecordValue(parsed))
|
|
503
|
+
return null;
|
|
504
|
+
const transport = parsed['transport'];
|
|
505
|
+
if (!isRecordValue(transport))
|
|
506
|
+
return null;
|
|
507
|
+
const env = transport['env'];
|
|
508
|
+
if (!isRecordValue(env))
|
|
509
|
+
return null;
|
|
510
|
+
const id = env['AIS_AGENT_ID'];
|
|
511
|
+
return typeof id === 'string' && UUID_ONLY.test(id) ? id : null;
|
|
512
|
+
}
|
|
513
|
+
export function agentIdFromMcpGetOutput(stdout) {
|
|
514
|
+
if (stdout.trimStart().startsWith('{'))
|
|
515
|
+
return agentIdFromCodexJson(stdout);
|
|
516
|
+
const lines = stdout.split('\n');
|
|
517
|
+
let inEnvironment = false;
|
|
518
|
+
for (const line of lines) {
|
|
519
|
+
if (/^\s*Environment:\s*$/.test(line)) {
|
|
520
|
+
inEnvironment = true;
|
|
521
|
+
continue;
|
|
522
|
+
}
|
|
523
|
+
if (inEnvironment) {
|
|
524
|
+
if (line.length > 0 && !/^\s/.test(line)) {
|
|
525
|
+
inEnvironment = false;
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
const match = MCP_AGENT_ID_LINE.exec(line);
|
|
529
|
+
if (match?.[1] !== undefined)
|
|
530
|
+
return match[1];
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
export const MCP_GET_TIMEOUT_MS = 60_000;
|
|
536
|
+
export function claudeMcpGetArgv(serverName) {
|
|
537
|
+
return ['mcp', 'get', serverName];
|
|
538
|
+
}
|
|
539
|
+
export function classifyMcpGetResult(result, serverName) {
|
|
540
|
+
if (result.code === 0) {
|
|
541
|
+
const owner = agentIdFromMcpGetOutput(`${result.stdout}\n${result.stderr}`);
|
|
542
|
+
return owner !== null ? 'present' : 'unknown';
|
|
543
|
+
}
|
|
544
|
+
const text = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
|
545
|
+
// Only the tools' own sentence for a missing connection, at the start of a line and naming the connection
|
|
546
|
+
// that was asked for: `No MCP server named "<name>".` (Claude Code) or `Error: No MCP server named '<name>'
|
|
547
|
+
// found.` (Codex). The same words echoed inside another failure, or about another name, stay "unknown".
|
|
548
|
+
const wanted = serverName.toLowerCase();
|
|
549
|
+
for (const line of text.split('\n')) {
|
|
550
|
+
const match = /^(?:error: )?no mcp server named (["']?)([^"'\s]+)\1(?=[\s.]|$)/.exec(line.trim());
|
|
551
|
+
if (match !== null && match[2] === wanted)
|
|
552
|
+
return 'absent';
|
|
553
|
+
}
|
|
554
|
+
return 'unknown';
|
|
555
|
+
}
|
|
556
|
+
function mcpGetReportsUpToDate(stdout, stderr, version) {
|
|
557
|
+
return `${stdout}\n${stderr}`.includes(`aismemory@${version}`);
|
|
558
|
+
}
|
|
559
|
+
export function codexMcpGetArgv(serverName) {
|
|
560
|
+
return ['mcp', 'get', serverName, '--json'];
|
|
561
|
+
}
|
|
562
|
+
export function manualClaudeMcpRemoveCommand(serverName) {
|
|
563
|
+
return `claude mcp remove --scope user ${serverName}`;
|
|
564
|
+
}
|
|
565
|
+
function fingerprintContent(content) {
|
|
566
|
+
return createHash('sha256').update(content ?? '').digest('hex');
|
|
567
|
+
}
|
|
568
|
+
function fileChangeStatus(path, nextContent) {
|
|
569
|
+
if (!existsSync(path))
|
|
570
|
+
return 'new';
|
|
571
|
+
const current = readFileSync(path, 'utf8');
|
|
572
|
+
return current === nextContent ? 'unchanged' : 'changed';
|
|
573
|
+
}
|
|
574
|
+
function stableStringifyMcp(config) {
|
|
575
|
+
return `${JSON.stringify(config, null, 2)}\n`;
|
|
576
|
+
}
|
|
577
|
+
function buildMcpServerEntry(agentId, version) {
|
|
578
|
+
return {
|
|
579
|
+
command: 'npx',
|
|
580
|
+
args: ['-y', `aismemory@${version}`],
|
|
581
|
+
env: {
|
|
582
|
+
AIS_AGENT_ID: agentId,
|
|
583
|
+
},
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
function isJsonObject(value) {
|
|
587
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
588
|
+
}
|
|
589
|
+
function deepJsonEqual(a, b) {
|
|
590
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
591
|
+
}
|
|
592
|
+
function detectJsonIndent(existingJson) {
|
|
593
|
+
const trailingNewline = existingJson.endsWith('\n');
|
|
594
|
+
const firstIndented = existingJson.split('\n').find((line) => /^\s+\S/.test(line));
|
|
595
|
+
if (firstIndented !== undefined && firstIndented.startsWith('\t')) {
|
|
596
|
+
return { space: '\t', trailingNewline };
|
|
597
|
+
}
|
|
598
|
+
const m = /^(\s+)/.exec(firstIndented ?? '');
|
|
599
|
+
const spaces = m?.[1]?.length ?? 2;
|
|
600
|
+
return { space: spaces, trailingNewline };
|
|
601
|
+
}
|
|
602
|
+
/** Parse JSON, add only `mcpServers.<name>`, verify no other keys or servers change. */
|
|
603
|
+
function mergeJsonMcpConfigPreserving(existingJson, agentId, version, serverName, configPath) {
|
|
604
|
+
const parsed = parseJsonFile(configPath, existingJson);
|
|
605
|
+
const snapshot = JSON.parse(JSON.stringify(parsed));
|
|
606
|
+
const entry = buildMcpServerEntry(agentId, version);
|
|
607
|
+
const servers = parsed['mcpServers'];
|
|
608
|
+
if (!isJsonObject(servers)) {
|
|
609
|
+
throw new Error('Refusing to change MCP config: mcpServers is not an object.');
|
|
610
|
+
}
|
|
611
|
+
if (Object.prototype.hasOwnProperty.call(servers, serverName))
|
|
612
|
+
return existingJson;
|
|
613
|
+
const nextRoot = { ...parsed, mcpServers: { ...servers, [serverName]: entry } };
|
|
614
|
+
const { space, trailingNewline } = detectJsonIndent(existingJson);
|
|
615
|
+
const serialized = JSON.stringify(nextRoot, null, space);
|
|
616
|
+
const withNl = trailingNewline ? `${serialized}\n` : serialized;
|
|
617
|
+
let reparsed;
|
|
618
|
+
try {
|
|
619
|
+
reparsed = JSON.parse(withNl);
|
|
620
|
+
}
|
|
621
|
+
catch {
|
|
622
|
+
throw new Error('Refusing to change MCP config: merge did not produce valid JSON.');
|
|
623
|
+
}
|
|
624
|
+
if (!isJsonObject(reparsed)) {
|
|
625
|
+
throw new Error('Refusing to change MCP config: merge did not produce a JSON object.');
|
|
626
|
+
}
|
|
627
|
+
for (const key of Object.keys(snapshot)) {
|
|
628
|
+
if (key === 'mcpServers')
|
|
629
|
+
continue;
|
|
630
|
+
if (!deepJsonEqual(reparsed[key], snapshot[key])) {
|
|
631
|
+
throw new Error('Refusing to change MCP config: merge would alter other top-level keys.');
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
const afterServers = reparsed['mcpServers'];
|
|
635
|
+
if (!isJsonObject(afterServers)) {
|
|
636
|
+
throw new Error('Refusing to change MCP config: mcpServers is not an object after merge.');
|
|
637
|
+
}
|
|
638
|
+
for (const key of Object.keys(servers)) {
|
|
639
|
+
if (!deepJsonEqual(afterServers[key], servers[key])) {
|
|
640
|
+
throw new Error('Refusing to change MCP config: merge would alter other server entries.');
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return withNl;
|
|
644
|
+
}
|
|
645
|
+
export function mergeJsonMcpConfig(existingJson, agentId, version, serverName, configPath = '(mcp.json)') {
|
|
646
|
+
const entry = buildMcpServerEntry(agentId, version);
|
|
647
|
+
if (existingJson !== null && existingJson.trim() !== '') {
|
|
648
|
+
const parsed = parseJsonFile(configPath, existingJson);
|
|
649
|
+
const serversField = parsed['mcpServers'];
|
|
650
|
+
if (serversField !== undefined && !isJsonObject(serversField)) {
|
|
651
|
+
throw new Error(`Refusing to change MCP config: mcpServers is not an object.`);
|
|
652
|
+
}
|
|
653
|
+
if (isJsonObject(serversField)
|
|
654
|
+
&& Object.keys(serversField).length > 0) {
|
|
655
|
+
return {
|
|
656
|
+
content: mergeJsonMcpConfigPreserving(existingJson, agentId, version, serverName, configPath),
|
|
657
|
+
entryOnly: entry,
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
const root = { ...parsed };
|
|
661
|
+
const servers = isJsonObject(root['mcpServers']) ? { ...root['mcpServers'] } : {};
|
|
662
|
+
servers[serverName] = entry;
|
|
663
|
+
root['mcpServers'] = servers;
|
|
664
|
+
return { content: stableStringifyMcp(root), entryOnly: entry };
|
|
665
|
+
}
|
|
666
|
+
const root = {
|
|
667
|
+
mcpServers: {
|
|
668
|
+
[serverName]: entry,
|
|
669
|
+
},
|
|
670
|
+
};
|
|
671
|
+
return { content: stableStringifyMcp(root), entryOnly: entry };
|
|
672
|
+
}
|
|
673
|
+
export function jsonHasMcpServer(existingJson, serverName) {
|
|
674
|
+
if (existingJson === null || existingJson.trim() === '')
|
|
675
|
+
return false;
|
|
676
|
+
try {
|
|
677
|
+
const parsed = JSON.parse(existingJson);
|
|
678
|
+
if (!isJsonObject(parsed))
|
|
679
|
+
return false;
|
|
680
|
+
const servers = parsed['mcpServers'];
|
|
681
|
+
if (!isJsonObject(servers))
|
|
682
|
+
return false;
|
|
683
|
+
return Object.prototype.hasOwnProperty.call(servers, serverName);
|
|
684
|
+
}
|
|
685
|
+
catch {
|
|
686
|
+
return false;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
export function removeJsonMcpEntry(existingJson, serverName, configPath, keepEmptyServers = false) {
|
|
690
|
+
const parsed = (() => {
|
|
691
|
+
try {
|
|
692
|
+
return JSON.parse(existingJson);
|
|
693
|
+
}
|
|
694
|
+
catch {
|
|
695
|
+
throw new Error(configReadErrorMessage(configPath));
|
|
696
|
+
}
|
|
697
|
+
})();
|
|
698
|
+
if (!isJsonObject(parsed))
|
|
699
|
+
return existingJson;
|
|
700
|
+
const root = { ...parsed };
|
|
701
|
+
const servers = root['mcpServers'];
|
|
702
|
+
if (!isJsonObject(servers))
|
|
703
|
+
return existingJson;
|
|
704
|
+
const merged = { ...servers };
|
|
705
|
+
delete merged[serverName];
|
|
706
|
+
if (Object.keys(merged).length === 0 && !keepEmptyServers)
|
|
707
|
+
delete root['mcpServers'];
|
|
708
|
+
else
|
|
709
|
+
root['mcpServers'] = merged;
|
|
710
|
+
return stableStringifyMcp(root);
|
|
711
|
+
}
|
|
712
|
+
function codexMcpTableHeader(serverName) {
|
|
713
|
+
return `[mcp_servers.${serverName}]`;
|
|
714
|
+
}
|
|
715
|
+
function escapeRegexLiteral(text) {
|
|
716
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
717
|
+
}
|
|
718
|
+
function lineHasForeignCodexMcpHeader(line, serverName) {
|
|
719
|
+
const quoted = escapeRegexLiteral(serverName);
|
|
720
|
+
const pattern = new RegExp(`^\\[mcp_servers\\.(?:"${quoted}"|'${quoted}'|${quoted})(?:\\.[^\\]]+)?\\]\\s*(?:#.*)?$`);
|
|
721
|
+
if (pattern.test(line.trim()))
|
|
722
|
+
return true;
|
|
723
|
+
return new RegExp(`^\\[mcp_servers\\.\\s*['"]${quoted}['"]\\s*\\]`).test(line.trim());
|
|
724
|
+
}
|
|
725
|
+
function foreignCodexMcpHeader(content, serverName, agentId) {
|
|
726
|
+
const lines = content.split('\n');
|
|
727
|
+
let inOurBlock = false;
|
|
728
|
+
for (const line of lines) {
|
|
729
|
+
const begin = TOML_MARKER_BEGIN.exec(line.trim());
|
|
730
|
+
if (begin !== null) {
|
|
731
|
+
inOurBlock = begin[1] === agentId;
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
if (TOML_MARKER_END.test(line.trim())) {
|
|
735
|
+
inOurBlock = false;
|
|
736
|
+
continue;
|
|
737
|
+
}
|
|
738
|
+
if (inOurBlock)
|
|
739
|
+
continue;
|
|
740
|
+
if (lineHasForeignCodexMcpHeader(line, serverName))
|
|
741
|
+
return true;
|
|
742
|
+
}
|
|
743
|
+
return false;
|
|
744
|
+
}
|
|
745
|
+
function damagedTomlMarker(content, agentId) {
|
|
746
|
+
const lines = content.split('\n');
|
|
747
|
+
let open = false;
|
|
748
|
+
let openAgent = null;
|
|
749
|
+
for (const line of lines) {
|
|
750
|
+
const begin = TOML_MARKER_BEGIN.exec(line.trim());
|
|
751
|
+
if (begin !== null) {
|
|
752
|
+
if (open)
|
|
753
|
+
return true;
|
|
754
|
+
open = true;
|
|
755
|
+
openAgent = begin[1] ?? null;
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
const end = TOML_MARKER_END.exec(line.trim());
|
|
759
|
+
if (end !== null) {
|
|
760
|
+
if (!open)
|
|
761
|
+
return true;
|
|
762
|
+
if ((end[1] ?? '') !== openAgent)
|
|
763
|
+
return true;
|
|
764
|
+
open = false;
|
|
765
|
+
openAgent = null;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return open && openAgent === agentId;
|
|
769
|
+
}
|
|
770
|
+
function readTomlBlockId(content, agentId) {
|
|
771
|
+
for (const line of content.split('\n')) {
|
|
772
|
+
const match = TOML_MARKER_BEGIN.exec(line.trim());
|
|
773
|
+
if (match?.[1] === agentId && BLOCK_ID_PATTERN.test(match[2] ?? ''))
|
|
774
|
+
return match[2] ?? null;
|
|
775
|
+
}
|
|
776
|
+
return null;
|
|
777
|
+
}
|
|
778
|
+
function codexTomlBlock(agentId, blockId, version, serverName) {
|
|
779
|
+
const name = serverName;
|
|
780
|
+
return [
|
|
781
|
+
tomBeginMarker(agentId, blockId),
|
|
782
|
+
'',
|
|
783
|
+
codexMcpTableHeader(name),
|
|
784
|
+
'command = "npx"',
|
|
785
|
+
`args = ["-y", "aismemory@${version}"]`,
|
|
786
|
+
'',
|
|
787
|
+
`[mcp_servers.${name}.env]`,
|
|
788
|
+
`AIS_AGENT_ID = "${agentId}"`,
|
|
789
|
+
'',
|
|
790
|
+
tomEndMarker(agentId, blockId),
|
|
791
|
+
].join('\n');
|
|
792
|
+
}
|
|
793
|
+
export function mergeCodexTomlMcp(existing, agentId, version, serverName, _configPath = '(config.toml)') {
|
|
794
|
+
const raw = existing ?? '';
|
|
795
|
+
if (damagedTomlMarker(raw, agentId)) {
|
|
796
|
+
throw new Error('Refusing to change Codex config: setup MCP marker block is damaged; fix it and run setup again.');
|
|
797
|
+
}
|
|
798
|
+
if (foreignCodexMcpHeader(raw, serverName, agentId)) {
|
|
799
|
+
throw new Error(`Refusing to change Codex config: ${codexMcpTableHeader(serverName)} already exists outside setup markers.`);
|
|
800
|
+
}
|
|
801
|
+
const blockId = readTomlBlockId(raw, agentId) ?? randomBytes(8).toString('hex');
|
|
802
|
+
const lines = raw.split('\n');
|
|
803
|
+
const kept = [];
|
|
804
|
+
let inBlock = false;
|
|
805
|
+
for (const line of lines) {
|
|
806
|
+
if (TOML_MARKER_BEGIN.test(line.trim())) {
|
|
807
|
+
const m = TOML_MARKER_BEGIN.exec(line.trim());
|
|
808
|
+
if (m?.[1] === agentId) {
|
|
809
|
+
inBlock = true;
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (inBlock) {
|
|
814
|
+
if (TOML_MARKER_END.test(line.trim())) {
|
|
815
|
+
inBlock = false;
|
|
816
|
+
}
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
kept.push(line);
|
|
820
|
+
}
|
|
821
|
+
const trimmed = kept.join('\n').replace(/\n+$/, '');
|
|
822
|
+
const block = codexTomlBlock(agentId, blockId, version, serverName);
|
|
823
|
+
if (trimmed.length === 0)
|
|
824
|
+
return { content: `${block}\n`, blockId };
|
|
825
|
+
return { content: `${trimmed}\n\n${block}\n`, blockId };
|
|
826
|
+
}
|
|
827
|
+
export function codexTomlTablesOnce(content) {
|
|
828
|
+
const seen = new Set();
|
|
829
|
+
for (const line of content.split('\n')) {
|
|
830
|
+
const m = /^\[([^\]]+)\]/.exec(line.trim());
|
|
831
|
+
if (m === null)
|
|
832
|
+
continue;
|
|
833
|
+
const key = m[1] ?? '';
|
|
834
|
+
if (seen.has(key))
|
|
835
|
+
return false;
|
|
836
|
+
seen.add(key);
|
|
837
|
+
}
|
|
838
|
+
return true;
|
|
839
|
+
}
|
|
840
|
+
export function removeCodexTomlMcpEntry(existing, agentId, configPath = 'config.toml') {
|
|
841
|
+
const lines = existing.split('\n');
|
|
842
|
+
let beginIdx = -1;
|
|
843
|
+
let beginId = '';
|
|
844
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
845
|
+
const m = TOML_MARKER_BEGIN.exec(lines[i]?.trim() ?? '');
|
|
846
|
+
if (m?.[1] === agentId) {
|
|
847
|
+
beginIdx = i;
|
|
848
|
+
beginId = m[2] ?? '';
|
|
849
|
+
break;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
if (beginIdx === -1)
|
|
853
|
+
return existing;
|
|
854
|
+
let endIdx = -1;
|
|
855
|
+
for (let i = beginIdx + 1; i < lines.length; i += 1) {
|
|
856
|
+
const m = TOML_MARKER_END.exec(lines[i]?.trim() ?? '');
|
|
857
|
+
if (m?.[1] === agentId && (m[2] ?? '') === beginId) {
|
|
858
|
+
endIdx = i;
|
|
859
|
+
break;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
if (endIdx === -1) {
|
|
863
|
+
throw new Error(`the block in ${configPath} is damaged; remove it by hand`);
|
|
864
|
+
}
|
|
865
|
+
const kept = [...lines.slice(0, beginIdx), ...lines.slice(endIdx + 1)];
|
|
866
|
+
const out = kept.join('\n').replace(/\n+$/, '');
|
|
867
|
+
if (out.length === 0)
|
|
868
|
+
return '';
|
|
869
|
+
return existing.endsWith('\n') ? `${out}\n` : out;
|
|
870
|
+
}
|
|
871
|
+
export function claudeMcpAddArgv(agentId, version, serverName) {
|
|
872
|
+
return [
|
|
873
|
+
'mcp',
|
|
874
|
+
'add',
|
|
875
|
+
'--scope',
|
|
876
|
+
'user',
|
|
877
|
+
serverName,
|
|
878
|
+
'-e',
|
|
879
|
+
`AIS_AGENT_ID=${agentId}`,
|
|
880
|
+
'--',
|
|
881
|
+
'npx',
|
|
882
|
+
'-y',
|
|
883
|
+
`aismemory@${version}`,
|
|
884
|
+
];
|
|
885
|
+
}
|
|
886
|
+
export function claudeMcpRemoveArgv(serverName) {
|
|
887
|
+
return ['mcp', 'remove', '--scope', 'user', serverName];
|
|
888
|
+
}
|
|
889
|
+
export function codexMcpAddArgv(agentId, version, serverName) {
|
|
890
|
+
return [
|
|
891
|
+
'mcp',
|
|
892
|
+
'add',
|
|
893
|
+
serverName,
|
|
894
|
+
'--env',
|
|
895
|
+
`AIS_AGENT_ID=${agentId}`,
|
|
896
|
+
'--',
|
|
897
|
+
'npx',
|
|
898
|
+
'-y',
|
|
899
|
+
`aismemory@${version}`,
|
|
900
|
+
];
|
|
901
|
+
}
|
|
902
|
+
export function codexMcpRemoveArgv(serverName) {
|
|
903
|
+
return ['mcp', 'remove', serverName];
|
|
904
|
+
}
|
|
905
|
+
export function manualClaudeMcpAddCommand(agentId, version, serverName) {
|
|
906
|
+
const parts = ['claude', ...claudeMcpAddArgv(agentId, version, serverName)];
|
|
907
|
+
return parts.join(' ');
|
|
908
|
+
}
|
|
909
|
+
async function planCommandToolMcp(bin, agentId, version, serverName, toolchainOk, runner) {
|
|
910
|
+
const ourEntry = buildMcpServerEntry(agentId, version);
|
|
911
|
+
const addArgv = bin === 'claude'
|
|
912
|
+
? claudeMcpAddArgv(agentId, version, serverName)
|
|
913
|
+
: codexMcpAddArgv(agentId, version, serverName);
|
|
914
|
+
const label = bin === 'claude' ? '(claude mcp add)' : '(codex mcp add)';
|
|
915
|
+
if (!toolchainOk) {
|
|
916
|
+
if (bin === 'claude') {
|
|
917
|
+
const manual = manualClaudeMcpAddCommand(agentId, version, serverName);
|
|
918
|
+
return {
|
|
919
|
+
mcpPlan: {
|
|
920
|
+
transport: 'command',
|
|
921
|
+
path: label,
|
|
922
|
+
status: 'skipped',
|
|
923
|
+
planFingerprint: null,
|
|
924
|
+
ourServerEntry: ourEntry,
|
|
925
|
+
manualCommand: manual,
|
|
926
|
+
skipReason: `Claude Code is not done: claude is not on PATH; run: ${manual}`,
|
|
927
|
+
},
|
|
928
|
+
refused: true,
|
|
929
|
+
refuseReason: `Claude Code is not done: claude is not on PATH; run: ${manual}`,
|
|
930
|
+
};
|
|
931
|
+
}
|
|
932
|
+
return {
|
|
933
|
+
mcpPlan: {
|
|
934
|
+
transport: 'command',
|
|
935
|
+
path: label,
|
|
936
|
+
status: 'changed',
|
|
937
|
+
planFingerprint: null,
|
|
938
|
+
ourServerEntry: ourEntry,
|
|
939
|
+
commandArgv: addArgv,
|
|
940
|
+
},
|
|
941
|
+
refused: false,
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
if (runner === undefined) {
|
|
945
|
+
return {
|
|
946
|
+
mcpPlan: {
|
|
947
|
+
transport: 'command',
|
|
948
|
+
path: label,
|
|
949
|
+
status: 'changed',
|
|
950
|
+
planFingerprint: null,
|
|
951
|
+
ourServerEntry: ourEntry,
|
|
952
|
+
commandArgv: addArgv,
|
|
953
|
+
},
|
|
954
|
+
refused: false,
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
const getArgv = bin === 'claude' ? claudeMcpGetArgv(serverName) : codexMcpGetArgv(serverName);
|
|
958
|
+
const got = await runner(bin, getArgv, MCP_GET_TIMEOUT_MS);
|
|
959
|
+
const presence = classifyMcpGetResult(got, serverName);
|
|
960
|
+
if (presence === 'unknown') {
|
|
961
|
+
const manual = `${bin} ${getArgv.join(' ')}`;
|
|
962
|
+
return {
|
|
963
|
+
mcpPlan: null,
|
|
964
|
+
refused: true,
|
|
965
|
+
refuseReason: `Refusing ${bin === 'claude' ? 'Claude Code' : 'Codex'} MCP: could not verify ${serverName}; run: ${manual}`,
|
|
966
|
+
};
|
|
967
|
+
}
|
|
968
|
+
if (presence === 'absent') {
|
|
969
|
+
return {
|
|
970
|
+
mcpPlan: {
|
|
971
|
+
transport: 'command',
|
|
972
|
+
path: label,
|
|
973
|
+
status: 'changed',
|
|
974
|
+
planFingerprint: null,
|
|
975
|
+
ourServerEntry: ourEntry,
|
|
976
|
+
commandArgv: addArgv,
|
|
977
|
+
},
|
|
978
|
+
refused: false,
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
const owner = agentIdFromMcpGetOutput(`${got.stdout}\n${got.stderr}`);
|
|
982
|
+
if (owner === null) {
|
|
983
|
+
const manual = `${bin} ${getArgv.join(' ')}`;
|
|
984
|
+
return {
|
|
985
|
+
mcpPlan: null,
|
|
986
|
+
refused: true,
|
|
987
|
+
refuseReason: `Refusing ${bin === 'claude' ? 'Claude Code' : 'Codex'} MCP: could not read owner for ${serverName}; run: ${manual}`,
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
if (owner !== agentId) {
|
|
991
|
+
return {
|
|
992
|
+
mcpPlan: null,
|
|
993
|
+
refused: true,
|
|
994
|
+
refuseReason: `Refusing ${bin === 'claude' ? 'Claude Code' : 'Codex'} MCP: connection ${serverName} belongs to agent ${owner}, not ${agentId}.`,
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
const upToDate = mcpGetReportsUpToDate(got.stdout, got.stderr, version);
|
|
998
|
+
if (upToDate) {
|
|
999
|
+
return {
|
|
1000
|
+
mcpPlan: {
|
|
1001
|
+
transport: 'command',
|
|
1002
|
+
path: label,
|
|
1003
|
+
status: 'unchanged',
|
|
1004
|
+
planFingerprint: null,
|
|
1005
|
+
ourServerEntry: ourEntry,
|
|
1006
|
+
},
|
|
1007
|
+
refused: false,
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
return {
|
|
1011
|
+
mcpPlan: {
|
|
1012
|
+
transport: 'command',
|
|
1013
|
+
path: label,
|
|
1014
|
+
status: 'changed',
|
|
1015
|
+
planFingerprint: null,
|
|
1016
|
+
ourServerEntry: ourEntry,
|
|
1017
|
+
commandArgv: addArgv,
|
|
1018
|
+
},
|
|
1019
|
+
refused: false,
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
function planCursorMcpJson(mcpPath, existingMcp, agentId, version, serverName) {
|
|
1023
|
+
const ourEntry = buildMcpServerEntry(agentId, version);
|
|
1024
|
+
let otherNames = [];
|
|
1025
|
+
if (existingMcp !== null && existingMcp.trim() !== '') {
|
|
1026
|
+
const parsed = parseJsonFile(mcpPath, existingMcp);
|
|
1027
|
+
const servers = parsed['mcpServers'];
|
|
1028
|
+
if (servers !== undefined && !isJsonObject(servers)) {
|
|
1029
|
+
throw new Error('Refusing to change MCP config: mcpServers is not an object.');
|
|
1030
|
+
}
|
|
1031
|
+
if (servers !== undefined && isJsonObject(servers)) {
|
|
1032
|
+
otherNames = otherAismemoryConnectionNames(servers, serverName);
|
|
1033
|
+
if (Object.prototype.hasOwnProperty.call(servers, serverName)) {
|
|
1034
|
+
const raw = servers[serverName];
|
|
1035
|
+
if (!isJsonObject(raw)) {
|
|
1036
|
+
return {
|
|
1037
|
+
mcpPlan: null,
|
|
1038
|
+
refused: true,
|
|
1039
|
+
refuseReason: `Refusing Cursor MCP: entry ${serverName} is not an object.`,
|
|
1040
|
+
otherNames,
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
const owner = mcpEntryAgentId(raw);
|
|
1044
|
+
if (owner !== null && owner !== agentId) {
|
|
1045
|
+
return {
|
|
1046
|
+
mcpPlan: null,
|
|
1047
|
+
refused: true,
|
|
1048
|
+
refuseReason: `Refusing Cursor MCP: ${serverName} belongs to agent ${owner}, not ${agentId}.`,
|
|
1049
|
+
otherNames,
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
const status = mcpEntryVersionMatches(raw, version) ? 'unchanged' : 'changed';
|
|
1053
|
+
const merged = status === 'unchanged'
|
|
1054
|
+
? { content: existingMcp, entryOnly: ourEntry }
|
|
1055
|
+
: mergeJsonMcpConfig(existingMcp, agentId, version, serverName, mcpPath);
|
|
1056
|
+
return {
|
|
1057
|
+
mcpPlan: {
|
|
1058
|
+
transport: 'file',
|
|
1059
|
+
path: mcpPath,
|
|
1060
|
+
status,
|
|
1061
|
+
content: status === 'changed' ? merged.content : undefined,
|
|
1062
|
+
planFingerprint: fingerprintContent(existingMcp),
|
|
1063
|
+
ourServerEntry: ourEntry,
|
|
1064
|
+
},
|
|
1065
|
+
refused: false,
|
|
1066
|
+
otherNames,
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
const merged = mergeJsonMcpConfig(existingMcp, agentId, version, serverName, mcpPath);
|
|
1072
|
+
return {
|
|
1073
|
+
mcpPlan: {
|
|
1074
|
+
transport: 'file',
|
|
1075
|
+
path: mcpPath,
|
|
1076
|
+
status: fileChangeStatus(mcpPath, merged.content),
|
|
1077
|
+
content: merged.content,
|
|
1078
|
+
planFingerprint: fingerprintContent(existingMcp),
|
|
1079
|
+
ourServerEntry: merged.entryOnly,
|
|
1080
|
+
},
|
|
1081
|
+
refused: false,
|
|
1082
|
+
otherNames,
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
function planInstructionContent(existingInstructions, agentId, entryInstructions, accountRules, setDate, cursorShell) {
|
|
1086
|
+
const blockId = blockIdForPlan(existingInstructions, agentId);
|
|
1087
|
+
const block = buildInstructionBlock(agentId, blockId, entryInstructions, accountRules, setDate);
|
|
1088
|
+
if (existingInstructions === null && cursorShell) {
|
|
1089
|
+
return buildCursorRulesFile(agentId, blockId, entryInstructions, accountRules, setDate, true);
|
|
1090
|
+
}
|
|
1091
|
+
return applyInstructionBlock(existingInstructions, block, agentId);
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* A tool counts as installed when its folder is in the home, or when its
|
|
1095
|
+
* command answers on PATH. A tool that was installed and never started has no
|
|
1096
|
+
* folder yet (CORBOT-41B255A7). Cursor has no command to ask.
|
|
1097
|
+
*/
|
|
1098
|
+
function setupToolPresent(home, tool, toolchain) {
|
|
1099
|
+
if (detectSetupTool(home, tool))
|
|
1100
|
+
return true;
|
|
1101
|
+
if (tool === 'claude-code')
|
|
1102
|
+
return toolchain.claudeOnPath;
|
|
1103
|
+
if (tool === 'codex')
|
|
1104
|
+
return toolchain.codexMcpAdd;
|
|
1105
|
+
return false;
|
|
1106
|
+
}
|
|
1107
|
+
export async function buildSetupPlan(opts) {
|
|
1108
|
+
const version = opts.packageVersion ?? readPackageVersion();
|
|
1109
|
+
const toolchain = opts.toolchain ?? { claudeOnPath: false, codexMcpAdd: false };
|
|
1110
|
+
const serverName = setupMcpServerName(opts.agentId);
|
|
1111
|
+
const entryInstructions = renderEntryInstructions(opts.agentId);
|
|
1112
|
+
const { accountRules, ownNotes, rulesOmitted } = splitOperatingLayerRules(opts.fullContext);
|
|
1113
|
+
const noAccountRules = accountRules.length === 0;
|
|
1114
|
+
const roots = writableRoots(opts.home, opts.project);
|
|
1115
|
+
const tools = ['claude-code', 'cursor', 'codex'];
|
|
1116
|
+
const toolPlans = [];
|
|
1117
|
+
let claudeConnectionCheckNote = false;
|
|
1118
|
+
for (const tool of tools) {
|
|
1119
|
+
const found = setupToolPresent(opts.home, tool, toolchain);
|
|
1120
|
+
if (!found) {
|
|
1121
|
+
toolPlans.push({ tool, found: false, mcpPlan: null, instructionPlan: null, ownNotes: [] });
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
let mcpPlan = null;
|
|
1125
|
+
let instructionPlan = null;
|
|
1126
|
+
let refused = false;
|
|
1127
|
+
let otherAismemoryNames = [];
|
|
1128
|
+
const pathRefusal = planTimeWriteTargets(tool, opts.home, opts.project, opts.agentId)
|
|
1129
|
+
.map((p) => pathGuardMessage(roots, p))
|
|
1130
|
+
.find((m) => m !== null);
|
|
1131
|
+
if (pathRefusal !== undefined && pathRefusal !== null) {
|
|
1132
|
+
toolPlans.push({
|
|
1133
|
+
tool,
|
|
1134
|
+
found: true,
|
|
1135
|
+
mcpPlan: {
|
|
1136
|
+
transport: 'file',
|
|
1137
|
+
path: '(blocked)',
|
|
1138
|
+
status: 'skipped',
|
|
1139
|
+
planFingerprint: null,
|
|
1140
|
+
ourServerEntry: null,
|
|
1141
|
+
skipReason: pathRefusal,
|
|
1142
|
+
},
|
|
1143
|
+
instructionPlan: {
|
|
1144
|
+
path: null,
|
|
1145
|
+
status: 'skipped',
|
|
1146
|
+
content: '',
|
|
1147
|
+
planFingerprint: null,
|
|
1148
|
+
skipMessage: pathRefusal,
|
|
1149
|
+
},
|
|
1150
|
+
ownNotes: [],
|
|
1151
|
+
refused: true,
|
|
1152
|
+
});
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
if (tool === 'claude-code') {
|
|
1156
|
+
const planned = await planCommandToolMcp('claude', opts.agentId, version, serverName, toolchain.claudeOnPath, opts.commandRunner);
|
|
1157
|
+
mcpPlan = planned.mcpPlan;
|
|
1158
|
+
refused = planned.refused;
|
|
1159
|
+
if (planned.refuseReason !== undefined && mcpPlan === null) {
|
|
1160
|
+
mcpPlan = {
|
|
1161
|
+
transport: 'command',
|
|
1162
|
+
path: '(claude mcp add)',
|
|
1163
|
+
status: 'skipped',
|
|
1164
|
+
planFingerprint: null,
|
|
1165
|
+
ourServerEntry: null,
|
|
1166
|
+
skipReason: planned.refuseReason,
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
if (toolchain.claudeOnPath && opts.commandRunner !== undefined) {
|
|
1170
|
+
claudeConnectionCheckNote = true;
|
|
1171
|
+
}
|
|
1172
|
+
if (!refused) {
|
|
1173
|
+
const instructionPath = claudeInstructionPath(opts.home, opts.project);
|
|
1174
|
+
const existingInstructions = readTextFile(instructionPath);
|
|
1175
|
+
const next = planInstructionContent(existingInstructions, opts.agentId, entryInstructions, accountRules, opts.setDate, false);
|
|
1176
|
+
instructionPlan = {
|
|
1177
|
+
path: instructionPath,
|
|
1178
|
+
status: fileChangeStatus(instructionPath, next),
|
|
1179
|
+
content: next,
|
|
1180
|
+
planFingerprint: fingerprintContent(existingInstructions),
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
else {
|
|
1184
|
+
instructionPlan = {
|
|
1185
|
+
path: null,
|
|
1186
|
+
status: 'skipped',
|
|
1187
|
+
content: '',
|
|
1188
|
+
planFingerprint: null,
|
|
1189
|
+
skipMessage: planned.refuseReason ?? mcpPlan?.skipReason,
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
else if (tool === 'cursor') {
|
|
1194
|
+
const mcpPath = join(opts.home, '.cursor', 'mcp.json');
|
|
1195
|
+
const existingMcp = readTextFile(mcpPath);
|
|
1196
|
+
const planned = planCursorMcpJson(mcpPath, existingMcp, opts.agentId, version, serverName);
|
|
1197
|
+
mcpPlan = planned.mcpPlan;
|
|
1198
|
+
refused = planned.refused;
|
|
1199
|
+
otherAismemoryNames = planned.otherNames;
|
|
1200
|
+
if (planned.refuseReason !== undefined) {
|
|
1201
|
+
mcpPlan = {
|
|
1202
|
+
transport: 'file',
|
|
1203
|
+
path: mcpPath,
|
|
1204
|
+
status: 'skipped',
|
|
1205
|
+
planFingerprint: fingerprintContent(existingMcp),
|
|
1206
|
+
ourServerEntry: null,
|
|
1207
|
+
skipReason: planned.refuseReason,
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
if (refused) {
|
|
1211
|
+
instructionPlan = {
|
|
1212
|
+
path: null,
|
|
1213
|
+
status: 'skipped',
|
|
1214
|
+
content: '',
|
|
1215
|
+
planFingerprint: null,
|
|
1216
|
+
skipMessage: planned.refuseReason ?? mcpPlan?.skipReason,
|
|
1217
|
+
};
|
|
1218
|
+
}
|
|
1219
|
+
else {
|
|
1220
|
+
const instructionPath = cursorInstructionPath(opts.project, opts.agentId);
|
|
1221
|
+
if (instructionPath === null) {
|
|
1222
|
+
instructionPlan = {
|
|
1223
|
+
path: null,
|
|
1224
|
+
status: 'skipped',
|
|
1225
|
+
content: '',
|
|
1226
|
+
planFingerprint: null,
|
|
1227
|
+
skipMessage: 'Cursor rules: run with --project <folder> to add them to a project',
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
else {
|
|
1231
|
+
const existingInstructions = readTextFile(instructionPath);
|
|
1232
|
+
const next = planInstructionContent(existingInstructions, opts.agentId, entryInstructions, accountRules, opts.setDate, existingInstructions === null);
|
|
1233
|
+
instructionPlan = {
|
|
1234
|
+
path: instructionPath,
|
|
1235
|
+
status: fileChangeStatus(instructionPath, next),
|
|
1236
|
+
content: next,
|
|
1237
|
+
planFingerprint: fingerprintContent(existingInstructions),
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
else {
|
|
1243
|
+
const mcpPath = join(opts.home, '.codex', 'config.toml');
|
|
1244
|
+
const existingMcp = readTextFile(mcpPath);
|
|
1245
|
+
const ourEntry = buildMcpServerEntry(opts.agentId, version);
|
|
1246
|
+
if (toolchain.codexMcpAdd) {
|
|
1247
|
+
const planned = await planCommandToolMcp('codex', opts.agentId, version, serverName, true, opts.commandRunner);
|
|
1248
|
+
mcpPlan = planned.mcpPlan;
|
|
1249
|
+
refused = planned.refused;
|
|
1250
|
+
if (planned.refuseReason !== undefined && mcpPlan === null) {
|
|
1251
|
+
mcpPlan = {
|
|
1252
|
+
transport: 'command',
|
|
1253
|
+
path: '(codex mcp add)',
|
|
1254
|
+
status: 'skipped',
|
|
1255
|
+
planFingerprint: null,
|
|
1256
|
+
ourServerEntry: null,
|
|
1257
|
+
skipReason: planned.refuseReason,
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
else {
|
|
1262
|
+
const merged = mergeCodexTomlMcp(existingMcp, opts.agentId, version, serverName, mcpPath);
|
|
1263
|
+
mcpPlan = {
|
|
1264
|
+
transport: 'file',
|
|
1265
|
+
path: mcpPath,
|
|
1266
|
+
status: fileChangeStatus(mcpPath, merged.content),
|
|
1267
|
+
content: merged.content,
|
|
1268
|
+
planFingerprint: fingerprintContent(existingMcp),
|
|
1269
|
+
ourServerEntry: ourEntry,
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
const instructionPath = codexInstructionPath(opts.home, opts.project);
|
|
1273
|
+
const existingInstructions = readTextFile(instructionPath);
|
|
1274
|
+
const next = planInstructionContent(existingInstructions, opts.agentId, entryInstructions, accountRules, opts.setDate, false);
|
|
1275
|
+
instructionPlan = {
|
|
1276
|
+
path: instructionPath,
|
|
1277
|
+
status: fileChangeStatus(instructionPath, next),
|
|
1278
|
+
content: next,
|
|
1279
|
+
planFingerprint: fingerprintContent(existingInstructions),
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
toolPlans.push({
|
|
1283
|
+
tool,
|
|
1284
|
+
found: true,
|
|
1285
|
+
mcpPlan,
|
|
1286
|
+
instructionPlan,
|
|
1287
|
+
ownNotes: tool === 'claude-code' ? ownNotes : [],
|
|
1288
|
+
refused,
|
|
1289
|
+
otherAismemoryNames,
|
|
1290
|
+
});
|
|
1291
|
+
}
|
|
1292
|
+
if (toolPlans.some((t) => t.found)) {
|
|
1293
|
+
for (const plan of toolPlans)
|
|
1294
|
+
plan.ownNotes = [];
|
|
1295
|
+
const first = toolPlans.find((t) => t.found);
|
|
1296
|
+
if (first !== undefined)
|
|
1297
|
+
first.ownNotes = ownNotes;
|
|
1298
|
+
}
|
|
1299
|
+
return {
|
|
1300
|
+
agentId: opts.agentId,
|
|
1301
|
+
tools: toolPlans,
|
|
1302
|
+
rulesOmitted,
|
|
1303
|
+
noAccountRules,
|
|
1304
|
+
claudeConnectionCheckNote,
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
export function otherAismemoryNotice(names) {
|
|
1308
|
+
return names.map((name) => `You also have a memory connection named ${name}. It was not made by setup and is left as it is.`);
|
|
1309
|
+
}
|
|
1310
|
+
export function plannedFileWrites(plan) {
|
|
1311
|
+
const paths = [];
|
|
1312
|
+
for (const tool of plan.tools) {
|
|
1313
|
+
if (!tool.found)
|
|
1314
|
+
continue;
|
|
1315
|
+
if (tool.mcpPlan?.transport === 'file' && tool.mcpPlan.content !== undefined
|
|
1316
|
+
&& tool.mcpPlan.status !== 'unchanged' && tool.mcpPlan.status !== 'skipped') {
|
|
1317
|
+
paths.push(tool.mcpPlan.path);
|
|
1318
|
+
}
|
|
1319
|
+
const instr = tool.instructionPlan;
|
|
1320
|
+
if (instr?.path !== null && instr?.path !== undefined
|
|
1321
|
+
&& instr.status !== 'unchanged' && instr.status !== 'skipped') {
|
|
1322
|
+
paths.push(instr.path);
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
return paths;
|
|
1326
|
+
}
|
|
1327
|
+
export function planHasRefusedTool(plan) {
|
|
1328
|
+
return plan.tools.some((t) => t.refused === true);
|
|
1329
|
+
}
|
|
1330
|
+
function formatOurMcpEntry(entry, serverName) {
|
|
1331
|
+
if (entry === null)
|
|
1332
|
+
return '';
|
|
1333
|
+
return JSON.stringify({ [serverName]: entry }, null, 2);
|
|
1334
|
+
}
|
|
1335
|
+
function instructionBlockForDryRun(content, agentId) {
|
|
1336
|
+
const blockId = readBlockIdFromFile(content, agentId);
|
|
1337
|
+
if (blockId === null)
|
|
1338
|
+
return content.trimEnd();
|
|
1339
|
+
const begin = setupBeginMarker(agentId, blockId);
|
|
1340
|
+
const end = setupEndMarker(agentId, blockId);
|
|
1341
|
+
const start = content.indexOf(begin);
|
|
1342
|
+
const endIdx = content.indexOf(end);
|
|
1343
|
+
if (start < 0 || endIdx < 0)
|
|
1344
|
+
return content.trimEnd();
|
|
1345
|
+
return content.slice(start, endIdx + end.length);
|
|
1346
|
+
}
|
|
1347
|
+
function homeTargetDryRunPath(path, home) {
|
|
1348
|
+
const resolved = resolve(path);
|
|
1349
|
+
const homeNorm = resolve(home);
|
|
1350
|
+
if (resolved !== homeNorm && !resolved.startsWith(`${homeNorm}/`)) {
|
|
1351
|
+
return resolved;
|
|
1352
|
+
}
|
|
1353
|
+
if (existsSync(resolved)) {
|
|
1354
|
+
try {
|
|
1355
|
+
const real = realpathSync(resolved);
|
|
1356
|
+
if (real !== resolved) {
|
|
1357
|
+
return `${resolved} -> ${real}`;
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
catch {
|
|
1361
|
+
// leave resolved
|
|
1362
|
+
}
|
|
1363
|
+
return resolved;
|
|
1364
|
+
}
|
|
1365
|
+
let suffix = basename(resolved);
|
|
1366
|
+
let parent = dirname(resolved);
|
|
1367
|
+
while (isPathUnderRoot(homeNorm, parent)) {
|
|
1368
|
+
try {
|
|
1369
|
+
if (lstatSync(parent).isSymbolicLink()) {
|
|
1370
|
+
return `${resolved} -> ${join(realpathSync(parent), suffix)}`;
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
catch {
|
|
1374
|
+
// keep walking
|
|
1375
|
+
}
|
|
1376
|
+
if (parent === homeNorm)
|
|
1377
|
+
break;
|
|
1378
|
+
suffix = join(basename(parent), suffix);
|
|
1379
|
+
parent = dirname(parent);
|
|
1380
|
+
}
|
|
1381
|
+
return resolved;
|
|
1382
|
+
}
|
|
1383
|
+
export function formatDryRun(plan, opts) {
|
|
1384
|
+
const serverName = setupMcpServerName(plan.agentId);
|
|
1385
|
+
const lines = [SETUP_NEW_WARNING, ''];
|
|
1386
|
+
if (plan.claudeConnectionCheckNote === true) {
|
|
1387
|
+
lines.push('Checking your Claude Code connection may take up to a minute.');
|
|
1388
|
+
lines.push('');
|
|
1389
|
+
}
|
|
1390
|
+
if ((plan.rulesOmitted ?? 0) > 0) {
|
|
1391
|
+
lines.push(`${plan.rulesOmitted} account rules were left out (limit is ${SETUP_MAX_ACCOUNT_RULES}).`);
|
|
1392
|
+
lines.push('');
|
|
1393
|
+
}
|
|
1394
|
+
for (const tool of plan.tools) {
|
|
1395
|
+
const label = tool.tool;
|
|
1396
|
+
if (!tool.found) {
|
|
1397
|
+
lines.push(`${label}: not found on this machine`);
|
|
1398
|
+
continue;
|
|
1399
|
+
}
|
|
1400
|
+
lines.push(`${label}:`);
|
|
1401
|
+
for (const note of otherAismemoryNotice(tool.otherAismemoryNames ?? [])) {
|
|
1402
|
+
lines.push(` ${note}`);
|
|
1403
|
+
}
|
|
1404
|
+
if (tool.mcpPlan !== null) {
|
|
1405
|
+
const mcp = tool.mcpPlan;
|
|
1406
|
+
// A settings file reached through a link: show where the write really lands. Command entries
|
|
1407
|
+
// ("(claude mcp add)") are not paths and are printed as they are.
|
|
1408
|
+
const mcpLabel = mcp.transport === 'file' && opts?.home !== undefined
|
|
1409
|
+
? homeTargetDryRunPath(mcp.path, opts.home)
|
|
1410
|
+
: mcp.path;
|
|
1411
|
+
lines.push(` ${mcpLabel} (${mcp.status})`);
|
|
1412
|
+
if (mcp.manualCommand !== undefined) {
|
|
1413
|
+
lines.push(` Run manually: ${mcp.manualCommand}`);
|
|
1414
|
+
}
|
|
1415
|
+
if (mcp.commandArgv !== undefined) {
|
|
1416
|
+
const bin = tool.tool === 'codex' ? 'codex' : 'claude';
|
|
1417
|
+
lines.push(` Would run: ${bin} ${mcp.commandArgv.join(' ')}`);
|
|
1418
|
+
}
|
|
1419
|
+
if (mcp.skipReason !== undefined)
|
|
1420
|
+
lines.push(` ${mcp.skipReason}`);
|
|
1421
|
+
if (mcp.ourServerEntry !== null) {
|
|
1422
|
+
lines.push(formatOurMcpEntry(mcp.ourServerEntry, serverName));
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
if (tool.instructionPlan !== null) {
|
|
1426
|
+
const instr = tool.instructionPlan;
|
|
1427
|
+
if (instr.skipMessage !== undefined) {
|
|
1428
|
+
lines.push(` ${instr.skipMessage}`);
|
|
1429
|
+
}
|
|
1430
|
+
else if (instr.path !== null) {
|
|
1431
|
+
const pathLabel = opts?.home !== undefined
|
|
1432
|
+
? homeTargetDryRunPath(instr.path, opts.home)
|
|
1433
|
+
: instr.path;
|
|
1434
|
+
lines.push(` ${pathLabel} (${instr.status})`);
|
|
1435
|
+
lines.push(instructionBlockForDryRun(instr.content, plan.agentId));
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
const notesSource = plan.tools.find((t) => t.ownNotes.length > 0);
|
|
1440
|
+
if (notesSource !== undefined && notesSource.ownNotes.length > 0) {
|
|
1441
|
+
lines.push('');
|
|
1442
|
+
lines.push('Notes your agent saved for itself; these stay in the service and load with the agent:');
|
|
1443
|
+
for (const note of notesSource.ownNotes)
|
|
1444
|
+
lines.push(` - ${sanitizeForTerminal(note)}`);
|
|
1445
|
+
}
|
|
1446
|
+
return `${lines.join('\n')}\n`;
|
|
1447
|
+
}
|
|
1448
|
+
const FILE_CHANGED_MSG = 'changed while you were deciding; run setup again';
|
|
1449
|
+
function assertFingerprint(path, planFingerprint) {
|
|
1450
|
+
if (planFingerprint === null)
|
|
1451
|
+
return;
|
|
1452
|
+
const now = fingerprintContent(readTextFile(path));
|
|
1453
|
+
if (now !== planFingerprint)
|
|
1454
|
+
throw new Error(`${path}: ${FILE_CHANGED_MSG}`);
|
|
1455
|
+
}
|
|
1456
|
+
function isEmptyJsonObject(text) {
|
|
1457
|
+
const trimmed = text.trim();
|
|
1458
|
+
if (trimmed === '{}' || trimmed === '')
|
|
1459
|
+
return true;
|
|
1460
|
+
try {
|
|
1461
|
+
const parsed = JSON.parse(text);
|
|
1462
|
+
return isJsonObject(parsed) && Object.keys(parsed).length === 0;
|
|
1463
|
+
}
|
|
1464
|
+
catch {
|
|
1465
|
+
return false;
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
export function writableRoots(home, project) {
|
|
1469
|
+
const roots = [resolve(home)];
|
|
1470
|
+
if (project !== undefined)
|
|
1471
|
+
roots.push(resolve(project));
|
|
1472
|
+
return roots;
|
|
1473
|
+
}
|
|
1474
|
+
export function assertPathWritable(roots, path, resolvedWriteTarget) {
|
|
1475
|
+
const normalized = resolve(path);
|
|
1476
|
+
const writeTarget = resolvedWriteTarget !== undefined ? resolve(resolvedWriteTarget) : normalized;
|
|
1477
|
+
const resolvedRoots = roots.map((r) => resolve(r));
|
|
1478
|
+
const root = resolvedRoots
|
|
1479
|
+
.filter((r) => normalized === r || normalized.startsWith(`${r}/`))
|
|
1480
|
+
.sort((a, b) => b.length - a.length)[0];
|
|
1481
|
+
if (root === undefined) {
|
|
1482
|
+
throw new Error(`refusing to write outside setup roots: ${normalized}`);
|
|
1483
|
+
}
|
|
1484
|
+
const inProject = matchedRootIsProject(roots, root);
|
|
1485
|
+
const linkMsg = inProject
|
|
1486
|
+
? refuseSymlinkInProject(root, normalized)
|
|
1487
|
+
: refuseSymlinkWrite(root, normalized);
|
|
1488
|
+
if (linkMsg !== null)
|
|
1489
|
+
throw new Error(linkMsg);
|
|
1490
|
+
const backup = `${writeTarget}.aismemory-backup`;
|
|
1491
|
+
const backupMsg = inProject
|
|
1492
|
+
? refuseSymlinkInProject(root, backup)
|
|
1493
|
+
: refuseSymlinkWrite(root, backup);
|
|
1494
|
+
if (backupMsg !== null)
|
|
1495
|
+
throw new Error(backupMsg);
|
|
1496
|
+
}
|
|
1497
|
+
function pathGuardMessage(roots, path) {
|
|
1498
|
+
try {
|
|
1499
|
+
assertPathWritable(roots, path);
|
|
1500
|
+
return null;
|
|
1501
|
+
}
|
|
1502
|
+
catch (err) {
|
|
1503
|
+
return err instanceof Error ? err.message : String(err);
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
function planTimeWriteTargets(tool, home, project, agentId) {
|
|
1507
|
+
const paths = [];
|
|
1508
|
+
if (tool === 'claude-code') {
|
|
1509
|
+
paths.push(claudeInstructionPath(home, project));
|
|
1510
|
+
}
|
|
1511
|
+
else if (tool === 'cursor') {
|
|
1512
|
+
paths.push(join(home, '.cursor', 'mcp.json'));
|
|
1513
|
+
const instr = cursorInstructionPath(project, agentId);
|
|
1514
|
+
if (instr !== null)
|
|
1515
|
+
paths.push(instr);
|
|
1516
|
+
}
|
|
1517
|
+
else {
|
|
1518
|
+
paths.push(join(home, '.codex', 'config.toml'));
|
|
1519
|
+
paths.push(codexInstructionPath(home, project));
|
|
1520
|
+
}
|
|
1521
|
+
return paths;
|
|
1522
|
+
}
|
|
1523
|
+
async function writePlannedFile(roots, path, content) {
|
|
1524
|
+
const writeTarget = existingRealPath(path);
|
|
1525
|
+
assertPathWritable(roots, path, writeTarget);
|
|
1526
|
+
await backupFileOnce(writeTarget);
|
|
1527
|
+
writeTextFileAtomic(path, content);
|
|
1528
|
+
}
|
|
1529
|
+
function writeTextToTemp(targetPath, content) {
|
|
1530
|
+
const normalized = resolve(targetPath);
|
|
1531
|
+
let mode;
|
|
1532
|
+
let target = normalized;
|
|
1533
|
+
if (existsSync(target)) {
|
|
1534
|
+
target = realpathSync(target);
|
|
1535
|
+
mode = lstatSync(target).mode & 0o777;
|
|
1536
|
+
}
|
|
1537
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
1538
|
+
const tmpPath = join(dirname(target), `.${basename(target)}.aismemory-${randomBytes(6).toString('hex')}.tmp`);
|
|
1539
|
+
writeFileSync(tmpPath, content, { encoding: 'utf-8', flag: 'wx', ...(mode !== undefined ? { mode } : {}) });
|
|
1540
|
+
if (mode !== undefined)
|
|
1541
|
+
chmodSync(tmpPath, mode);
|
|
1542
|
+
return tmpPath;
|
|
1543
|
+
}
|
|
1544
|
+
function commitTempRename(tmpPath, targetPath) {
|
|
1545
|
+
const normalized = resolve(targetPath);
|
|
1546
|
+
const target = existsSync(normalized) ? realpathSync(normalized) : normalized;
|
|
1547
|
+
renameSync(tmpPath, target);
|
|
1548
|
+
}
|
|
1549
|
+
export async function applySetupPlan(opts) {
|
|
1550
|
+
const stderr = opts.writeStderr ?? (() => undefined);
|
|
1551
|
+
const roots = writableRoots(opts.home, opts.project);
|
|
1552
|
+
let fileChangeFailed = false;
|
|
1553
|
+
for (const tool of opts.plan.tools) {
|
|
1554
|
+
if (!tool.found)
|
|
1555
|
+
continue;
|
|
1556
|
+
if (tool.refused === true)
|
|
1557
|
+
continue;
|
|
1558
|
+
if (tool.mcpPlan !== null) {
|
|
1559
|
+
const mcp = tool.mcpPlan;
|
|
1560
|
+
if (mcp.status !== 'unchanged' && mcp.status !== 'skipped') {
|
|
1561
|
+
if (mcp.transport === 'command' && mcp.commandArgv !== undefined) {
|
|
1562
|
+
const bin = tool.tool === 'codex' ? 'codex' : 'claude';
|
|
1563
|
+
if (opts.commandRunner === undefined) {
|
|
1564
|
+
throw new Error(`Cannot run ${bin} without a command runner.`);
|
|
1565
|
+
}
|
|
1566
|
+
const result = await opts.commandRunner(bin, mcp.commandArgv, MCP_GET_TIMEOUT_MS);
|
|
1567
|
+
if (result.code !== 0) {
|
|
1568
|
+
throw new Error(`${bin} exited ${result.code}: ${result.stderr.trim() || result.stdout.trim()}`);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
else if (mcp.transport === 'file' && mcp.content !== undefined) {
|
|
1572
|
+
try {
|
|
1573
|
+
assertFingerprint(mcp.path, mcp.planFingerprint);
|
|
1574
|
+
await writePlannedFile(roots, mcp.path, mcp.content);
|
|
1575
|
+
}
|
|
1576
|
+
catch (err) {
|
|
1577
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1578
|
+
if (msg.includes('refusing to write')) {
|
|
1579
|
+
fileChangeFailed = true;
|
|
1580
|
+
stderr(`${tool.tool}: ${msg}\n`);
|
|
1581
|
+
}
|
|
1582
|
+
else {
|
|
1583
|
+
fileChangeFailed = true;
|
|
1584
|
+
stderr(`${msg}\n`);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
if (tool.instructionPlan !== null && tool.instructionPlan.path !== null) {
|
|
1591
|
+
const instr = tool.instructionPlan;
|
|
1592
|
+
const instrPath = instr.path;
|
|
1593
|
+
if (instrPath === null || instr.status === 'unchanged' || instr.status === 'skipped')
|
|
1594
|
+
continue;
|
|
1595
|
+
try {
|
|
1596
|
+
assertFingerprint(instrPath, instr.planFingerprint);
|
|
1597
|
+
await writePlannedFile(roots, instrPath, instr.content);
|
|
1598
|
+
}
|
|
1599
|
+
catch (err) {
|
|
1600
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1601
|
+
if (msg.includes('refusing to write')) {
|
|
1602
|
+
fileChangeFailed = true;
|
|
1603
|
+
stderr(`${tool.tool}: ${msg}\n`);
|
|
1604
|
+
continue;
|
|
1605
|
+
}
|
|
1606
|
+
fileChangeFailed = true;
|
|
1607
|
+
stderr(`${msg}\n`);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
if (fileChangeFailed)
|
|
1612
|
+
return;
|
|
1613
|
+
}
|
|
1614
|
+
function instructionBlockRemoveError(content, agentId, path) {
|
|
1615
|
+
const lines = content.split('\n');
|
|
1616
|
+
const beginIdx = lines.findIndex((line) => {
|
|
1617
|
+
const match = MARKER_BEGIN.exec(line.trim());
|
|
1618
|
+
return match?.[1] === agentId;
|
|
1619
|
+
});
|
|
1620
|
+
if (beginIdx === -1)
|
|
1621
|
+
return null;
|
|
1622
|
+
const beginMatch = MARKER_BEGIN.exec(lines[beginIdx]?.trim() ?? '');
|
|
1623
|
+
const beginId = beginMatch?.[2] ?? '';
|
|
1624
|
+
let endIdx = -1;
|
|
1625
|
+
for (let i = beginIdx + 1; i < lines.length; i += 1) {
|
|
1626
|
+
const endMatch = MARKER_END.exec(lines[i]?.trim() ?? '');
|
|
1627
|
+
if (endMatch?.[1] === agentId && (endMatch[2] ?? '') === beginId) {
|
|
1628
|
+
endIdx = i;
|
|
1629
|
+
break;
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
if (endIdx === -1)
|
|
1633
|
+
return `the block in ${path} is damaged; remove it by hand`;
|
|
1634
|
+
return null;
|
|
1635
|
+
}
|
|
1636
|
+
async function verifyCommandMcpOwned(bin, serverName, agentId, runner) {
|
|
1637
|
+
if (runner === undefined)
|
|
1638
|
+
return null;
|
|
1639
|
+
const getArgv = bin === 'claude' ? claudeMcpGetArgv(serverName) : codexMcpGetArgv(serverName);
|
|
1640
|
+
const got = await runner(bin, getArgv, MCP_GET_TIMEOUT_MS);
|
|
1641
|
+
const presence = classifyMcpGetResult(got, serverName);
|
|
1642
|
+
if (presence === 'absent')
|
|
1643
|
+
return null;
|
|
1644
|
+
if (presence === 'unknown') {
|
|
1645
|
+
return `Refusing remove: run ${bin} ${getArgv.join(' ')} to verify ${serverName}.`;
|
|
1646
|
+
}
|
|
1647
|
+
const owner = agentIdFromMcpGetOutput(`${got.stdout}\n${got.stderr}`);
|
|
1648
|
+
if (owner === null) {
|
|
1649
|
+
return `Refusing remove: run ${bin} ${getArgv.join(' ')} to verify ${serverName}.`;
|
|
1650
|
+
}
|
|
1651
|
+
if (owner !== agentId) {
|
|
1652
|
+
return `Refusing remove: ${serverName} belongs to agent ${owner}, not ${agentId}.`;
|
|
1653
|
+
}
|
|
1654
|
+
return null;
|
|
1655
|
+
}
|
|
1656
|
+
function verifyCursorMcpOwned(mcpPath, raw, serverName, agentId) {
|
|
1657
|
+
if (raw === null || !jsonHasMcpServer(raw, serverName))
|
|
1658
|
+
return null;
|
|
1659
|
+
const parsed = parseJsonFile(mcpPath, raw);
|
|
1660
|
+
const servers = parsed['mcpServers'];
|
|
1661
|
+
if (!isJsonObject(servers))
|
|
1662
|
+
return null;
|
|
1663
|
+
const entry = servers[serverName];
|
|
1664
|
+
if (!isJsonObject(entry))
|
|
1665
|
+
return `Refusing remove: ${serverName} is not a valid MCP entry.`;
|
|
1666
|
+
const owner = mcpEntryAgentId(entry);
|
|
1667
|
+
if (owner !== agentId) {
|
|
1668
|
+
return `Refusing remove: ${serverName} belongs to agent ${owner ?? '(unknown)'}, not ${agentId}.`;
|
|
1669
|
+
}
|
|
1670
|
+
return null;
|
|
1671
|
+
}
|
|
1672
|
+
function codexHasOurMarkedBlock(raw, agentId) {
|
|
1673
|
+
if (raw === null)
|
|
1674
|
+
return false;
|
|
1675
|
+
return raw.split('\n').some((line) => {
|
|
1676
|
+
const m = TOML_MARKER_BEGIN.exec(line.trim());
|
|
1677
|
+
return m?.[1] === agentId;
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
/** Plans removal using only local files (no network, no full_context). */
|
|
1681
|
+
export async function planRemoveSetup(opts) {
|
|
1682
|
+
const tools = ['claude-code', 'cursor', 'codex'];
|
|
1683
|
+
const toolchain = opts.toolchain ?? { claudeOnPath: false, codexMcpAdd: false };
|
|
1684
|
+
const serverName = setupMcpServerName(opts.agentId);
|
|
1685
|
+
const toolPlans = [];
|
|
1686
|
+
for (const tool of tools) {
|
|
1687
|
+
const found = detectSetupTool(opts.home, tool);
|
|
1688
|
+
if (!found) {
|
|
1689
|
+
toolPlans.push({ tool, found: false, mcpPlan: null, instructionPlan: null, ownNotes: [] });
|
|
1690
|
+
continue;
|
|
1691
|
+
}
|
|
1692
|
+
let mcpPlan = null;
|
|
1693
|
+
let instructionPlan = null;
|
|
1694
|
+
let refused = false;
|
|
1695
|
+
let refuseReason;
|
|
1696
|
+
if (tool === 'claude-code') {
|
|
1697
|
+
let claudeRemovePlanned = false;
|
|
1698
|
+
if (toolchain.claudeOnPath && opts.commandRunner !== undefined) {
|
|
1699
|
+
const getArgv = claudeMcpGetArgv(serverName);
|
|
1700
|
+
const got = await opts.commandRunner('claude', getArgv, MCP_GET_TIMEOUT_MS);
|
|
1701
|
+
const presence = classifyMcpGetResult(got, serverName);
|
|
1702
|
+
if (presence === 'absent') {
|
|
1703
|
+
claudeRemovePlanned = false;
|
|
1704
|
+
}
|
|
1705
|
+
else if (presence === 'unknown') {
|
|
1706
|
+
refused = true;
|
|
1707
|
+
refuseReason = `Refusing remove: run claude ${getArgv.join(' ')} to verify ${serverName}.`;
|
|
1708
|
+
}
|
|
1709
|
+
else {
|
|
1710
|
+
const owner = agentIdFromMcpGetOutput(`${got.stdout}\n${got.stderr}`);
|
|
1711
|
+
if (owner === null) {
|
|
1712
|
+
refused = true;
|
|
1713
|
+
refuseReason = `Refusing remove: run claude ${getArgv.join(' ')} to verify ${serverName}.`;
|
|
1714
|
+
}
|
|
1715
|
+
else if (owner !== opts.agentId) {
|
|
1716
|
+
refused = true;
|
|
1717
|
+
refuseReason = `Refusing remove: ${serverName} belongs to agent ${owner}, not ${opts.agentId}.`;
|
|
1718
|
+
}
|
|
1719
|
+
else {
|
|
1720
|
+
claudeRemovePlanned = true;
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
else if (toolchain.claudeOnPath) {
|
|
1725
|
+
claudeRemovePlanned = true;
|
|
1726
|
+
}
|
|
1727
|
+
mcpPlan = toolchain.claudeOnPath
|
|
1728
|
+
? {
|
|
1729
|
+
transport: 'command',
|
|
1730
|
+
path: '(claude mcp remove)',
|
|
1731
|
+
status: claudeRemovePlanned ? 'changed' : 'skipped',
|
|
1732
|
+
planFingerprint: null,
|
|
1733
|
+
ourServerEntry: null,
|
|
1734
|
+
commandArgv: claudeRemovePlanned ? claudeMcpRemoveArgv(serverName) : undefined,
|
|
1735
|
+
skipReason: refuseReason,
|
|
1736
|
+
}
|
|
1737
|
+
: {
|
|
1738
|
+
transport: 'command',
|
|
1739
|
+
path: '(claude mcp remove)',
|
|
1740
|
+
status: 'changed',
|
|
1741
|
+
planFingerprint: null,
|
|
1742
|
+
ourServerEntry: null,
|
|
1743
|
+
manualCommand: manualClaudeMcpRemoveCommand(serverName),
|
|
1744
|
+
};
|
|
1745
|
+
const instructionPath = claudeInstructionPath(opts.home, opts.project);
|
|
1746
|
+
const rawInstr = readTextFile(instructionPath);
|
|
1747
|
+
const blockErr = rawInstr !== null
|
|
1748
|
+
? instructionBlockRemoveError(rawInstr, opts.agentId, instructionPath)
|
|
1749
|
+
: null;
|
|
1750
|
+
if (blockErr !== null) {
|
|
1751
|
+
refused = true;
|
|
1752
|
+
refuseReason = blockErr;
|
|
1753
|
+
}
|
|
1754
|
+
instructionPlan = {
|
|
1755
|
+
path: instructionPath,
|
|
1756
|
+
status: rawInstr !== null && readBlockIdFromFile(rawInstr, opts.agentId) !== null && blockErr === null
|
|
1757
|
+
? 'changed'
|
|
1758
|
+
: 'skipped',
|
|
1759
|
+
content: rawInstr ?? '',
|
|
1760
|
+
planFingerprint: fingerprintContent(rawInstr),
|
|
1761
|
+
skipMessage: blockErr ?? undefined,
|
|
1762
|
+
};
|
|
1763
|
+
}
|
|
1764
|
+
else if (tool === 'cursor') {
|
|
1765
|
+
const mcpPath = join(opts.home, '.cursor', 'mcp.json');
|
|
1766
|
+
const raw = readTextFile(mcpPath);
|
|
1767
|
+
const verifyErr = verifyCursorMcpOwned(mcpPath, raw, serverName, opts.agentId);
|
|
1768
|
+
if (verifyErr !== null) {
|
|
1769
|
+
refused = true;
|
|
1770
|
+
refuseReason = verifyErr;
|
|
1771
|
+
}
|
|
1772
|
+
const hasOurs = raw !== null && jsonHasMcpServer(raw, serverName) && verifyErr === null;
|
|
1773
|
+
mcpPlan = {
|
|
1774
|
+
transport: 'file',
|
|
1775
|
+
path: mcpPath,
|
|
1776
|
+
status: hasOurs ? 'changed' : 'skipped',
|
|
1777
|
+
content: raw ?? '',
|
|
1778
|
+
planFingerprint: fingerprintContent(raw),
|
|
1779
|
+
ourServerEntry: null,
|
|
1780
|
+
skipReason: refuseReason,
|
|
1781
|
+
};
|
|
1782
|
+
const instructionPath = cursorInstructionPath(opts.project, opts.agentId);
|
|
1783
|
+
if (instructionPath === null) {
|
|
1784
|
+
instructionPlan = {
|
|
1785
|
+
path: null,
|
|
1786
|
+
status: 'skipped',
|
|
1787
|
+
content: '',
|
|
1788
|
+
planFingerprint: null,
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
else {
|
|
1792
|
+
const rawInstr = readTextFile(instructionPath);
|
|
1793
|
+
const blockErr = rawInstr !== null
|
|
1794
|
+
? instructionBlockRemoveError(rawInstr, opts.agentId, instructionPath)
|
|
1795
|
+
: null;
|
|
1796
|
+
if (blockErr !== null) {
|
|
1797
|
+
refused = true;
|
|
1798
|
+
refuseReason = blockErr;
|
|
1799
|
+
}
|
|
1800
|
+
instructionPlan = {
|
|
1801
|
+
path: instructionPath,
|
|
1802
|
+
status: rawInstr !== null && readBlockIdFromFile(rawInstr, opts.agentId) !== null && blockErr === null
|
|
1803
|
+
? 'changed'
|
|
1804
|
+
: 'skipped',
|
|
1805
|
+
content: rawInstr ?? '',
|
|
1806
|
+
planFingerprint: fingerprintContent(rawInstr),
|
|
1807
|
+
skipMessage: blockErr ?? undefined,
|
|
1808
|
+
};
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
else {
|
|
1812
|
+
const mcpPath = join(opts.home, '.codex', 'config.toml');
|
|
1813
|
+
const raw = readTextFile(mcpPath);
|
|
1814
|
+
if (toolchain.codexMcpAdd) {
|
|
1815
|
+
const verifyErr = await verifyCommandMcpOwned('codex', serverName, opts.agentId, opts.commandRunner);
|
|
1816
|
+
if (verifyErr !== null) {
|
|
1817
|
+
refused = true;
|
|
1818
|
+
refuseReason = verifyErr;
|
|
1819
|
+
}
|
|
1820
|
+
mcpPlan = {
|
|
1821
|
+
transport: 'command',
|
|
1822
|
+
path: '(codex mcp remove)',
|
|
1823
|
+
status: verifyErr === null ? 'changed' : 'skipped',
|
|
1824
|
+
planFingerprint: null,
|
|
1825
|
+
ourServerEntry: null,
|
|
1826
|
+
commandArgv: verifyErr === null ? codexMcpRemoveArgv(serverName) : undefined,
|
|
1827
|
+
skipReason: refuseReason,
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
else {
|
|
1831
|
+
const hasBlock = codexHasOurMarkedBlock(raw, opts.agentId);
|
|
1832
|
+
let blockErr;
|
|
1833
|
+
if (raw !== null && hasBlock) {
|
|
1834
|
+
if (damagedTomlMarker(raw, opts.agentId)) {
|
|
1835
|
+
blockErr = `the block in ${mcpPath} is damaged; remove it by hand`;
|
|
1836
|
+
}
|
|
1837
|
+
else {
|
|
1838
|
+
try {
|
|
1839
|
+
removeCodexTomlMcpEntry(raw, opts.agentId, mcpPath);
|
|
1840
|
+
}
|
|
1841
|
+
catch (err) {
|
|
1842
|
+
blockErr = err instanceof Error ? err.message : String(err);
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
}
|
|
1846
|
+
if (blockErr !== undefined) {
|
|
1847
|
+
refused = true;
|
|
1848
|
+
refuseReason = blockErr;
|
|
1849
|
+
}
|
|
1850
|
+
mcpPlan = {
|
|
1851
|
+
transport: 'file',
|
|
1852
|
+
path: mcpPath,
|
|
1853
|
+
status: hasBlock && blockErr === undefined ? 'changed' : 'skipped',
|
|
1854
|
+
content: raw ?? '',
|
|
1855
|
+
planFingerprint: fingerprintContent(raw),
|
|
1856
|
+
ourServerEntry: null,
|
|
1857
|
+
skipReason: refuseReason,
|
|
1858
|
+
};
|
|
1859
|
+
}
|
|
1860
|
+
const instructionPath = codexInstructionPath(opts.home, opts.project);
|
|
1861
|
+
const rawInstr = readTextFile(instructionPath);
|
|
1862
|
+
const blockErr = rawInstr !== null
|
|
1863
|
+
? instructionBlockRemoveError(rawInstr, opts.agentId, instructionPath)
|
|
1864
|
+
: null;
|
|
1865
|
+
if (blockErr !== null) {
|
|
1866
|
+
refused = true;
|
|
1867
|
+
refuseReason = blockErr;
|
|
1868
|
+
}
|
|
1869
|
+
instructionPlan = {
|
|
1870
|
+
path: instructionPath,
|
|
1871
|
+
status: rawInstr !== null && readBlockIdFromFile(rawInstr, opts.agentId) !== null && blockErr === null
|
|
1872
|
+
? 'changed'
|
|
1873
|
+
: 'skipped',
|
|
1874
|
+
content: rawInstr ?? '',
|
|
1875
|
+
planFingerprint: fingerprintContent(rawInstr),
|
|
1876
|
+
skipMessage: blockErr ?? undefined,
|
|
1877
|
+
};
|
|
1878
|
+
}
|
|
1879
|
+
toolPlans.push({
|
|
1880
|
+
tool,
|
|
1881
|
+
found: true,
|
|
1882
|
+
mcpPlan,
|
|
1883
|
+
instructionPlan,
|
|
1884
|
+
ownNotes: [],
|
|
1885
|
+
refused,
|
|
1886
|
+
});
|
|
1887
|
+
}
|
|
1888
|
+
return { agentId: opts.agentId, tools: toolPlans };
|
|
1889
|
+
}
|
|
1890
|
+
export function collectRemoveValidationFailures(plan, roots) {
|
|
1891
|
+
const failures = [];
|
|
1892
|
+
for (const tool of plan.tools) {
|
|
1893
|
+
if (!tool.found)
|
|
1894
|
+
continue;
|
|
1895
|
+
if (tool.refused === true) {
|
|
1896
|
+
const msg = tool.mcpPlan?.skipReason ?? tool.instructionPlan?.skipMessage;
|
|
1897
|
+
if (msg !== undefined)
|
|
1898
|
+
failures.push({ tool: tool.tool, message: msg });
|
|
1899
|
+
continue;
|
|
1900
|
+
}
|
|
1901
|
+
if (tool.mcpPlan?.transport === 'file' && tool.mcpPlan.status === 'changed') {
|
|
1902
|
+
const path = tool.mcpPlan.path;
|
|
1903
|
+
const outsideMsg = pathGuardMessage(roots, path);
|
|
1904
|
+
if (outsideMsg !== null) {
|
|
1905
|
+
failures.push({ tool: tool.tool, message: outsideMsg });
|
|
1906
|
+
continue;
|
|
1907
|
+
}
|
|
1908
|
+
const linkMsg = roots.map((r) => refuseSymlinkWrite(r, path)).find((m) => m !== null);
|
|
1909
|
+
if (linkMsg !== undefined && linkMsg !== null) {
|
|
1910
|
+
failures.push({ tool: tool.tool, message: linkMsg });
|
|
1911
|
+
continue;
|
|
1912
|
+
}
|
|
1913
|
+
if (existsSync(path)) {
|
|
1914
|
+
const raw = readFileSync(path, 'utf8');
|
|
1915
|
+
if (tool.mcpPlan.planFingerprint !== null && fingerprintContent(raw) !== tool.mcpPlan.planFingerprint) {
|
|
1916
|
+
failures.push({ tool: tool.tool, message: `${path}: ${FILE_CHANGED_MSG}` });
|
|
1917
|
+
continue;
|
|
1918
|
+
}
|
|
1919
|
+
if (tool.tool === 'codex') {
|
|
1920
|
+
try {
|
|
1921
|
+
removeCodexTomlMcpEntry(raw, plan.agentId, path);
|
|
1922
|
+
}
|
|
1923
|
+
catch (err) {
|
|
1924
|
+
failures.push({ tool: tool.tool, message: err instanceof Error ? err.message : String(err) });
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
const instr = tool.instructionPlan;
|
|
1930
|
+
if (instr?.path !== null && instr?.path !== undefined && instr.status === 'changed') {
|
|
1931
|
+
const outsideMsg = pathGuardMessage(roots, instr.path ?? '');
|
|
1932
|
+
if (outsideMsg !== null) {
|
|
1933
|
+
failures.push({ tool: tool.tool, message: outsideMsg });
|
|
1934
|
+
continue;
|
|
1935
|
+
}
|
|
1936
|
+
const linkMsg = roots.map((r) => refuseSymlinkWrite(r, instr.path ?? '')).find((m) => m !== null);
|
|
1937
|
+
if (linkMsg !== undefined && linkMsg !== null) {
|
|
1938
|
+
failures.push({ tool: tool.tool, message: linkMsg });
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
if (existsSync(instr.path)) {
|
|
1942
|
+
const raw = readFileSync(instr.path, 'utf8');
|
|
1943
|
+
const blockErr = instructionBlockRemoveError(raw, plan.agentId, instr.path);
|
|
1944
|
+
if (blockErr !== null) {
|
|
1945
|
+
failures.push({ tool: tool.tool, message: blockErr });
|
|
1946
|
+
continue;
|
|
1947
|
+
}
|
|
1948
|
+
if (instr.planFingerprint !== null && fingerprintContent(raw) !== instr.planFingerprint) {
|
|
1949
|
+
failures.push({ tool: tool.tool, message: `${instr.path}: ${FILE_CHANGED_MSG}` });
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
return failures;
|
|
1955
|
+
}
|
|
1956
|
+
export async function applyRemoveSetupPlan(opts) {
|
|
1957
|
+
const requireBlockId = opts.requireBlockId !== false;
|
|
1958
|
+
const dry = opts.dryRun === true;
|
|
1959
|
+
const serverName = setupMcpServerName(opts.plan.agentId);
|
|
1960
|
+
const roots = writableRoots(opts.home, opts.project);
|
|
1961
|
+
const failures = collectRemoveValidationFailures(opts.plan, roots);
|
|
1962
|
+
if (dry)
|
|
1963
|
+
return;
|
|
1964
|
+
const failedTools = new Set(failures.map((f) => f.tool));
|
|
1965
|
+
const fileOps = [];
|
|
1966
|
+
const commandOps = [];
|
|
1967
|
+
const pendingTemps = [];
|
|
1968
|
+
try {
|
|
1969
|
+
for (const tool of opts.plan.tools) {
|
|
1970
|
+
if (!tool.found)
|
|
1971
|
+
continue;
|
|
1972
|
+
if (failedTools.has(tool.tool))
|
|
1973
|
+
continue;
|
|
1974
|
+
if (tool.mcpPlan !== null && tool.mcpPlan.status === 'changed' && tool.mcpPlan.transport === 'file') {
|
|
1975
|
+
const mcp = tool.mcpPlan;
|
|
1976
|
+
if (!existsSync(mcp.path))
|
|
1977
|
+
continue;
|
|
1978
|
+
const raw = readFileSync(mcp.path, 'utf8');
|
|
1979
|
+
// The first apply backs up a file that already existed; no backup means setup created the file.
|
|
1980
|
+
// Only a file setup created may be deleted on remove, and a person's own empty "mcpServers" stays.
|
|
1981
|
+
const existedBeforeSetup = existsSync(`${existingRealPath(mcp.path)}.aismemory-backup`);
|
|
1982
|
+
const next = tool.tool === 'codex'
|
|
1983
|
+
? removeCodexTomlMcpEntry(raw, opts.plan.agentId, mcp.path)
|
|
1984
|
+
: removeJsonMcpEntry(raw, serverName, mcp.path, existedBeforeSetup);
|
|
1985
|
+
if (next === raw)
|
|
1986
|
+
continue;
|
|
1987
|
+
assertPathWritable(roots, mcp.path, existingRealPath(mcp.path));
|
|
1988
|
+
await backupFileOnce(existingRealPath(mcp.path));
|
|
1989
|
+
if (!existedBeforeSetup && (next.length === 0 || (mcp.path.endsWith('.json') && isEmptyJsonObject(next)))) {
|
|
1990
|
+
fileOps.push({ path: mcp.path, deleteFile: true });
|
|
1991
|
+
}
|
|
1992
|
+
else {
|
|
1993
|
+
const tmpPath = writeTextToTemp(mcp.path, next);
|
|
1994
|
+
pendingTemps.push(tmpPath);
|
|
1995
|
+
fileOps.push({ path: mcp.path, tmpPath });
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
if (tool.instructionPlan !== null && tool.instructionPlan.path !== null
|
|
1999
|
+
&& tool.instructionPlan.status === 'changed') {
|
|
2000
|
+
const path = tool.instructionPlan.path;
|
|
2001
|
+
if (!existsSync(path))
|
|
2002
|
+
continue;
|
|
2003
|
+
const raw = readFileSync(path, 'utf8');
|
|
2004
|
+
const next = removeInstructionBlock(raw, opts.plan.agentId, requireBlockId);
|
|
2005
|
+
const deleteFile = tool.tool === 'cursor'
|
|
2006
|
+
&& cursorFileCreatedBySetup(raw)
|
|
2007
|
+
&& contentIsOnlySetupCursorShell(next, opts.plan.agentId);
|
|
2008
|
+
if (deleteFile) {
|
|
2009
|
+
assertPathWritable(roots, path);
|
|
2010
|
+
fileOps.push({ path, deleteFile: true });
|
|
2011
|
+
}
|
|
2012
|
+
else if (next !== raw) {
|
|
2013
|
+
assertPathWritable(roots, path, existingRealPath(path));
|
|
2014
|
+
await backupFileOnce(existingRealPath(path));
|
|
2015
|
+
if (next.length === 0) {
|
|
2016
|
+
fileOps.push({ path, deleteFile: true });
|
|
2017
|
+
}
|
|
2018
|
+
else {
|
|
2019
|
+
const tmpPath = writeTextToTemp(path, next);
|
|
2020
|
+
pendingTemps.push(tmpPath);
|
|
2021
|
+
fileOps.push({ path, tmpPath });
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
if (tool.mcpPlan !== null && tool.mcpPlan.status === 'changed' && tool.mcpPlan.transport === 'command') {
|
|
2026
|
+
const mcp = tool.mcpPlan;
|
|
2027
|
+
if (mcp.commandArgv !== undefined && opts.commandRunner !== undefined) {
|
|
2028
|
+
const bin = tool.tool === 'codex' ? 'codex' : 'claude';
|
|
2029
|
+
commandOps.push({ tool: tool.tool, bin, argv: mcp.commandArgv });
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
const changedFiles = [];
|
|
2034
|
+
const pendingRenames = [];
|
|
2035
|
+
for (const op of fileOps) {
|
|
2036
|
+
if (op.deleteFile === true) {
|
|
2037
|
+
if (existsSync(op.path) && !lstatSync(op.path).isSymbolicLink()) {
|
|
2038
|
+
unlinkSync(op.path);
|
|
2039
|
+
}
|
|
2040
|
+
changedFiles.push(op.path);
|
|
2041
|
+
continue;
|
|
2042
|
+
}
|
|
2043
|
+
if (op.tmpPath !== undefined) {
|
|
2044
|
+
pendingRenames.push({ path: op.path, tmpPath: op.tmpPath });
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
for (const pending of pendingRenames) {
|
|
2048
|
+
commitTempRename(pending.tmpPath, pending.path);
|
|
2049
|
+
const idx = pendingTemps.indexOf(pending.tmpPath);
|
|
2050
|
+
if (idx >= 0)
|
|
2051
|
+
pendingTemps.splice(idx, 1);
|
|
2052
|
+
changedFiles.push(pending.path);
|
|
2053
|
+
}
|
|
2054
|
+
for (const cmd of commandOps) {
|
|
2055
|
+
if (opts.commandRunner === undefined) {
|
|
2056
|
+
throw new Error(`Cannot run ${cmd.bin} without a command runner.`);
|
|
2057
|
+
}
|
|
2058
|
+
const result = await opts.commandRunner(cmd.bin, cmd.argv, MCP_GET_TIMEOUT_MS);
|
|
2059
|
+
if (result.code !== 0) {
|
|
2060
|
+
const manual = `${cmd.bin} ${cmd.argv.join(' ')}`;
|
|
2061
|
+
throw new Error(`Files changed: ${changedFiles.join(', ')}. ${manual} failed (exit ${result.code}). Finish by hand: ${manual}`);
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
}
|
|
2065
|
+
finally {
|
|
2066
|
+
for (const tmp of pendingTemps) {
|
|
2067
|
+
try {
|
|
2068
|
+
if (existsSync(tmp))
|
|
2069
|
+
unlinkSync(tmp);
|
|
2070
|
+
}
|
|
2071
|
+
catch {
|
|
2072
|
+
// best-effort cleanup
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
if (failures.length > 0) {
|
|
2077
|
+
const msg = failures.map((f) => `${f.tool}: ${f.message}`).join('\n');
|
|
2078
|
+
throw new Error(msg);
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
async function mcpEntryPresentOnDisk(tool, home, agentId, runner) {
|
|
2082
|
+
const serverName = setupMcpServerName(agentId);
|
|
2083
|
+
if (tool === 'cursor') {
|
|
2084
|
+
const mcpPath = join(home, '.cursor', 'mcp.json');
|
|
2085
|
+
const raw = readTextFile(mcpPath);
|
|
2086
|
+
if (!jsonHasMcpServer(raw, serverName))
|
|
2087
|
+
return false;
|
|
2088
|
+
const parsed = parseJsonFile(mcpPath, raw ?? '{}');
|
|
2089
|
+
const servers = parsed['mcpServers'];
|
|
2090
|
+
if (!isJsonObject(servers))
|
|
2091
|
+
return false;
|
|
2092
|
+
const entry = servers[serverName];
|
|
2093
|
+
if (!isJsonObject(entry))
|
|
2094
|
+
return false;
|
|
2095
|
+
return mcpEntryAgentId(entry) === agentId;
|
|
2096
|
+
}
|
|
2097
|
+
if (tool === 'codex') {
|
|
2098
|
+
const mcpPath = join(home, '.codex', 'config.toml');
|
|
2099
|
+
const raw = readTextFile(mcpPath);
|
|
2100
|
+
if (codexHasOurMarkedBlock(raw, agentId))
|
|
2101
|
+
return true;
|
|
2102
|
+
// No marked block: setup added the connection with `codex mcp add`, and Codex wrote its own plain
|
|
2103
|
+
// table with no marker. Ask Codex below, as for Claude Code, or a finished setup reads as incomplete.
|
|
2104
|
+
}
|
|
2105
|
+
if (runner !== undefined) {
|
|
2106
|
+
const bin = tool === 'claude-code' ? 'claude' : 'codex';
|
|
2107
|
+
const getArgv = bin === 'claude' ? claudeMcpGetArgv(serverName) : codexMcpGetArgv(serverName);
|
|
2108
|
+
const got = await runner(bin, getArgv, MCP_GET_TIMEOUT_MS);
|
|
2109
|
+
const presence = classifyMcpGetResult(got, serverName);
|
|
2110
|
+
if (presence !== 'present')
|
|
2111
|
+
return false;
|
|
2112
|
+
return agentIdFromMcpGetOutput(`${got.stdout}\n${got.stderr}`) === agentId;
|
|
2113
|
+
}
|
|
2114
|
+
return false;
|
|
2115
|
+
}
|
|
2116
|
+
export async function summarizeSetupOrientation(home, plan, runner) {
|
|
2117
|
+
const lines = [];
|
|
2118
|
+
for (const tool of plan.tools) {
|
|
2119
|
+
const name = tool.tool;
|
|
2120
|
+
if (!tool.found) {
|
|
2121
|
+
lines.push({ label: name, status: 'not-installed' });
|
|
2122
|
+
continue;
|
|
2123
|
+
}
|
|
2124
|
+
const mcpOk = await mcpEntryPresentOnDisk(tool.tool, home, plan.agentId, runner);
|
|
2125
|
+
const blockPresent = tool.instructionPlan !== null &&
|
|
2126
|
+
tool.instructionPlan.path !== null &&
|
|
2127
|
+
existsSync(tool.instructionPlan.path) &&
|
|
2128
|
+
readBlockIdFromFile(readTextFile(tool.instructionPlan.path) ?? '', plan.agentId) !== null;
|
|
2129
|
+
if (mcpOk && blockPresent)
|
|
2130
|
+
lines.push({ label: name, status: 'present' });
|
|
2131
|
+
else
|
|
2132
|
+
lines.push({ label: name, status: 'missing' });
|
|
2133
|
+
}
|
|
2134
|
+
return lines;
|
|
2135
|
+
}
|
|
2136
|
+
export function formatOrientationSummary(lines) {
|
|
2137
|
+
const out = ['Orientation after setup:'];
|
|
2138
|
+
for (const line of lines) {
|
|
2139
|
+
if (line.status === 'not-installed') {
|
|
2140
|
+
out.push(` ${line.label}: not installed on this machine`);
|
|
2141
|
+
}
|
|
2142
|
+
else if (line.status === 'present') {
|
|
2143
|
+
out.push(` ${line.label}: setup present`);
|
|
2144
|
+
}
|
|
2145
|
+
else {
|
|
2146
|
+
out.push(` ${line.label}: setup incomplete`);
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
return `${out.join('\n')}\n`;
|
|
2150
|
+
}
|
|
2151
|
+
export function plannedPaths(plan) {
|
|
2152
|
+
const paths = [];
|
|
2153
|
+
for (const tool of plan.tools) {
|
|
2154
|
+
if (!tool.found)
|
|
2155
|
+
continue;
|
|
2156
|
+
if (tool.mcpPlan !== null && tool.mcpPlan.transport === 'file')
|
|
2157
|
+
paths.push(tool.mcpPlan.path);
|
|
2158
|
+
if (tool.instructionPlan?.path !== null && tool.instructionPlan?.path !== undefined) {
|
|
2159
|
+
paths.push(tool.instructionPlan.path);
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
return paths;
|
|
2163
|
+
}
|
|
2164
|
+
export function fingerprintFileAtPath(path) {
|
|
2165
|
+
return fingerprintContent(readTextFile(path));
|
|
2166
|
+
}
|
|
2167
|
+
const whoamiNameSchema = z.object({
|
|
2168
|
+
success: z.literal(true),
|
|
2169
|
+
data: z
|
|
2170
|
+
.object({
|
|
2171
|
+
name: z.string().optional(),
|
|
2172
|
+
identity: z.object({ name: z.string().optional() }).passthrough().optional(),
|
|
2173
|
+
})
|
|
2174
|
+
.passthrough(),
|
|
2175
|
+
});
|
|
2176
|
+
/** Agent display name from the same whoami body hooks and the MCP server return. */
|
|
2177
|
+
export function agentDisplayNameFromWhoami(body) {
|
|
2178
|
+
const parsed = whoamiNameSchema.safeParse(body);
|
|
2179
|
+
if (!parsed.success)
|
|
2180
|
+
return null;
|
|
2181
|
+
const data = parsed.data.data;
|
|
2182
|
+
if (typeof data.name === 'string' && data.name.length > 0)
|
|
2183
|
+
return data.name;
|
|
2184
|
+
const identityName = data.identity?.name;
|
|
2185
|
+
if (typeof identityName === 'string' && identityName.length > 0)
|
|
2186
|
+
return identityName;
|
|
2187
|
+
return null;
|
|
2188
|
+
}
|
|
2189
|
+
export function formatSignedInBannerLine(agentName, agentId, signInSource, opts = {}) {
|
|
2190
|
+
// Remove never asks the service for the name; "unknown" there reads like a failure.
|
|
2191
|
+
const missing = opts.nameLookedUp === false ? '(name not looked up)' : '(name unknown)';
|
|
2192
|
+
const label = agentName !== null ? displayServiceStringForTerminal(agentName) : missing;
|
|
2193
|
+
// The source can carry a file path the person must be able to read whole: strip controls, do not cap.
|
|
2194
|
+
const source = sanitizeForTerminal(signInSource);
|
|
2195
|
+
return `This machine is signed in as ${label} (${agentId}), from ${source}.`;
|
|
2196
|
+
}
|
|
2197
|
+
export function humanSignInSourceLabel(env, home, resolvedAgentId, authKind) {
|
|
2198
|
+
let pin;
|
|
2199
|
+
try {
|
|
2200
|
+
pin = loadSessionIdentity(env);
|
|
2201
|
+
}
|
|
2202
|
+
catch {
|
|
2203
|
+
pin = null;
|
|
2204
|
+
}
|
|
2205
|
+
if (pin !== null && pin.agentId === resolvedAgentId) {
|
|
2206
|
+
return 'AIS_AGENT_ID in your environment';
|
|
2207
|
+
}
|
|
2208
|
+
switch (authKind) {
|
|
2209
|
+
case 'workspace-key':
|
|
2210
|
+
return env['AIS_WORKSPACE_KEY'] !== undefined ? 'AIS_WORKSPACE_KEY in your environment' : 'AIS_API_KEY in your environment';
|
|
2211
|
+
case 'agent-api-key':
|
|
2212
|
+
return env['AIS_API_KEY'] !== undefined ? 'AIS_API_KEY in your environment' : 'AIS_AGENT_API_KEY in your environment';
|
|
2213
|
+
case 'run-pass':
|
|
2214
|
+
return 'run-pass file in your environment';
|
|
2215
|
+
case 'oauth': {
|
|
2216
|
+
if (hasEnrolledKey({ keysDir: join(home, '.aismemory', 'keys') })) {
|
|
2217
|
+
return 'device key enrolled on this machine';
|
|
2218
|
+
}
|
|
2219
|
+
const override = env['AIS_CREDENTIALS_FILE'];
|
|
2220
|
+
if (typeof override === 'string' && override.trim().length > 0) {
|
|
2221
|
+
return `credentials file ${override.trim()} (from AIS_CREDENTIALS_FILE)`;
|
|
2222
|
+
}
|
|
2223
|
+
return 'saved sign-in in your home folder';
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
/** Path of a sign-in file that exists but cannot be parsed; null when nothing is unreadable. */
|
|
2228
|
+
export function unreadableSignInFilePath(home, env) {
|
|
2229
|
+
let credentialsPath;
|
|
2230
|
+
try {
|
|
2231
|
+
credentialsPath = credentialsFilePath(home, env);
|
|
2232
|
+
}
|
|
2233
|
+
catch {
|
|
2234
|
+
if (typeof env['AIS_CREDENTIALS_FILE'] === 'string' && env['AIS_CREDENTIALS_FILE'].trim().length > 0) {
|
|
2235
|
+
return env['AIS_CREDENTIALS_FILE'].trim();
|
|
2236
|
+
}
|
|
2237
|
+
return null;
|
|
2238
|
+
}
|
|
2239
|
+
if (!existsSync(credentialsPath))
|
|
2240
|
+
return null;
|
|
2241
|
+
let raw;
|
|
2242
|
+
try {
|
|
2243
|
+
raw = readFileSync(credentialsPath, 'utf-8').trim();
|
|
2244
|
+
}
|
|
2245
|
+
catch {
|
|
2246
|
+
// Present but it cannot be opened (permissions, a folder in its place): unreadable, by name.
|
|
2247
|
+
return credentialsPath;
|
|
2248
|
+
}
|
|
2249
|
+
if (raw.length === 0)
|
|
2250
|
+
return credentialsPath;
|
|
2251
|
+
try {
|
|
2252
|
+
const parsed = JSON.parse(raw);
|
|
2253
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
2254
|
+
return credentialsPath;
|
|
2255
|
+
const agentId = Reflect.get(parsed, 'agentId');
|
|
2256
|
+
const token = Reflect.get(parsed, 'token');
|
|
2257
|
+
const hasV2 = typeof agentId === 'string' && typeof Reflect.get(parsed, 'tenantId') === 'string';
|
|
2258
|
+
const hasV1 = typeof token === 'string' && typeof agentId === 'string';
|
|
2259
|
+
if (!hasV2 && !hasV1)
|
|
2260
|
+
return credentialsPath;
|
|
2261
|
+
return null;
|
|
2262
|
+
}
|
|
2263
|
+
catch {
|
|
2264
|
+
return credentialsPath;
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
export function setupAuthKindFromHookClient(client) {
|
|
2268
|
+
const prefix = client.credentialKey.split(':')[0] ?? '';
|
|
2269
|
+
switch (prefix) {
|
|
2270
|
+
case 'workspace-key':
|
|
2271
|
+
return 'workspace-key';
|
|
2272
|
+
case 'agent-api-key':
|
|
2273
|
+
return 'agent-api-key';
|
|
2274
|
+
case 'run-pass':
|
|
2275
|
+
return 'run-pass';
|
|
2276
|
+
case 'oauth-bearer':
|
|
2277
|
+
return 'oauth';
|
|
2278
|
+
default:
|
|
2279
|
+
throw new Error(`unknown hook credential kind: ${prefix}`);
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
export function setupSignedInClientFromHookClient(client) {
|
|
2283
|
+
return {
|
|
2284
|
+
agentId: client.agentId,
|
|
2285
|
+
pin: client.pin,
|
|
2286
|
+
authKind: setupAuthKindFromHookClient(client),
|
|
2287
|
+
callWhoami: () => client.call('whoami', {}),
|
|
2288
|
+
};
|
|
2289
|
+
}
|
|
2290
|
+
/**
|
|
2291
|
+
* Resolve the signed-in agent via `resolveHookClient` (credential order matches MCP main() / whoami).
|
|
2292
|
+
*/
|
|
2293
|
+
export async function resolveSetupSignedInClient(env, home) {
|
|
2294
|
+
try {
|
|
2295
|
+
const hook = await resolveHookClient(env, home);
|
|
2296
|
+
return setupSignedInClientFromHookClient(hook);
|
|
2297
|
+
}
|
|
2298
|
+
catch (err) {
|
|
2299
|
+
if (err instanceof HookFailure) {
|
|
2300
|
+
if (err.message === NO_CREDENTIAL_HINT)
|
|
2301
|
+
throw new Error('no credential');
|
|
2302
|
+
throw new Error(err.message);
|
|
2303
|
+
}
|
|
2304
|
+
throw err;
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
export const SETUP_NOT_SIGNED_IN_MSG = 'This machine is not signed in to your memory account. Run `aismemory` once to sign in, or pass --identity <agent id>.';
|
|
2308
|
+
export const SETUP_SIGN_IN_CHECK_FAILED_MSG = 'Could not check the sign-in on this machine. Pass --identity <agent id>, or run `aismemory` to sign in again.';
|
|
2309
|
+
export async function discoverSignedInAgentForSetup(home, env, options = {}) {
|
|
2310
|
+
const unreadable = unreadableSignInFilePath(home, env);
|
|
2311
|
+
if (unreadable !== null) {
|
|
2312
|
+
return { ok: false, exitCode: 1, message: `Could not read saved sign-in at ${unreadable}.\n` };
|
|
2313
|
+
}
|
|
2314
|
+
let sessionPin = null;
|
|
2315
|
+
try {
|
|
2316
|
+
sessionPin = loadSessionIdentity(env);
|
|
2317
|
+
}
|
|
2318
|
+
catch {
|
|
2319
|
+
return { ok: false, exitCode: 1, message: 'AIS_AGENT_ID is not a valid agent id; copy it from whoami\n' };
|
|
2320
|
+
}
|
|
2321
|
+
const adapterEnv = { ...env, AIS_AGENT_ID: sessionPin?.agentId ?? env['AIS_AGENT_ID'] };
|
|
2322
|
+
try {
|
|
2323
|
+
loadWorkspaceKeyConfig(adapterEnv);
|
|
2324
|
+
}
|
|
2325
|
+
catch (err) {
|
|
2326
|
+
if (err instanceof WorkspaceKeyConfigError) {
|
|
2327
|
+
return { ok: false, exitCode: 1, message: `${err.message}\n` };
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
try {
|
|
2331
|
+
loadAgentApiKeyConfig(adapterEnv);
|
|
2332
|
+
}
|
|
2333
|
+
catch (err) {
|
|
2334
|
+
if (err instanceof AgentApiKeyConfigError) {
|
|
2335
|
+
return { ok: false, exitCode: 1, message: `${err.message}\n` };
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
try {
|
|
2339
|
+
loadRunPassConfig(env);
|
|
2340
|
+
}
|
|
2341
|
+
catch (err) {
|
|
2342
|
+
if (err instanceof RunPassConfigError) {
|
|
2343
|
+
return { ok: false, exitCode: 1, message: `${err.message}\n` };
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
let client;
|
|
2347
|
+
try {
|
|
2348
|
+
client = await (options.resolveClient ?? resolveSetupSignedInClient)(env, home);
|
|
2349
|
+
}
|
|
2350
|
+
catch (err) {
|
|
2351
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2352
|
+
if (msg === 'no credential' || msg.startsWith('no agent selected')) {
|
|
2353
|
+
return { ok: false, exitCode: 1, message: `${SETUP_NOT_SIGNED_IN_MSG}\n` };
|
|
2354
|
+
}
|
|
2355
|
+
if (msg === 'AIS_AGENT_ID is not a valid agent id; copy it from whoami') {
|
|
2356
|
+
return { ok: false, exitCode: 1, message: `${msg}\n` };
|
|
2357
|
+
}
|
|
2358
|
+
if (msg.includes('unset one')) {
|
|
2359
|
+
return { ok: false, exitCode: 1, message: `${msg}\n` };
|
|
2360
|
+
}
|
|
2361
|
+
// Anything else is a failure to check, not proof that nobody is signed in. Say so; print only the
|
|
2362
|
+
// system error code (such as EACCES), never the error text, which could carry part of a credential.
|
|
2363
|
+
const code = typeof err === 'object' && err !== null ? Reflect.get(err, 'code') : undefined;
|
|
2364
|
+
const detail = typeof code === 'string' && /^[A-Z0-9_]{1,32}$/.test(code) ? ` (${code})` : '';
|
|
2365
|
+
return { ok: false, exitCode: 1, message: `${SETUP_SIGN_IN_CHECK_FAILED_MSG}${detail}\n` };
|
|
2366
|
+
}
|
|
2367
|
+
let agentName = null;
|
|
2368
|
+
if (options.skipAgentDisplayName !== true) {
|
|
2369
|
+
let whoamiBody;
|
|
2370
|
+
try {
|
|
2371
|
+
whoamiBody = await client.callWhoami();
|
|
2372
|
+
}
|
|
2373
|
+
catch {
|
|
2374
|
+
whoamiBody = null;
|
|
2375
|
+
}
|
|
2376
|
+
agentName = whoamiBody !== null ? agentDisplayNameFromWhoami(whoamiBody) : null;
|
|
2377
|
+
}
|
|
2378
|
+
const signInSource = humanSignInSourceLabel(env, home, client.agentId, client.authKind);
|
|
2379
|
+
return { ok: true, agentId: client.agentId, agentName, signInSource };
|
|
2380
|
+
}
|
|
2381
|
+
//# sourceMappingURL=setup-core.js.map
|