@geminixiang/mikan 1.0.0-beta.62 → 1.0.0-beta.64

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.
Files changed (56) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +13 -13
  3. package/dist/adapters/commands/sandbox.d.ts.map +1 -1
  4. package/dist/adapters/commands/sandbox.js +30 -53
  5. package/dist/adapters/commands/sandbox.js.map +1 -1
  6. package/dist/adapters/commands/types.d.ts +3 -3
  7. package/dist/adapters/commands/types.d.ts.map +1 -1
  8. package/dist/adapters/commands/types.js.map +1 -1
  9. package/dist/adapters/slack/bot.d.ts +8 -0
  10. package/dist/adapters/slack/bot.d.ts.map +1 -1
  11. package/dist/adapters/slack/bot.js +32 -2
  12. package/dist/adapters/slack/bot.js.map +1 -1
  13. package/dist/adapters/web/admin/portal.d.ts.map +1 -1
  14. package/dist/adapters/web/admin/portal.js +26 -121
  15. package/dist/adapters/web/admin/portal.js.map +1 -1
  16. package/dist/cli/boot.js +1 -1
  17. package/dist/cli/boot.js.map +1 -1
  18. package/dist/cli/office.d.ts.map +1 -1
  19. package/dist/cli/office.js +33 -1
  20. package/dist/cli/office.js.map +1 -1
  21. package/dist/config.d.ts +26 -11
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/config.js +103 -61
  24. package/dist/config.js.map +1 -1
  25. package/dist/harness/execution-resolver.d.ts.map +1 -1
  26. package/dist/harness/execution-resolver.js +1 -1
  27. package/dist/harness/execution-resolver.js.map +1 -1
  28. package/dist/harness/prompt.d.ts.map +1 -1
  29. package/dist/harness/prompt.js +17 -21
  30. package/dist/harness/prompt.js.map +1 -1
  31. package/dist/harness/runner.d.ts.map +1 -1
  32. package/dist/harness/runner.js +2 -2
  33. package/dist/harness/runner.js.map +1 -1
  34. package/dist/office/projection.d.ts +19 -2
  35. package/dist/office/projection.d.ts.map +1 -1
  36. package/dist/office/projection.js +67 -99
  37. package/dist/office/projection.js.map +1 -1
  38. package/dist/office/types.d.ts +7 -8
  39. package/dist/office/types.d.ts.map +1 -1
  40. package/dist/office/types.js.map +1 -1
  41. package/dist/sandbox/index.d.ts +9 -1
  42. package/dist/sandbox/index.d.ts.map +1 -1
  43. package/dist/sandbox/index.js +16 -12
  44. package/dist/sandbox/index.js.map +1 -1
  45. package/dist/sandbox/provisioner.d.ts +8 -0
  46. package/dist/sandbox/provisioner.d.ts.map +1 -1
  47. package/dist/sandbox/provisioner.js +36 -0
  48. package/dist/sandbox/provisioner.js.map +1 -1
  49. package/dist/settings-mutation.d.ts +5 -29
  50. package/dist/settings-mutation.d.ts.map +1 -1
  51. package/dist/settings-mutation.js +7 -13
  52. package/dist/settings-mutation.js.map +1 -1
  53. package/dist/types.d.ts +2 -32
  54. package/dist/types.d.ts.map +1 -1
  55. package/dist/types.js.map +1 -1
  56. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAe,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAEhC,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IACnD,YAA4B,YAAoB;QAC9C,KAAK,CAAC,mCAAmC,YAAY,EAAE,CAAC,CAAC;4BAD/B,YAAY;QAEtC,IA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,CACzE,CAAC;AACJ,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { Type, type Static } from \"@sinclair/typebox\";\nimport { existsSync, lstatSync, readFileSync, renameSync, rmSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { effectiveStateDir } from \"./cli/arg-grammar.js\";\nimport { readEnv } from \"./env-manifest.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"./file-guards.js\";\nimport { atomicWritePrivateFile } from \"./file-guards.js\";\nimport * as log from \"./log.js\";\n\nexport class MissingGlobalSettingsError extends Error {\n constructor(public readonly settingsPath: string) {\n super(`Missing global settings file at ${settingsPath}`);\n this.name = \"MissingGlobalSettingsError\";\n }\n}\n\nexport type { AgentConfig, SandboxSettings, WorkspacePolicyChoice } from \"./types.js\";\nimport type { AgentConfig, SandboxSettings, WorkspacePolicyChoice } from \"./types.js\";\nimport type { McpServerConfig } from \"./harness/types.js\";\nimport type { OnboardLlmChoice } from \"./types.js\";\nimport type { Office } from \"./office/index.js\";\n\nconst ONBOARD_SETTINGS: SettingsFileConfig = {\n llm: {\n provider: \"anthropic\",\n model: \"claude-sonnet-4-6\",\n thinkingLevel: \"off\",\n },\n slack: {\n replyMode: \"top-level\",\n },\n sandbox: {\n cpus: \"0.5\",\n memory: \"1g\",\n boost: {\n cpus: \"2\",\n memory: \"4g\",\n },\n // No pinned workspace door policy: with nothing set, the projection\n // follows the platform's own channel vocabulary (public channels share\n // workspace memory, private channels read it without writing, DMs stay\n // isolated — see workspace-projection platformDerivedWorkspace).\n // Deployments that predate this keep their explicit isolated setting.\n defaultSharedVault: \"\",\n },\n};\n\nconst SettingsFileSchema = Type.Object({\n llm: Type.Optional(\n Type.Object({\n provider: Type.Optional(Type.String()),\n model: Type.Optional(Type.String()),\n thinkingLevel: Type.Optional(\n Type.Union([\n Type.Literal(\"off\"),\n Type.Literal(\"minimal\"),\n Type.Literal(\"low\"),\n Type.Literal(\"medium\"),\n Type.Literal(\"high\"),\n Type.Literal(\"xhigh\"),\n Type.Literal(\"max\"),\n ]),\n ),\n }),\n ),\n sentry: Type.Optional(\n Type.Object({\n dsn: Type.Optional(Type.String()),\n }),\n ),\n slack: Type.Optional(\n Type.Object({\n replyMode: Type.Optional(Type.Union([Type.Literal(\"top-level\"), Type.Literal(\"thread\")])),\n }),\n ),\n sandbox: Type.Optional(\n Type.Object({\n cpus: Type.Optional(Type.String()),\n memory: Type.Optional(Type.String()),\n boost: Type.Optional(\n Type.Object({\n cpus: Type.Optional(Type.String()),\n memory: Type.Optional(Type.String()),\n }),\n ),\n image: Type.Optional(\n Type.Object({\n workspaceMount: Type.Optional(\n Type.Union([Type.Literal(\"private\"), Type.Literal(\"full\")]),\n ),\n }),\n ),\n workspace: Type.Optional(\n Type.Object({\n doorPolicy: Type.Optional(\n Type.Union([Type.Literal(\"isolated\"), Type.Literal(\"trusted\")]),\n ),\n layout: Type.Optional(\n Type.Union([\n Type.Literal(\"conversation\"),\n Type.Literal(\"shared-support\"),\n Type.Literal(\"full\"),\n ]),\n ),\n visibility: Type.Optional(Type.Union([Type.Literal(\"public\"), Type.Literal(\"private\")])),\n }),\n ),\n defaultSharedVault: Type.Optional(Type.String()),\n }),\n ),\n /**\n * MCP servers, keyed by name. Merged per key across scopes: a conversation\n * entry overrides (or, with `disabled: true`, turns off) the same-name\n * global entry; other global entries stay available. `open-connector` is an\n * ordinary entry that the host fills in from `OPENCONNECTOR_ENDPOINT` when\n * neither scope declares it (see `src/harness/open-connector.ts`).\n */\n mcpServers: Type.Optional(\n Type.Record(\n Type.String(),\n Type.Object({\n command: Type.Optional(Type.String()),\n args: Type.Optional(Type.Array(Type.String())),\n env: Type.Optional(Type.Record(Type.String(), Type.String())),\n url: Type.Optional(Type.String()),\n headers: Type.Optional(Type.Record(Type.String(), Type.String())),\n disabled: Type.Optional(Type.Boolean()),\n }),\n ),\n ),\n});\n\ntype SettingsFileConfig = Static<typeof SettingsFileSchema>;\n\nfunction loadSettingsFile(settingsPath: string): SettingsFileConfig | undefined {\n return readJsonSchemaFileIfExists(settingsPath, SettingsFileSchema, (detail) =>\n detail === \"unexpected JSON shape\"\n ? `Malformed settings file at ${settingsPath}: expected a JSON object at the top level`\n : `Malformed settings file at ${settingsPath}: ${detail}`,\n );\n}\n\nfunction normalizeSettingsConfig(config: SettingsFileConfig): Partial<AgentConfig> {\n return {\n ...(config.llm?.provider !== undefined ? { provider: config.llm.provider } : {}),\n ...(config.llm?.model !== undefined ? { model: config.llm.model } : {}),\n ...(config.llm?.thinkingLevel !== undefined ? { thinkingLevel: config.llm.thinkingLevel } : {}),\n ...(config.sentry?.dsn !== undefined ? { sentryDsn: config.sentry.dsn } : {}),\n ...(config.sandbox !== undefined ? { sandbox: normalizeSandboxSettings(config.sandbox) } : {}),\n ...(config.slack !== undefined ? { slack: config.slack } : {}),\n ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),\n };\n}\n\n/**\n * File shape → in-memory shape for the sandbox group. An empty or\n * whitespace-only `defaultSharedVault` means \"no default\" and is dropped;\n * non-empty values are trimmed. Everything else passes through as-is.\n */\nfunction normalizeSandboxSettings(sandbox: SandboxSettings): SandboxSettings {\n const defaultSharedVault = sandbox.defaultSharedVault?.trim();\n const legacyWorkspace =\n sandbox.image?.workspaceMount === \"private\"\n ? { doorPolicy: \"trusted\" as const, layout: \"shared-support\" as const }\n : sandbox.image?.workspaceMount === \"full\"\n ? { doorPolicy: \"trusted\" as const, layout: \"full\" as const }\n : undefined;\n const workspace = legacyWorkspace\n ? { ...legacyWorkspace, ...sandbox.workspace }\n : sandbox.workspace;\n return {\n ...(sandbox.cpus !== undefined ? { cpus: sandbox.cpus } : {}),\n ...(sandbox.memory !== undefined ? { memory: sandbox.memory } : {}),\n ...(sandbox.boost !== undefined ? { boost: sandbox.boost } : {}),\n ...(sandbox.image !== undefined ? { image: sandbox.image } : {}),\n ...(workspace !== undefined ? { workspace } : {}),\n ...(defaultSharedVault ? { defaultSharedVault } : {}),\n };\n}\n\n/**\n * Merge two sandbox settings groups. The merge invariant is LEAF-LEVEL:\n * an override that only sets `sandbox.memory` keeps the base `sandbox.cpus`,\n * and an override that only sets `boost.memory` keeps the base `boost.cpus`\n * (same for `image`). This mirrors how the fields merged when they were\n * flat top-level keys; a group-level spread would silently drop base leaves.\n */\nfunction mergeSandboxSettings(\n base: SandboxSettings | undefined,\n override: SandboxSettings | undefined,\n): SandboxSettings | undefined {\n if (!base) return override;\n if (!override) return base;\n return {\n ...base,\n ...override,\n ...(base.boost || override.boost ? { boost: { ...base.boost, ...override.boost } } : {}),\n ...(base.image || override.image ? { image: { ...base.image, ...override.image } } : {}),\n ...(base.workspace || override.workspace\n ? { workspace: { ...base.workspace, ...override.workspace } }\n : {}),\n };\n}\n\nfunction getSettingsPath(): string {\n return join(effectiveStateDir(), \"settings.json\");\n}\n\nfunction requireGlobalSettings(): SettingsFileConfig {\n const settingsPath = getSettingsPath();\n const config = loadSettingsFile(settingsPath);\n if (!config) {\n throw new MissingGlobalSettingsError(settingsPath);\n }\n return config;\n}\n\nfunction requireString(value: string | undefined, path: string): string {\n if (!value) {\n throw new Error(\n `Missing required global setting: ${path}. Run \\`mikan --onboard\\` to create settings.json.`,\n );\n }\n return value;\n}\n\nfunction toAgentConfig(fromFile: Partial<AgentConfig>): AgentConfig {\n const provider = requireString(fromFile.provider, \"llm.provider\");\n const model = requireString(fromFile.model, \"llm.model\");\n const thinkingLevel = requireString(fromFile.thinkingLevel, \"llm.thinkingLevel\") as ThinkingLevel;\n const sentryDsn = sentryDsnFrom(fromFile.sentryDsn);\n const sandbox = fromFile.sandbox;\n const slack = fromFile.slack;\n const mcpServers = fromFile.mcpServers;\n\n return {\n provider,\n model,\n thinkingLevel,\n sentryDsn,\n sandbox,\n slack,\n mcpServers,\n };\n}\n\nfunction loadRawGlobalSettings(): Partial<AgentConfig> {\n return normalizeSettingsConfig(requireGlobalSettings());\n}\n\nexport function loadGlobalSettings(): AgentConfig {\n return toAgentConfig(loadRawGlobalSettings());\n}\n\n/**\n * Host-authoritative location of a conversation's settings file:\n * `<office state dir>/settings.json`. The Office value names both the\n * state-dir key and the legacy pre-host-migration location (its workspace\n * dir) — the key is never inferred from a directory basename.\n *\n * Conversation settings used to live at `<conversationDir>/settings.json`,\n * but conversation dirs are bind-mounted read-write into sandbox containers\n * in image mode — code inside the sandbox could edit its own settings.json\n * and flip `sandbox.image.workspaceMount` to \"full\", remounting the entire\n * workspace into its container (cross-conversation access). Settings are an\n * administrator surface, so they live under the host-only state dir.\n *\n * Migration: on first access per conversation, a legacy\n * `<conversationDir>/settings.json` is moved here. The new file's existence\n * (an empty `{}` is written when there is nothing to migrate) is the\n * migration marker — a legacy file (re)appearing later, e.g. planted from\n * inside the sandbox, is never read again.\n */\nexport function conversationSettingsPath(office: Office): string {\n const hostPath = join(office.stateDir, \"settings.json\");\n if (existsSync(hostPath)) {\n assertSettingsFile(hostPath, \"Host conversation settings\");\n return hostPath;\n }\n\n ensureDirExists(dirname(hostPath));\n const legacyPath = join(office.dir, \"settings.json\");\n let content = \"{}\\n\";\n let migrated = false;\n if (existsSync(legacyPath)) {\n assertSettingsFile(legacyPath, \"Legacy conversation settings\");\n content = readFileSync(legacyPath, \"utf-8\");\n // Validate before moving the file. A malformed legacy file must fail\n // closed and remain available for an operator to repair.\n loadSettingsFile(legacyPath);\n migrated = true;\n }\n atomicWritePrivateFile(hostPath, content);\n if (migrated) {\n try {\n rmSync(legacyPath);\n } catch (err) {\n log.logWarning(`Could not remove legacy conversation settings: ${legacyPath}`, String(err));\n }\n log.logInfo(`Migrated conversation settings to host-only path: ${hostPath}`);\n }\n return hostPath;\n}\n\nfunction assertSettingsFile(path: string, label: string): void {\n let stats;\n try {\n stats = lstatSync(path);\n } catch (err) {\n throw new Error(`${label} cannot be inspected: ${path}`, { cause: err });\n }\n if (stats.isSymbolicLink() || !stats.isFile()) {\n throw new Error(`${label} must be a regular non-symlink file: ${path}`);\n }\n}\n\nconst AUTO_REPLY_FILE = \"auto-reply\";\nconst AUTO_REPLY_DISABLED_FILE = \"auto-reply.disabled\";\n\nexport function slackConversationAutoReplyEnabled(office: Office): boolean {\n return existsSync(join(office.dir, AUTO_REPLY_FILE));\n}\n\nexport function setSlackConversationAutoReply(office: Office, enabled: boolean): void {\n ensureDirExists(office.dir);\n const enabledPath = join(office.dir, AUTO_REPLY_FILE);\n const disabledPath = join(office.dir, AUTO_REPLY_DISABLED_FILE);\n const targetPath = enabled ? enabledPath : disabledPath;\n const otherPath = enabled ? disabledPath : enabledPath;\n\n if (existsSync(otherPath)) {\n renameSync(otherPath, targetPath);\n return;\n }\n if (enabled && !existsSync(targetPath)) {\n atomicWritePrivateFile(targetPath, \"\");\n }\n}\n\nexport function resolveConversationSettings(office: Office): AgentConfig {\n const globalConfig = loadRawGlobalSettings();\n const conversationConfig = normalizeSettingsConfig(\n loadSettingsFile(conversationSettingsPath(office)) ?? {},\n );\n // MCP servers merge per key: a conversation redefines or disables individual\n // servers without losing the rest of the global set.\n const mcpServers = { ...globalConfig.mcpServers, ...conversationConfig.mcpServers };\n // The sandbox group merges at the leaf level (see mergeSandboxSettings):\n // a conversation that only sets sandbox.memory keeps the global sandbox.cpus.\n const sandbox = mergeSandboxSettings(globalConfig.sandbox, conversationConfig.sandbox);\n return toAgentConfig({\n ...globalConfig,\n ...conversationConfig,\n ...(sandbox ? { sandbox } : {}),\n ...(Object.keys(mcpServers).length > 0 ? { mcpServers } : {}),\n });\n}\n\n/**\n * True when `child` is `parent` or a path inside it. Purely lexical (no\n * symlink resolution) — used for configuration sanity checks, not as the\n * final security boundary.\n */\nexport function isPathInside(child: string, parent: string): boolean {\n const parentPath = resolve(parent);\n const childPath = resolve(child);\n return childPath === parentPath || childPath.startsWith(parentPath + \"/\");\n}\n\n/**\n * The state dir (settings, office records, vaults) must never live inside\n * the working dir: conversation opt-in \"full\" mode mounts the entire working\n * dir read-write into sandbox containers, which would expose host-authoritative\n * state and credentials. Fatal under sandboxed modes; host mode has no mounts,\n * so only warn about the bad hygiene.\n */\nexport function assertStateDirOutsideWorkspace(\n stateDir: string,\n workingDir: string,\n sandboxType: string,\n): void {\n if (!isPathInside(stateDir, workingDir)) return;\n const message =\n `--state-dir (${stateDir}) must not be inside the working directory (${workingDir}): ` +\n `sandbox containers mount the working directory, and a mounted state dir ` +\n `would expose settings, office records, vaults, and credentials to sandboxed code.`;\n if (sandboxType === \"host\") {\n log.logWarning(\"Insecure state dir location\", message);\n return;\n }\n throw new Error(message);\n}\n\n/** Settings-file DSN wins over SENTRY_DSN env — the rule lives only here. */\nfunction sentryDsnFrom(fromFile: string | undefined): string | undefined {\n return fromFile || readEnv(\"SENTRY_DSN\");\n}\n\nexport function resolveSentryDsn(): string | undefined {\n const fromFile = normalizeSettingsConfig(loadSettingsFile(getSettingsPath()) ?? {});\n return sentryDsnFrom(fromFile.sentryDsn);\n}\n\nexport function createGlobalSettingsFile(stateDir: string, llm?: OnboardLlmChoice): string {\n const settingsPath = join(stateDir, \"settings.json\");\n if (existsSync(settingsPath)) {\n throw new Error(`Global settings already exists at ${settingsPath}`);\n }\n ensureDirExists(stateDir);\n const settings: SettingsFileConfig = llm\n ? {\n ...ONBOARD_SETTINGS,\n llm: {\n ...ONBOARD_SETTINGS.llm,\n provider: llm.provider,\n model: llm.model,\n },\n }\n : ONBOARD_SETTINGS;\n atomicWritePrivateFile(settingsPath, JSON.stringify(settings, null, 2));\n return settingsPath;\n}\n\n/**\n * Externally-visible base URL of the link/OAuth server, e.g.\n * `https://mikan.example.com` (no trailing slash). Read from `LINK_URL` or\n * `MIKAN_LINK_URL`, the same env var the bot uses to build credential onboarding links.\n */\nexport function resolveLinkBaseUrl(): string | undefined {\n const raw = readEnv(\"LINK_URL\");\n if (!raw) return undefined;\n return raw.replace(/\\/+$/, \"\");\n}\n\nfunction hasDefinedValue(values: Record<string, unknown> | undefined): boolean {\n return values !== undefined && Object.values(values).some((value) => value !== undefined);\n}\n\nfunction compactSettingsConfig(config: SettingsFileConfig): SettingsFileConfig {\n return {\n ...(hasDefinedValue(config.llm) ? { llm: config.llm } : {}),\n ...(hasDefinedValue(config.sentry) ? { sentry: config.sentry } : {}),\n ...(hasDefinedValue(config.sandbox) ? { sandbox: config.sandbox } : {}),\n ...(hasDefinedValue(config.slack) ? { slack: config.slack } : {}),\n // An empty map means \"all servers removed\".\n ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),\n };\n}\n\nfunction patchSettingsConfig(\n existing: SettingsFileConfig,\n config: Partial<AgentConfig>,\n): SettingsFileConfig {\n const patched: SettingsFileConfig = {\n ...existing,\n llm: {\n ...existing.llm,\n ...(config.provider !== undefined ? { provider: config.provider } : {}),\n ...(config.model !== undefined ? { model: config.model } : {}),\n ...(config.thinkingLevel !== undefined ? { thinkingLevel: config.thinkingLevel } : {}),\n },\n sentry: {\n ...existing.sentry,\n ...(config.sentryDsn !== undefined ? { dsn: config.sentryDsn } : {}),\n },\n // Leaf-level merge: a patch that only sets sandbox.boost.memory keeps the\n // existing boost.cpus (and every other existing leaf). compactSettingsConfig\n // drops the group entirely when it ends up with no defined values.\n sandbox: mergeSandboxSettings(existing.sandbox, config.sandbox) ?? {},\n slack: {\n ...existing.slack,\n ...config.slack,\n },\n // The portal edits the full MCP map, and\n // a merge would make removing a server impossible.\n ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),\n };\n return compactSettingsConfig(patched);\n}\n\nfunction loadSettingsFileForUpdate(\n settingsPath: string,\n defaultSettings: SettingsFileConfig,\n): SettingsFileConfig {\n if (!existsSync(settingsPath)) return defaultSettings;\n try {\n return loadSettingsFile(settingsPath) ?? {};\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n const message = detail.startsWith(\"Malformed settings file\")\n ? detail.replace(\"Malformed settings file\", \"Refusing to overwrite malformed settings file\")\n : detail;\n throw new Error(message, { cause: err });\n }\n}\n\nfunction updateSettingsFile(\n settingsPath: string,\n patch: Partial<AgentConfig>,\n defaultSettings: SettingsFileConfig,\n): void {\n const existing = loadSettingsFileForUpdate(settingsPath, defaultSettings);\n ensureDirExists(dirname(settingsPath));\n atomicWritePrivateFile(\n settingsPath,\n JSON.stringify(patchSettingsConfig(existing, patch), null, 2),\n );\n}\n\nexport function updateGlobalSettings(patch: Partial<AgentConfig>): void {\n updateSettingsFile(getSettingsPath(), patch, ONBOARD_SETTINGS);\n}\n\nexport function updateConversationSettings(office: Office, patch: Partial<AgentConfig>): void {\n updateSettingsFile(conversationSettingsPath(office), patch, {});\n}\n\n/**\n * The two scope-level MCP server maps, unmerged: the portal edits each scope's\n * own file, so it needs the raw per-scope values, not the effective merge\n * (`resolveConversationSettings` owns that).\n */\nexport function loadScopeMcpServers(office: Office): {\n global: Record<string, McpServerConfig>;\n conversation: Record<string, McpServerConfig>;\n} {\n return {\n global: loadRawGlobalSettings().mcpServers ?? {},\n conversation: loadSettingsFile(conversationSettingsPath(office))?.mcpServers ?? {},\n };\n}\n\n/**\n * The conversation's own door-policy override (legacy `image.workspaceMount`\n * included), or null when the office follows the global default. Missing\n * `visibility` on a shared-support choice defaults to \"public\" downstream\n * (see resolveEffectiveWorkspace), preserving today's read-write behavior for\n * every office that predates this setting.\n */\nexport function loadConversationWorkspaceOverride(office: Office): WorkspacePolicyChoice | null {\n const file = loadSettingsFile(conversationSettingsPath(office));\n const sandbox = file?.sandbox;\n if (sandbox?.workspace?.doorPolicy === \"isolated\") return { doorPolicy: \"isolated\" };\n if (sandbox?.workspace?.doorPolicy === \"trusted\") {\n if (sandbox.workspace.layout === \"full\") return { doorPolicy: \"trusted\", layout: \"full\" };\n return {\n doorPolicy: \"trusted\",\n layout: \"shared-support\",\n ...(sandbox.workspace.visibility ? { visibility: sandbox.workspace.visibility } : {}),\n };\n }\n if (sandbox?.image?.workspaceMount === \"full\") return { doorPolicy: \"trusted\", layout: \"full\" };\n if (sandbox?.image?.workspaceMount === \"private\") {\n return { doorPolicy: \"trusted\", layout: \"shared-support\" };\n }\n return null;\n}\n\nexport function setConversationWorkspacePolicy(\n office: Office,\n choice: WorkspacePolicyChoice | null,\n): void {\n writeWorkspacePolicy(conversationSettingsPath(office), choice, {});\n}\n\nexport function setGlobalWorkspacePolicy(choice: WorkspacePolicyChoice | null): void {\n writeWorkspacePolicy(getSettingsPath(), choice, ONBOARD_SETTINGS);\n}\n\n/**\n * The generic settings patch merges leaves and cannot remove keys, so the\n * door-policy writer edits the file shape directly: it always drops the\n * legacy `image.workspaceMount` (the explicit choice replaces it) and either\n * sets or removes the `workspace` group.\n */\nfunction writeWorkspacePolicy(\n settingsPath: string,\n choice: WorkspacePolicyChoice | null,\n defaultSettings: SettingsFileConfig,\n): void {\n const existing = loadSettingsFileForUpdate(settingsPath, defaultSettings);\n const { workspaceMount: _legacy, ...image } = existing.sandbox?.image ?? {};\n const { workspace: _previous, image: _image, ...sandboxRest } = existing.sandbox ?? {};\n const sandbox: SandboxSettings = {\n ...sandboxRest,\n ...(hasDefinedValue(image) ? { image } : {}),\n ...(choice ? { workspace: choice } : {}),\n };\n ensureDirExists(dirname(settingsPath));\n atomicWritePrivateFile(\n settingsPath,\n JSON.stringify(compactSettingsConfig({ ...existing, sandbox }), null, 2),\n );\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAe,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAClF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAC/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAA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ACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { Type, type Static } from \"@sinclair/typebox\";\nimport { existsSync, lstatSync, readFileSync, renameSync, rmSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { effectiveStateDir } from \"./cli/arg-grammar.js\";\nimport { readEnv } from \"./env-manifest.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"./file-guards.js\";\nimport { atomicWritePrivateFile } from \"./file-guards.js\";\nimport * as log from \"./log.js\";\n\nexport class MissingGlobalSettingsError extends Error {\n constructor(public readonly settingsPath: string) {\n super(`Missing global settings file at ${settingsPath}`);\n this.name = \"MissingGlobalSettingsError\";\n }\n}\n\nexport type { AgentConfig, SandboxSettings } from \"./types.js\";\nimport type { AgentConfig, OfficeKey, SandboxSettings } from \"./types.js\";\nimport type { McpServerConfig } from \"./harness/types.js\";\nimport type { OnboardLlmChoice } from \"./types.js\";\nimport { listRegisteredOffices, type Office, type Workspace } from \"./office/index.js\";\n\nconst ONBOARD_SETTINGS: SettingsFileConfig = {\n llm: {\n provider: \"anthropic\",\n model: \"claude-sonnet-4-6\",\n thinkingLevel: \"off\",\n },\n slack: {\n replyMode: \"top-level\",\n },\n sandbox: {\n cpus: \"0.5\",\n memory: \"1g\",\n boost: {\n cpus: \"2\",\n memory: \"4g\",\n },\n // Office visibility is not a setting here: it follows the platform\n // conversation type (see office/projection resolveOfficeVisibility).\n defaultSharedVault: \"\",\n },\n};\n\nconst SettingsFileSchema = Type.Object({\n llm: Type.Optional(\n Type.Object({\n provider: Type.Optional(Type.String()),\n model: Type.Optional(Type.String()),\n thinkingLevel: Type.Optional(\n Type.Union([\n Type.Literal(\"off\"),\n Type.Literal(\"minimal\"),\n Type.Literal(\"low\"),\n Type.Literal(\"medium\"),\n Type.Literal(\"high\"),\n Type.Literal(\"xhigh\"),\n Type.Literal(\"max\"),\n ]),\n ),\n }),\n ),\n sentry: Type.Optional(\n Type.Object({\n dsn: Type.Optional(Type.String()),\n }),\n ),\n slack: Type.Optional(\n Type.Object({\n replyMode: Type.Optional(Type.Union([Type.Literal(\"top-level\"), Type.Literal(\"thread\")])),\n }),\n ),\n /**\n * Conversation-only office policy. `visibility: \"private\"` marks a\n * platform-public conversation as private; nothing can widen visibility\n * beyond what the platform grants, so \"public\" is never stored here.\n */\n office: Type.Optional(\n Type.Object({\n visibility: Type.Optional(Type.Literal(\"private\")),\n }),\n ),\n sandbox: Type.Optional(\n Type.Object({\n cpus: Type.Optional(Type.String()),\n memory: Type.Optional(Type.String()),\n boost: Type.Optional(\n Type.Object({\n cpus: Type.Optional(Type.String()),\n memory: Type.Optional(Type.String()),\n }),\n ),\n /**\n * Retired door-policy keys (ADR 0008). Still accepted so existing files\n * load, never copied into AgentConfig, and removed by\n * `mikan office migrate-door-policy`.\n */\n image: Type.Optional(\n Type.Object({\n workspaceMount: Type.Optional(\n Type.Union([Type.Literal(\"private\"), Type.Literal(\"full\")]),\n ),\n }),\n ),\n workspace: Type.Optional(\n Type.Object({\n doorPolicy: Type.Optional(\n Type.Union([Type.Literal(\"isolated\"), Type.Literal(\"trusted\")]),\n ),\n layout: Type.Optional(\n Type.Union([\n Type.Literal(\"conversation\"),\n Type.Literal(\"shared-support\"),\n Type.Literal(\"full\"),\n ]),\n ),\n visibility: Type.Optional(Type.Union([Type.Literal(\"public\"), Type.Literal(\"private\")])),\n }),\n ),\n defaultSharedVault: Type.Optional(Type.String()),\n }),\n ),\n /**\n * MCP servers, keyed by name. Merged per key across scopes: a conversation\n * entry overrides (or, with `disabled: true`, turns off) the same-name\n * global entry; other global entries stay available. `open-connector` is an\n * ordinary entry that the host fills in from `OPENCONNECTOR_ENDPOINT` when\n * neither scope declares it (see `src/harness/open-connector.ts`).\n */\n mcpServers: Type.Optional(\n Type.Record(\n Type.String(),\n Type.Object({\n command: Type.Optional(Type.String()),\n args: Type.Optional(Type.Array(Type.String())),\n env: Type.Optional(Type.Record(Type.String(), Type.String())),\n url: Type.Optional(Type.String()),\n headers: Type.Optional(Type.Record(Type.String(), Type.String())),\n disabled: Type.Optional(Type.Boolean()),\n }),\n ),\n ),\n});\n\ntype SettingsFileConfig = Static<typeof SettingsFileSchema>;\ntype SandboxFileSettings = NonNullable<SettingsFileConfig[\"sandbox\"]>;\n\nfunction loadSettingsFile(settingsPath: string): SettingsFileConfig | undefined {\n return readJsonSchemaFileIfExists(settingsPath, SettingsFileSchema, (detail) =>\n detail === \"unexpected JSON shape\"\n ? `Malformed settings file at ${settingsPath}: expected a JSON object at the top level`\n : `Malformed settings file at ${settingsPath}: ${detail}`,\n );\n}\n\nfunction normalizeSettingsConfig(config: SettingsFileConfig): Partial<AgentConfig> {\n return {\n ...(config.llm?.provider !== undefined ? { provider: config.llm.provider } : {}),\n ...(config.llm?.model !== undefined ? { model: config.llm.model } : {}),\n ...(config.llm?.thinkingLevel !== undefined ? { thinkingLevel: config.llm.thinkingLevel } : {}),\n ...(config.sentry?.dsn !== undefined ? { sentryDsn: config.sentry.dsn } : {}),\n ...(config.sandbox !== undefined ? { sandbox: normalizeSandboxSettings(config.sandbox) } : {}),\n ...(config.slack !== undefined ? { slack: config.slack } : {}),\n ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),\n };\n}\n\n/**\n * File shape → in-memory shape for the sandbox group. An empty or\n * whitespace-only `defaultSharedVault` means \"no default\" and is dropped;\n * non-empty values are trimmed. Everything else passes through as-is.\n */\nfunction normalizeSandboxSettings(sandbox: SandboxFileSettings): SandboxSettings {\n const defaultSharedVault = sandbox.defaultSharedVault?.trim();\n // Retired `image.workspaceMount` and `workspace` are dropped here: office\n // visibility comes from the platform (ADR 0008), never from these keys.\n return {\n ...(sandbox.cpus !== undefined ? { cpus: sandbox.cpus } : {}),\n ...(sandbox.memory !== undefined ? { memory: sandbox.memory } : {}),\n ...(sandbox.boost !== undefined ? { boost: sandbox.boost } : {}),\n ...(defaultSharedVault ? { defaultSharedVault } : {}),\n };\n}\n\n/**\n * Merge two sandbox settings groups. The merge invariant is LEAF-LEVEL:\n * an override that only sets `sandbox.memory` keeps the base `sandbox.cpus`,\n * and an override that only sets `boost.memory` keeps the base `boost.cpus`\n * (same for `image`). This mirrors how the fields merged when they were\n * flat top-level keys; a group-level spread would silently drop base leaves.\n */\nfunction mergeSandboxSettings(\n base: SandboxSettings | undefined,\n override: SandboxSettings | undefined,\n): SandboxSettings | undefined {\n if (!base) return override;\n if (!override) return base;\n return {\n ...base,\n ...override,\n ...(base.boost || override.boost ? { boost: { ...base.boost, ...override.boost } } : {}),\n };\n}\n\nfunction getSettingsPath(): string {\n return join(effectiveStateDir(), \"settings.json\");\n}\n\nfunction requireGlobalSettings(): SettingsFileConfig {\n const settingsPath = getSettingsPath();\n const config = loadSettingsFile(settingsPath);\n if (!config) {\n throw new MissingGlobalSettingsError(settingsPath);\n }\n return config;\n}\n\nfunction requireString(value: string | undefined, path: string): string {\n if (!value) {\n throw new Error(\n `Missing required global setting: ${path}. Run \\`mikan --onboard\\` to create settings.json.`,\n );\n }\n return value;\n}\n\nfunction toAgentConfig(fromFile: Partial<AgentConfig>): AgentConfig {\n const provider = requireString(fromFile.provider, \"llm.provider\");\n const model = requireString(fromFile.model, \"llm.model\");\n const thinkingLevel = requireString(fromFile.thinkingLevel, \"llm.thinkingLevel\") as ThinkingLevel;\n const sentryDsn = sentryDsnFrom(fromFile.sentryDsn);\n const sandbox = fromFile.sandbox;\n const slack = fromFile.slack;\n const mcpServers = fromFile.mcpServers;\n\n return {\n provider,\n model,\n thinkingLevel,\n sentryDsn,\n sandbox,\n slack,\n mcpServers,\n };\n}\n\nfunction loadRawGlobalSettings(): Partial<AgentConfig> {\n return normalizeSettingsConfig(requireGlobalSettings());\n}\n\nexport function loadGlobalSettings(): AgentConfig {\n return toAgentConfig(loadRawGlobalSettings());\n}\n\n/**\n * Host-authoritative location of a conversation's settings file:\n * `<office state dir>/settings.json`. The Office value names both the\n * state-dir key and the legacy pre-host-migration location (its workspace\n * dir) — the key is never inferred from a directory basename.\n *\n * Conversation settings used to live at `<conversationDir>/settings.json`,\n * but conversation dirs are bind-mounted read-write into sandbox containers\n * in image mode — code inside the sandbox could edit its own settings.json\n * and flip `sandbox.image.workspaceMount` to \"full\", remounting the entire\n * workspace into its container (cross-conversation access). Settings are an\n * administrator surface, so they live under the host-only state dir.\n *\n * Migration: on first access per conversation, a legacy\n * `<conversationDir>/settings.json` is moved here. The new file's existence\n * (an empty `{}` is written when there is nothing to migrate) is the\n * migration marker — a legacy file (re)appearing later, e.g. planted from\n * inside the sandbox, is never read again.\n */\nexport function conversationSettingsPath(office: Office): string {\n const hostPath = join(office.stateDir, \"settings.json\");\n if (existsSync(hostPath)) {\n assertSettingsFile(hostPath, \"Host conversation settings\");\n return hostPath;\n }\n\n ensureDirExists(dirname(hostPath));\n const legacyPath = join(office.dir, \"settings.json\");\n let content = \"{}\\n\";\n let migrated = false;\n if (existsSync(legacyPath)) {\n assertSettingsFile(legacyPath, \"Legacy conversation settings\");\n content = readFileSync(legacyPath, \"utf-8\");\n // Validate before moving the file. A malformed legacy file must fail\n // closed and remain available for an operator to repair.\n loadSettingsFile(legacyPath);\n migrated = true;\n }\n atomicWritePrivateFile(hostPath, content);\n if (migrated) {\n try {\n rmSync(legacyPath);\n } catch (err) {\n log.logWarning(`Could not remove legacy conversation settings: ${legacyPath}`, String(err));\n }\n log.logInfo(`Migrated conversation settings to host-only path: ${hostPath}`);\n }\n return hostPath;\n}\n\nfunction assertSettingsFile(path: string, label: string): void {\n let stats;\n try {\n stats = lstatSync(path);\n } catch (err) {\n throw new Error(`${label} cannot be inspected: ${path}`, { cause: err });\n }\n if (stats.isSymbolicLink() || !stats.isFile()) {\n throw new Error(`${label} must be a regular non-symlink file: ${path}`);\n }\n}\n\nconst AUTO_REPLY_FILE = \"auto-reply\";\nconst AUTO_REPLY_DISABLED_FILE = \"auto-reply.disabled\";\n\nexport function slackConversationAutoReplyEnabled(office: Office): boolean {\n return existsSync(join(office.dir, AUTO_REPLY_FILE));\n}\n\nexport function setSlackConversationAutoReply(office: Office, enabled: boolean): void {\n ensureDirExists(office.dir);\n const enabledPath = join(office.dir, AUTO_REPLY_FILE);\n const disabledPath = join(office.dir, AUTO_REPLY_DISABLED_FILE);\n const targetPath = enabled ? enabledPath : disabledPath;\n const otherPath = enabled ? disabledPath : enabledPath;\n\n if (existsSync(otherPath)) {\n renameSync(otherPath, targetPath);\n return;\n }\n if (enabled && !existsSync(targetPath)) {\n atomicWritePrivateFile(targetPath, \"\");\n }\n}\n\nexport function resolveConversationSettings(office: Office): AgentConfig {\n const globalConfig = loadRawGlobalSettings();\n const conversationConfig = normalizeSettingsConfig(\n loadSettingsFile(conversationSettingsPath(office)) ?? {},\n );\n // MCP servers merge per key: a conversation redefines or disables individual\n // servers without losing the rest of the global set.\n const mcpServers = { ...globalConfig.mcpServers, ...conversationConfig.mcpServers };\n // The sandbox group merges at the leaf level (see mergeSandboxSettings):\n // a conversation that only sets sandbox.memory keeps the global sandbox.cpus.\n const sandbox = mergeSandboxSettings(globalConfig.sandbox, conversationConfig.sandbox);\n return toAgentConfig({\n ...globalConfig,\n ...conversationConfig,\n ...(sandbox ? { sandbox } : {}),\n ...(Object.keys(mcpServers).length > 0 ? { mcpServers } : {}),\n });\n}\n\n/**\n * True when `child` is `parent` or a path inside it. Purely lexical (no\n * symlink resolution) — used for configuration sanity checks, not as the\n * final security boundary.\n */\nexport function isPathInside(child: string, parent: string): boolean {\n const parentPath = resolve(parent);\n const childPath = resolve(child);\n return childPath === parentPath || childPath.startsWith(parentPath + \"/\");\n}\n\n/**\n * The state dir (settings, office records, vaults) must never live inside\n * the working dir: conversation opt-in \"full\" mode mounts the entire working\n * dir read-write into sandbox containers, which would expose host-authoritative\n * state and credentials. Fatal under sandboxed modes; host mode has no mounts,\n * so only warn about the bad hygiene.\n */\nexport function assertStateDirOutsideWorkspace(\n stateDir: string,\n workingDir: string,\n sandboxType: string,\n): void {\n if (!isPathInside(stateDir, workingDir)) return;\n const message =\n `--state-dir (${stateDir}) must not be inside the working directory (${workingDir}): ` +\n `sandbox containers mount the working directory, and a mounted state dir ` +\n `would expose settings, office records, vaults, and credentials to sandboxed code.`;\n if (sandboxType === \"host\") {\n log.logWarning(\"Insecure state dir location\", message);\n return;\n }\n throw new Error(message);\n}\n\n/** Settings-file DSN wins over SENTRY_DSN env — the rule lives only here. */\nfunction sentryDsnFrom(fromFile: string | undefined): string | undefined {\n return fromFile || readEnv(\"SENTRY_DSN\");\n}\n\nexport function resolveSentryDsn(): string | undefined {\n const fromFile = normalizeSettingsConfig(loadSettingsFile(getSettingsPath()) ?? {});\n return sentryDsnFrom(fromFile.sentryDsn);\n}\n\nexport function createGlobalSettingsFile(stateDir: string, llm?: OnboardLlmChoice): string {\n const settingsPath = join(stateDir, \"settings.json\");\n if (existsSync(settingsPath)) {\n throw new Error(`Global settings already exists at ${settingsPath}`);\n }\n ensureDirExists(stateDir);\n const settings: SettingsFileConfig = llm\n ? {\n ...ONBOARD_SETTINGS,\n llm: {\n ...ONBOARD_SETTINGS.llm,\n provider: llm.provider,\n model: llm.model,\n },\n }\n : ONBOARD_SETTINGS;\n atomicWritePrivateFile(settingsPath, JSON.stringify(settings, null, 2));\n return settingsPath;\n}\n\n/**\n * Externally-visible base URL of the link/OAuth server, e.g.\n * `https://mikan.example.com` (no trailing slash). Read from `LINK_URL` or\n * `MIKAN_LINK_URL`, the same env var the bot uses to build credential onboarding links.\n */\nexport function resolveLinkBaseUrl(): string | undefined {\n const raw = readEnv(\"LINK_URL\");\n if (!raw) return undefined;\n return raw.replace(/\\/+$/, \"\");\n}\n\nfunction hasDefinedValue(values: Record<string, unknown> | undefined): boolean {\n return values !== undefined && Object.values(values).some((value) => value !== undefined);\n}\n\nfunction compactSettingsConfig(config: SettingsFileConfig): SettingsFileConfig {\n return {\n ...(hasDefinedValue(config.llm) ? { llm: config.llm } : {}),\n ...(hasDefinedValue(config.sentry) ? { sentry: config.sentry } : {}),\n ...(hasDefinedValue(config.sandbox) ? { sandbox: config.sandbox } : {}),\n ...(hasDefinedValue(config.slack) ? { slack: config.slack } : {}),\n ...(hasDefinedValue(config.office) ? { office: config.office } : {}),\n // An empty map means \"all servers removed\".\n ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),\n };\n}\n\nfunction patchSettingsConfig(\n existing: SettingsFileConfig,\n config: Partial<AgentConfig>,\n): SettingsFileConfig {\n const patched: SettingsFileConfig = {\n ...existing,\n llm: {\n ...existing.llm,\n ...(config.provider !== undefined ? { provider: config.provider } : {}),\n ...(config.model !== undefined ? { model: config.model } : {}),\n ...(config.thinkingLevel !== undefined ? { thinkingLevel: config.thinkingLevel } : {}),\n },\n sentry: {\n ...existing.sentry,\n ...(config.sentryDsn !== undefined ? { dsn: config.sentryDsn } : {}),\n },\n // Leaf-level merge: a patch that only sets sandbox.boost.memory keeps the\n // existing boost.cpus (and every other existing leaf). compactSettingsConfig\n // drops the group entirely when it ends up with no defined values.\n sandbox: mergeSandboxSettings(existing.sandbox, config.sandbox) ?? {},\n slack: {\n ...existing.slack,\n ...config.slack,\n },\n // Office visibility has its own writer (setOfficeVisibilityOverride); the\n // generic patch must not drop it.\n ...(existing.office !== undefined ? { office: existing.office } : {}),\n // The portal edits the full MCP map, and\n // a merge would make removing a server impossible.\n ...(config.mcpServers !== undefined ? { mcpServers: config.mcpServers } : {}),\n };\n return compactSettingsConfig(patched);\n}\n\nfunction loadSettingsFileForUpdate(\n settingsPath: string,\n defaultSettings: SettingsFileConfig,\n): SettingsFileConfig {\n if (!existsSync(settingsPath)) return defaultSettings;\n try {\n return loadSettingsFile(settingsPath) ?? {};\n } catch (err) {\n const detail = err instanceof Error ? err.message : String(err);\n const message = detail.startsWith(\"Malformed settings file\")\n ? detail.replace(\"Malformed settings file\", \"Refusing to overwrite malformed settings file\")\n : detail;\n throw new Error(message, { cause: err });\n }\n}\n\nfunction updateSettingsFile(\n settingsPath: string,\n patch: Partial<AgentConfig>,\n defaultSettings: SettingsFileConfig,\n): void {\n const existing = loadSettingsFileForUpdate(settingsPath, defaultSettings);\n ensureDirExists(dirname(settingsPath));\n atomicWritePrivateFile(\n settingsPath,\n JSON.stringify(patchSettingsConfig(existing, patch), null, 2),\n );\n}\n\nexport function updateGlobalSettings(patch: Partial<AgentConfig>): void {\n updateSettingsFile(getSettingsPath(), patch, ONBOARD_SETTINGS);\n}\n\nexport function updateConversationSettings(office: Office, patch: Partial<AgentConfig>): void {\n updateSettingsFile(conversationSettingsPath(office), patch, {});\n}\n\n/**\n * The two scope-level MCP server maps, unmerged: the portal edits each scope's\n * own file, so it needs the raw per-scope values, not the effective merge\n * (`resolveConversationSettings` owns that).\n */\nexport function loadScopeMcpServers(office: Office): {\n global: Record<string, McpServerConfig>;\n conversation: Record<string, McpServerConfig>;\n} {\n return {\n global: loadRawGlobalSettings().mcpServers ?? {},\n conversation: loadSettingsFile(conversationSettingsPath(office))?.mcpServers ?? {},\n };\n}\n\n/**\n * The conversation's own visibility override, or null when it follows the\n * platform. Only \"private\" can be stored: an operator may narrow a public\n * channel, never widen a private one (see ADR 0008).\n */\nexport function loadOfficeVisibilityOverride(office: Office): \"private\" | null {\n return loadSettingsFile(conversationSettingsPath(office))?.office?.visibility ?? null;\n}\n\nexport function setOfficeVisibilityOverride(office: Office, visibility: \"private\" | null): void {\n const settingsPath = conversationSettingsPath(office);\n const existing = loadSettingsFileForUpdate(settingsPath, {});\n const { office: _previous, ...rest } = existing;\n ensureDirExists(dirname(settingsPath));\n atomicWritePrivateFile(\n settingsPath,\n JSON.stringify(\n compactSettingsConfig({ ...rest, ...(visibility ? { office: { visibility } } : {}) }),\n null,\n 2,\n ),\n );\n}\n\nexport interface DoorPolicyMigrationReport {\n /** Retired keys removed from the global settings file. */\n global: string[];\n conversations: { key: OfficeKey; removed: string[]; visibility?: \"private\" }[];\n skipped: { key: OfficeKey | \"global\"; reason: string }[];\n}\n\nconst RETIRED_KEYS = {\n image: \"sandbox.image.workspaceMount\",\n workspace: \"sandbox.workspace\",\n} as const;\n\n/**\n * Strip the retired door-policy keys from one settings file. Returns the\n * removed key paths, or an empty list when nothing had to change (the file is\n * then left byte-for-byte alone, which also preserves `{}` migration markers).\n * The only value carried forward is an explicit shared-support `private`\n * visibility, which maps onto `office.visibility` (ADR 0008). Every other\n * retired combination — `full`, `isolated`, legacy `private` — is dropped\n * without deriving a grant.\n */\nfunction stripRetiredDoorPolicy(\n settingsPath: string,\n allowVisibilityCarry: boolean,\n): { removed: string[]; visibility?: \"private\" } {\n const existing = loadSettingsFile(settingsPath);\n if (!existing?.sandbox) return { removed: [] };\n const { image, workspace, ...sandboxRest } = existing.sandbox;\n const removed: string[] = [];\n if (image?.workspaceMount !== undefined) removed.push(RETIRED_KEYS.image);\n if (workspace !== undefined) removed.push(RETIRED_KEYS.workspace);\n if (removed.length === 0) return { removed };\n const carry =\n allowVisibilityCarry &&\n workspace?.doorPolicy === \"trusted\" &&\n workspace.layout !== \"full\" &&\n workspace.visibility === \"private\";\n const { workspaceMount: _mount, ...imageRest } = image ?? {};\n const sandbox: SandboxFileSettings = {\n ...sandboxRest,\n ...(hasDefinedValue(imageRest) ? { image: imageRest } : {}),\n };\n const next: SettingsFileConfig = {\n ...existing,\n sandbox,\n ...(carry ? { office: { ...existing.office, visibility: \"private\" as const } } : {}),\n };\n atomicWritePrivateFile(settingsPath, JSON.stringify(compactSettingsConfig(next), null, 2));\n return { removed, ...(carry ? { visibility: \"private\" as const } : {}) };\n}\n\n/**\n * One-time removal of the retired door-policy settings from the global file\n * and every registered office (ADR 0008). Run with the daemon stopped.\n */\nexport function migrateLegacyDoorPolicy(workspace: Workspace): DoorPolicyMigrationReport {\n const report: DoorPolicyMigrationReport = { global: [], conversations: [], skipped: [] };\n try {\n report.global = stripRetiredDoorPolicy(\n join(workspace.stateDir, \"settings.json\"),\n false,\n ).removed;\n } catch (error) {\n report.skipped.push({\n key: \"global\",\n reason: error instanceof Error ? error.message : String(error),\n });\n }\n for (const record of listRegisteredOffices(workspace.stateDir)) {\n const office = workspace.office(record);\n const settingsPath = join(office.stateDir, \"settings.json\");\n if (!existsSync(settingsPath)) continue;\n try {\n const result = stripRetiredDoorPolicy(settingsPath, true);\n if (result.removed.length > 0) report.conversations.push({ key: office.key, ...result });\n } catch (error) {\n report.skipped.push({\n key: office.key,\n reason: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return report;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"execution-resolver.d.ts","sourceRoot":"","sources":["../../src/harness/execution-resolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,sBAAsB,EAAuB,MAAM,2BAA2B,CAAC;AACxF,OAAO,EAIL,KAAK,aAAa,EACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAA4B,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAShF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAiB,MAAM,aAAa,CAAC;AAE/D,qBAAa,sBAAsB;IAE/B,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,YAAY;IACpB,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,SAAS;IAJnB,YACU,UAAU,EAAE,aAAa,EACzB,YAAY,EAAE,YAAY,EAC1B,WAAW,EAAE,sBAAsB,GAAG,SAAS,EAC/C,SAAS,EAAE,SAAS,EAC1B;IAEE,OAAO,CAAC,OAAO,EAAE,YAAY;;;;OAYlC;IAED,OAAO,CAAC,WAAW;IA2CnB,OAAO,CAAC,wBAAwB;IAuBhC,OAAO,CAAC,oBAAoB;IAc5B,OAAO,CAAC,wBAAwB;IA0ChC,OAAO,CAAC,aAAa;CA4BtB"}
1
+ {"version":3,"file":"execution-resolver.d.ts","sourceRoot":"","sources":["../../src/harness/execution-resolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,sBAAsB,EAAuB,MAAM,2BAA2B,CAAC;AACxF,OAAO,EAIL,KAAK,aAAa,EACnB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAA4B,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAShF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,YAAY,EAAiB,MAAM,aAAa,CAAC;AAE/D,qBAAa,sBAAsB;IAE/B,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,YAAY;IACpB,OAAO,CAAC,WAAW;IACnB,OAAO,CAAC,SAAS;IAJnB,YACU,UAAU,EAAE,aAAa,EACzB,YAAY,EAAE,YAAY,EAC1B,WAAW,EAAE,sBAAsB,GAAG,SAAS,EAC/C,SAAS,EAAE,SAAS,EAC1B;IAEE,OAAO,CAAC,OAAO,EAAE,YAAY;;;;OAYlC;IAED,OAAO,CAAC,WAAW;IAuCnB,OAAO,CAAC,wBAAwB;IAuBhC,OAAO,CAAC,oBAAoB;IAc5B,OAAO,CAAC,wBAAwB;IA0ChC,OAAO,CAAC,aAAa;CA4BtB"}
@@ -44,7 +44,7 @@ export class ActorExecutionResolver {
44
44
  address: office.address,
45
45
  });
46
46
  const mounts = this.resolveMounts(injection.mounts, projection);
47
- assertSandboxSupportsWorkspacePolicy(this.baseConfig, projection.doorPolicy, projection.promptSources.globalMemoryReadOnly === true);
47
+ assertSandboxSupportsWorkspacePolicy(this.baseConfig, projection.visibility, office.key);
48
48
  return {
49
49
  plan: {
50
50
  credentialKey,
@@ -1 +1 @@
1
- {"version":3,"file":"execution-resolver.js","sourceRoot":"","sources":["../../src/harness/execution-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,E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,MAAM,CAAC,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAa;IACzC,MAAM,UAAU,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC;AAC/C,CAAC","sourcesContent":["import { posix } from \"node:path\";\nimport type { Workspace } from \"../office/index.js\";\nimport { loadGlobalSettings } from \"../config.js\";\nimport { DockerContainerManager, type ContainerMount } from \"../sandbox/provisioner.js\";\nimport {\n assertSandboxSupportsWorkspacePolicy,\n createExecutor,\n getSandboxCredentialCapabilities,\n type SandboxConfig,\n} from \"../sandbox/index.js\";\nimport { reportUserFacingError } from \"../observability/index.js\";\nimport { normalizeSharedVaultName, type VaultManager } from \"../vault/index.js\";\nimport { allowsAmbientDefaultSharedVault, resolveVaultInjection } from \"../vault/index.js\";\nimport {\n credentialAuthorizationKey,\n legacyExactCredentialAuthorizationKey,\n runtimeResourceKey,\n scopeCloudflareSandboxId,\n} from \"../sandbox/identity.js\";\nimport { resolveWorkspaceProjection } from \"../office/projection.js\";\nimport type { WorkspaceProjection } from \"../office/types.js\";\n\nexport type { ActorContext } from \"../types.js\";\nimport type { ActorContext, ExecutionPlan } from \"../types.js\";\n\nexport class ActorExecutionResolver {\n constructor(\n private baseConfig: SandboxConfig,\n private vaultManager: VaultManager,\n private provisioner: DockerContainerManager | undefined,\n private workspace: Workspace,\n ) {}\n\n async resolve(context: ActorContext) {\n const { plan, projection } = this.resolvePlan(context);\n const executor = createExecutor(\n plan.sandboxConfig,\n plan.env,\n this.buildEnsureReadyCallback(plan, context.address.conversationId),\n );\n return {\n executor,\n pathContext: executor.getPathContext(this.workspace.root),\n projection,\n };\n }\n\n private resolvePlan(context: ActorContext): {\n plan: ExecutionPlan;\n projection: WorkspaceProjection;\n } {\n const scope = { userId: context.userId, address: context.address };\n const credentialKey = credentialAuthorizationKey(this.baseConfig, scope);\n const legacyCredentialKey = legacyExactCredentialAuthorizationKey(this.baseConfig, scope);\n const resourceKey = runtimeResourceKey(this.baseConfig, {\n userId: context.userId,\n address: context.address,\n });\n this.ensureDefaultSharedVault(credentialKey, legacyCredentialKey, context.trustModel);\n\n const vault =\n this.vaultManager.resolve(credentialKey) ??\n (legacyCredentialKey ? this.vaultManager.resolve(legacyCredentialKey) : undefined);\n const capabilities = getSandboxCredentialCapabilities(this.baseConfig.type);\n const office = this.workspace.office(context.address);\n const projection = resolveWorkspaceProjection(office);\n const injection = resolveVaultInjection({\n vault,\n capabilities,\n sandboxType: this.baseConfig.type,\n address: office.address,\n });\n const mounts = this.resolveMounts(injection.mounts, projection);\n assertSandboxSupportsWorkspacePolicy(\n this.baseConfig,\n projection.doorPolicy,\n projection.promptSources.globalMemoryReadOnly === true,\n );\n return {\n plan: {\n credentialKey,\n resourceKey,\n sandboxConfig: this.resolveSandboxConfig(resourceKey),\n env: injection.env,\n mounts,\n },\n projection,\n };\n }\n\n private ensureDefaultSharedVault(\n credentialKey: string,\n legacyCredentialKey: string | undefined,\n trustModel: ActorContext[\"trustModel\"],\n ): void {\n if (!allowsAmbientDefaultSharedVault({ trustModel, sandboxType: this.baseConfig.type })) return;\n if (\n this.vaultManager.hasEntry(credentialKey) ||\n (legacyCredentialKey && this.vaultManager.hasEntry(legacyCredentialKey))\n ) {\n return;\n }\n\n let profile: string | undefined;\n try {\n profile = loadGlobalSettings().sandbox?.defaultSharedVault;\n } catch {\n return;\n }\n if (!profile || normalizeSharedVaultName(profile) !== profile) return;\n this.vaultManager.copySharedVaultTo(profile, credentialKey);\n }\n\n private resolveSandboxConfig(resourceKey: string): SandboxConfig {\n if (this.baseConfig.type === \"cloudflare\") {\n return {\n type: \"cloudflare\",\n sandboxId: scopeCloudflareSandboxId(this.baseConfig.sandboxId, resourceKey),\n };\n }\n if (this.baseConfig.type !== \"image\") return this.baseConfig;\n return {\n type: \"container\",\n container: DockerContainerManager.containerName(resourceKey),\n };\n }\n\n private buildEnsureReadyCallback(\n plan: ExecutionPlan,\n conversationId: string,\n ): (() => Promise<void>) | undefined {\n if (this.baseConfig.type !== \"image\" || plan.sandboxConfig.type !== \"container\") {\n return undefined;\n }\n\n return async () => {\n const expected = plan.sandboxConfig.type === \"container\" ? plan.sandboxConfig.container : \"\";\n let actual: string | undefined;\n try {\n actual = await this.provisioner?.provision(plan.resourceKey, {\n containerName: expected,\n mounts: plan.mounts,\n conversationId,\n });\n } catch (err) {\n reportUserFacingError(err, {\n domain: \"sandbox\",\n surface: \"sandbox_provision\",\n operation: \"ensure_image_container_ready\",\n severity: \"error\",\n context: {\n sandboxType: \"image\",\n conversationId,\n credentialKey: plan.credentialKey,\n resourceKey: plan.resourceKey,\n expectedContainer: expected,\n hasVault: Boolean(plan.env || plan.mounts.length > 0),\n },\n });\n throw err;\n }\n if (actual && actual !== expected) {\n throw new Error(\n `Provisioner returned container \"${actual}\" for resource key \"${plan.resourceKey}\", expected \"${expected}\"`,\n );\n }\n };\n }\n\n private resolveMounts(\n vaultMounts: ContainerMount[],\n projection: WorkspaceProjection,\n ): ContainerMount[] {\n const protectedMounts = projection.mounts;\n for (let index = 0; index < vaultMounts.length; index += 1) {\n const vaultMount = vaultMounts[index];\n if (vaultMount === undefined) continue;\n const workspaceCollision = protectedMounts.find((protectedMount) =>\n targetsOverlap(protectedMount.target, vaultMount.target),\n );\n if (workspaceCollision) {\n throw new Error(\n `Vault mount target \"${vaultMount.target}\" overlaps protected workspace target \"${workspaceCollision.target}\"`,\n );\n }\n\n const vaultCollision = vaultMounts\n .slice(0, index)\n .find((other) => targetsOverlap(other.target, vaultMount.target));\n if (vaultCollision) {\n throw new Error(\n `Vault mount target \"${vaultMount.target}\" overlaps vault target \"${vaultCollision.target}\"`,\n );\n }\n }\n return [...protectedMounts, ...vaultMounts];\n }\n}\n\nfunction targetsOverlap(left: string, right: string): boolean {\n const a = normalizeMountTarget(left);\n const b = normalizeMountTarget(right);\n return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);\n}\n\nfunction normalizeMountTarget(value: string): string {\n const normalized = posix.normalize(value);\n return normalized.replace(/\\/+$/, \"\") || \"/\";\n}\n"]}
1
+ {"version":3,"file":"execution-resolver.js","sourceRoot":"","sources":["../../src/harness/execution-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAElC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAuB,MAAM,2BAA2B,CAAC;AACxF,OAAO,EACL,oCAAoC,EACpC,cAAc,EACd,gCAAgC,GAEjC,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAqB,MAAM,mBAAmB,CAAC;AAChF,OAAO,EAAE,+BAA+B,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC3F,OAAO,EACL,0BAA0B,EAC1B,qCAAqC,EACrC,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAMrE,MAAM,OAAO,sBAAsB;IACjC,YACU,UAAyB,EACzB,YAA0B,EAC1B,WAA+C,EAC/C,SAAoB;0BAHpB,UAAU;4BACV,YAAY;2BACZ,WAAW;yBACX,SAAS;IAChB,CAAC;IAEJ,KAAK,CAAC,OAAO,CAAC,OAAqB;QACjC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,W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C,CAAC,EAAE,KAAK,CAAC;iBACf,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,cAAc,CAAC,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;YACpE,IAAI,cAAc,EAAE,CAAC;gBACnB,MAAM,IAAI,KAAK,CACb,uBAAuB,UAAU,CAAC,MAAM,4BAA4B,cAAc,CAAC,MAAM,GAAG,CAC7F,CAAC;YACJ,CAAC;QACH,CAAC;QACD,OAAO,CAAC,GAAG,eAAe,EAAE,GAAG,WAAW,CAAC,CAAC;IAC9C,CAAC;CACF;AAED,SAAS,cAAc,CAAC,IAAY,EAAE,KAAa;IACjD,MAAM,CAAC,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,oBAAoB,CAAC,KAAa;IACzC,MAAM,UAAU,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC;AAC/C,CAAC","sourcesContent":["import { posix } from \"node:path\";\nimport type { Workspace } from \"../office/index.js\";\nimport { loadGlobalSettings } from \"../config.js\";\nimport { DockerContainerManager, type ContainerMount } from \"../sandbox/provisioner.js\";\nimport {\n assertSandboxSupportsWorkspacePolicy,\n createExecutor,\n getSandboxCredentialCapabilities,\n type SandboxConfig,\n} from \"../sandbox/index.js\";\nimport { reportUserFacingError } from \"../observability/index.js\";\nimport { normalizeSharedVaultName, type VaultManager } from \"../vault/index.js\";\nimport { allowsAmbientDefaultSharedVault, resolveVaultInjection } from \"../vault/index.js\";\nimport {\n credentialAuthorizationKey,\n legacyExactCredentialAuthorizationKey,\n runtimeResourceKey,\n scopeCloudflareSandboxId,\n} from \"../sandbox/identity.js\";\nimport { resolveWorkspaceProjection } from \"../office/projection.js\";\nimport type { WorkspaceProjection } from \"../office/types.js\";\n\nexport type { ActorContext } from \"../types.js\";\nimport type { ActorContext, ExecutionPlan } from \"../types.js\";\n\nexport class ActorExecutionResolver {\n constructor(\n private baseConfig: SandboxConfig,\n private vaultManager: VaultManager,\n private provisioner: DockerContainerManager | undefined,\n private workspace: Workspace,\n ) {}\n\n async resolve(context: ActorContext) {\n const { plan, projection } = this.resolvePlan(context);\n const executor = createExecutor(\n plan.sandboxConfig,\n plan.env,\n this.buildEnsureReadyCallback(plan, context.address.conversationId),\n );\n return {\n executor,\n pathContext: executor.getPathContext(this.workspace.root),\n projection,\n };\n }\n\n private resolvePlan(context: ActorContext): {\n plan: ExecutionPlan;\n projection: WorkspaceProjection;\n } {\n const scope = { userId: context.userId, address: context.address };\n const credentialKey = credentialAuthorizationKey(this.baseConfig, scope);\n const legacyCredentialKey = legacyExactCredentialAuthorizationKey(this.baseConfig, scope);\n const resourceKey = runtimeResourceKey(this.baseConfig, {\n userId: context.userId,\n address: context.address,\n });\n this.ensureDefaultSharedVault(credentialKey, legacyCredentialKey, context.trustModel);\n\n const vault =\n this.vaultManager.resolve(credentialKey) ??\n (legacyCredentialKey ? this.vaultManager.resolve(legacyCredentialKey) : undefined);\n const capabilities = getSandboxCredentialCapabilities(this.baseConfig.type);\n const office = this.workspace.office(context.address);\n const projection = resolveWorkspaceProjection(office);\n const injection = resolveVaultInjection({\n vault,\n capabilities,\n sandboxType: this.baseConfig.type,\n address: office.address,\n });\n const mounts = this.resolveMounts(injection.mounts, projection);\n assertSandboxSupportsWorkspacePolicy(this.baseConfig, projection.visibility, office.key);\n return {\n plan: {\n credentialKey,\n resourceKey,\n sandboxConfig: this.resolveSandboxConfig(resourceKey),\n env: injection.env,\n mounts,\n },\n projection,\n };\n }\n\n private ensureDefaultSharedVault(\n credentialKey: string,\n legacyCredentialKey: string | undefined,\n trustModel: ActorContext[\"trustModel\"],\n ): void {\n if (!allowsAmbientDefaultSharedVault({ trustModel, sandboxType: this.baseConfig.type })) return;\n if (\n this.vaultManager.hasEntry(credentialKey) ||\n (legacyCredentialKey && this.vaultManager.hasEntry(legacyCredentialKey))\n ) {\n return;\n }\n\n let profile: string | undefined;\n try {\n profile = loadGlobalSettings().sandbox?.defaultSharedVault;\n } catch {\n return;\n }\n if (!profile || normalizeSharedVaultName(profile) !== profile) return;\n this.vaultManager.copySharedVaultTo(profile, credentialKey);\n }\n\n private resolveSandboxConfig(resourceKey: string): SandboxConfig {\n if (this.baseConfig.type === \"cloudflare\") {\n return {\n type: \"cloudflare\",\n sandboxId: scopeCloudflareSandboxId(this.baseConfig.sandboxId, resourceKey),\n };\n }\n if (this.baseConfig.type !== \"image\") return this.baseConfig;\n return {\n type: \"container\",\n container: DockerContainerManager.containerName(resourceKey),\n };\n }\n\n private buildEnsureReadyCallback(\n plan: ExecutionPlan,\n conversationId: string,\n ): (() => Promise<void>) | undefined {\n if (this.baseConfig.type !== \"image\" || plan.sandboxConfig.type !== \"container\") {\n return undefined;\n }\n\n return async () => {\n const expected = plan.sandboxConfig.type === \"container\" ? plan.sandboxConfig.container : \"\";\n let actual: string | undefined;\n try {\n actual = await this.provisioner?.provision(plan.resourceKey, {\n containerName: expected,\n mounts: plan.mounts,\n conversationId,\n });\n } catch (err) {\n reportUserFacingError(err, {\n domain: \"sandbox\",\n surface: \"sandbox_provision\",\n operation: \"ensure_image_container_ready\",\n severity: \"error\",\n context: {\n sandboxType: \"image\",\n conversationId,\n credentialKey: plan.credentialKey,\n resourceKey: plan.resourceKey,\n expectedContainer: expected,\n hasVault: Boolean(plan.env || plan.mounts.length > 0),\n },\n });\n throw err;\n }\n if (actual && actual !== expected) {\n throw new Error(\n `Provisioner returned container \"${actual}\" for resource key \"${plan.resourceKey}\", expected \"${expected}\"`,\n );\n }\n };\n }\n\n private resolveMounts(\n vaultMounts: ContainerMount[],\n projection: WorkspaceProjection,\n ): ContainerMount[] {\n const protectedMounts = projection.mounts;\n for (let index = 0; index < vaultMounts.length; index += 1) {\n const vaultMount = vaultMounts[index];\n if (vaultMount === undefined) continue;\n const workspaceCollision = protectedMounts.find((protectedMount) =>\n targetsOverlap(protectedMount.target, vaultMount.target),\n );\n if (workspaceCollision) {\n throw new Error(\n `Vault mount target \"${vaultMount.target}\" overlaps protected workspace target \"${workspaceCollision.target}\"`,\n );\n }\n\n const vaultCollision = vaultMounts\n .slice(0, index)\n .find((other) => targetsOverlap(other.target, vaultMount.target));\n if (vaultCollision) {\n throw new Error(\n `Vault mount target \"${vaultMount.target}\" overlaps vault target \"${vaultCollision.target}\"`,\n );\n }\n }\n return [...protectedMounts, ...vaultMounts];\n }\n}\n\nfunction targetsOverlap(left: string, right: string): boolean {\n const a = normalizeMountTarget(left);\n const b = normalizeMountTarget(right);\n return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);\n}\n\nfunction normalizeMountTarget(value: string): string {\n const normalized = posix.normalize(value);\n return normalized.replace(/\\/+$/, \"\") || \"/\";\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/harness/prompt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAK1D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAiB,MAAM,qBAAqB,CAAC;AAEvF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAgB3D,wBAAgB,yBAAyB,CACvC,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,kBAAkB,GAC9B,MAAM,CA2BR;AAED;;;G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AG,MAAM,GAAG,UAAU,CAAC,GAC7D,MAAM,GAAG,SAAS,CAOpB;AA+MD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,wBAAwB,GAAG,MAAM,CAKzE;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,cAAc,EAAE,OAAO,EACvB,kBAAkB,EAAE,MAAM,GAAG,SAAS,EACtC,YAAY,EAAE,MAAM,GACnB,MAAM,CAkBR;AAED,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,MAAM,EACZ,kBAAkB,EAAE,MAAM,GAAG,SAAS,EACtC,WAAW,CAAC,EAAE,MAAM,GACnB,MAAM,CAYR"}
@@ -244,22 +244,20 @@ ${envDescription}
244
244
  function buildWorkspaceSkillsPrompt(input, paths) {
245
245
  const { office, projection, skills, skippedSkillLinks = [] } = input;
246
246
  const { workspaceRoot, conversationPath, scratchPath } = paths;
247
- const workspaceLayout = projection.layout === "full"
248
- ? `${workspaceRoot}/ contains the complete trusted workspace.`
249
- : projection.layout === "shared-support"
250
- ? `${workspaceRoot}/ contains shared MEMORY.md, skills/, and this conversation's directory.`
251
- : `${conversationPath}/ is the only conversation workspace mounted; global memory and skills are not available.`;
252
- const skillStorageGuidance = projection.doorPolicy === "trusted"
253
- ? `Store shared skills in \`${workspaceRoot}/skills/<name>/\` or conversation-specific skills in \`${conversationPath}/skills/<name>/\`.`
254
- : `Store skills in \`${conversationPath}/skills/<name>/\`; this office cannot access workspace-global skills.`;
247
+ const knowledgeReadOnly = projection.promptSources.globalKnowledgeReadOnly === true;
248
+ const workspaceLayout = knowledgeReadOnly
249
+ ? `${workspaceRoot}/ contains this private conversation's directory, read-only shared MEMORY.md and skills/, and read-only public/ with every public channel's office.`
250
+ : `${workspaceRoot}/ contains this public conversation's directory, shared MEMORY.md and skills/, and read-only public/ with every public channel's office.`;
251
+ const skillStorageGuidance = knowledgeReadOnly
252
+ ? `Store skills in \`${conversationPath}/skills/<name>/\`; shared \`${workspaceRoot}/skills/\` is read-only for this private office.`
253
+ : `Store shared skills in \`${workspaceRoot}/skills/<name>/\` or conversation-specific skills in \`${conversationPath}/skills/<name>/\`.`;
255
254
  return `## Workspace Layout
256
255
  ${workspaceLayout}
257
- ${projection.layout === "conversation"
258
- ? `${conversationPath}/ # This conversation`
259
- : `${workspaceRoot}/
260
- ├── MEMORY.md # Global memory (all conversations)
261
- ├── skills/ # Global CLI tools you create
262
- └── ${office.key}/ # This conversation`}
256
+ ${workspaceRoot}/
257
+ ├── MEMORY.md # Shared memory${knowledgeReadOnly ? " (read-only here)" : " (all public conversations)"}
258
+ ├── skills/ # Shared CLI tools${knowledgeReadOnly ? " (read-only here)" : " you create"}
259
+ ├── public/<office-key>/ # Other public channels' offices (read-only)
260
+ └── ${office.key}/ # This conversation
263
261
  ├── MEMORY.md # Conversation-specific memory
264
262
  ├── log.jsonl # Human-readable message history (no tool results)
265
263
  ├── sessions/ # Structured session history used for context reconstruction
@@ -300,13 +298,11 @@ function buildOperatingPrompt(input, paths) {
300
298
  const { memory, projection, sandboxConfig } = input;
301
299
  const { workspaceRoot, conversationPath } = paths;
302
300
  const isContainerLike = sandboxConfig.type === "container" || sandboxConfig.type === "image";
303
- const globalMemoryReadOnly = projection.promptSources.globalMemoryReadOnly === true;
304
- const memoryGuidance = projection.doorPolicy === "trusted"
305
- ? globalMemoryReadOnly
306
- ? `\`${workspaceRoot}/MEMORY.md\` is shared workspace memory mounted read-only for this office (private visibility): you can read what other offices have learned, but writes to it are rejected. Write everything you learn here to \`${conversationPath}/MEMORY.md\` instead; it never leaves this conversation.`
307
- : `Write important shared knowledge to \`${workspaceRoot}/MEMORY.md\` and conversation-specific knowledge to \`${conversationPath}/MEMORY.md\`.`
308
- : `Write durable knowledge only to \`${conversationPath}/MEMORY.md\`; this office cannot access workspace-global memory.`;
309
- const systemLogPath = projection.layout === "conversation"
301
+ const globalMemoryReadOnly = projection.promptSources.globalKnowledgeReadOnly === true;
302
+ const memoryGuidance = globalMemoryReadOnly
303
+ ? `\`${workspaceRoot}/MEMORY.md\` is shared workspace memory mounted read-only for this private office: you can read what public channels have learned, but writes to it are rejected. Write everything you learn here to \`${conversationPath}/MEMORY.md\` instead; it never leaves this conversation.`
304
+ : `Write important shared knowledge to \`${workspaceRoot}/MEMORY.md\` and conversation-specific knowledge to \`${conversationPath}/MEMORY.md\`.`;
305
+ const systemLogPath = globalMemoryReadOnly
310
306
  ? `${conversationPath}/SYSTEM.md`
311
307
  : `${workspaceRoot}/SYSTEM.md`;
312
308
  return `## Events
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../src/harness/prompt.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGtF,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAGhE,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AAEjC,SAAS,gBAAgB,CAAC,IAAY,EAAE,IAAY;IAClD,MAAM,YAAY,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC1C,OAAO,CACL,YAAY,KAAK,EAAE;QACnB,CAAC,YAAY,KAAK,IAAI,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,CAC7F,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,IAAY;IACtC,OAAO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CAAC;wBACS,YAAY;gBACpB,kBAAkB;;2CAES,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,IAAY,EACZ,kBAAsC,EACtC,WAAoB;IAEpB,IAAI,CAAC,kBAAkB;QAAE,OAAO,IAAI,CAAC;IACrC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;IAC/B,MAAM,YAAY,GAAG,iBAAiB,kBAAkB,GAAG,CAAC;IAC5D,6EAA6E;IAC7E,4EAA4E;IAC5E,MAAM,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,YAAY,eAAe,WAAW,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IACxF,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1C,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC;QACzC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE;QAClD,CAAC,CAAC,OAAO,CAAC;IACZ,OAAO,GAAG,IAAI,OAAO,MAAM,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { Office } from \"../office/index.js\";\nimport type { ImageContent } from \"@earendil-works/pi-ai\";\nimport { existsSync, lstatSync } from \"node:fs\";\nimport { chmod, mkdtemp, rm, writeFile, readFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, isAbsolute, join, posix, relative, resolve, sep } from \"node:path\";\nimport type { ConversationMessage } from \"../adapter.js\";\nimport type { Executor, RuntimePathContext, SandboxConfig } from \"../sandbox/index.js\";\nimport { formatSkillsForPrompt } from \"./skills.js\";\nimport type { WorkspaceProjection } from \"../office/types.js\";\nimport { formatHistoryLine } from \"../sessions/history-line.js\";\nimport type { BuildSystemPromptOptions } from \"./types.js\";\n\nimport * as log from \"../log.js\";\n\nfunction isWithinPathRoot(path: string, root: string): boolean {\n const pathRelative = relative(root, path);\n return (\n pathRelative === \"\" ||\n (pathRelative !== \"..\" && !pathRelative.startsWith(`..${sep}`) && !isAbsolute(pathRelative))\n );\n}\n\nfunction hasParentTraversal(path: string): boolean {\n return path.split(/[\\\\/]/).some((segment) => segment === \"..\");\n}\n\nexport function translateAttachPathToHost(\n filePath: string,\n pathContext: RuntimePathContext,\n): string {\n if (!pathContext.runtimeToHostPath) {\n throw new Error(\n \"Cannot attach files: this sandbox has no host-backed runtime path mapping; attachments are unavailable for remote sandboxes such as Cloudflare\",\n );\n }\n if (hasParentTraversal(filePath)) {\n throw new Error(\"Cannot attach files: parent-directory traversal is not allowed\");\n }\n\n const runtimeRoot = resolve(pathContext.runtimeWorkspaceRoot);\n const runtimePath = posix.isAbsolute(filePath)\n ? filePath\n : posix.join(pathContext.runtimeWorkspaceRoot, filePath);\n const normalizedRuntimePath = resolve(runtimePath);\n if (!isWithinPathRoot(normalizedRuntimePath, runtimeRoot)) {\n throw new Error(\"Cannot attach files: path must be within the runtime workspace\");\n }\n\n const hostRoot = resolve(pathContext.hostWorkspaceRoot);\n const translatedPath = pathContext.runtimeToHostPath(runtimePath);\n const hostPath = resolve(translatedPath);\n if (!isWithinPathRoot(hostPath, hostRoot)) {\n throw new Error(\"Cannot attach files: path must be within the host workspace\");\n }\n\n return hostPath;\n}\n\n/**\n * Normalize an attachment path using runtime lexical semantics only. The\n * executor remains the authority for reading the resulting runtime path.\n */\nexport function normalizeAttachRuntimePath(filePath: string, runtimeWorkspaceRoot: string): string {\n if (hasParentTraversal(filePath)) {\n throw new Error(\"Cannot attach files: parent-directory traversal is not allowed\");\n }\n\n const runtimeRoot = posix.resolve(runtimeWorkspaceRoot);\n const runtimePath = posix.resolve(runtimeRoot, filePath);\n const runtimeRelativePath = posix.relative(runtimeRoot, runtimePath);\n if (\n runtimeRelativePath === \"..\" ||\n runtimeRelativePath.startsWith(\"../\") ||\n posix.isAbsolute(runtimeRelativePath)\n ) {\n throw new Error(\"Cannot attach files: path must be within the runtime workspace\");\n }\n return runtimePath;\n}\n\nexport async function withStagedRuntimeFile(\n executor: Executor,\n runtimePath: string,\n upload: (stagedPath: string) => Promise<void>,\n): Promise<void> {\n const content = Buffer.from(await executor.readFileBase64(runtimePath), \"base64\");\n let stagingDir: string | undefined;\n try {\n stagingDir = await mkdtemp(join(tmpdir(), \"mikan-upload-\"));\n await chmod(stagingDir, 0o700);\n const stagedPath = join(stagingDir, basename(runtimePath));\n await writeFile(stagedPath, content, { mode: 0o600, flag: \"wx\" });\n await chmod(stagedPath, 0o600);\n await upload(stagedPath);\n } finally {\n if (stagingDir) await rm(stagingDir, { recursive: true, force: true });\n }\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nasync function collectMessageAttachments(\n message: ConversationMessage,\n workspacePath: string,\n pathContext?: RuntimePathContext,\n readAttachment?: (runtimePath: string) => Promise<string>,\n): Promise<{ imageAttachments: ImageContent[]; nonImagePaths: string[] }> {\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const attachment of message.attachments || []) {\n const runtimePath = `${workspacePath}/${attachment.localPath}`;\n const hostPath = pathContext?.runtimeToHostPath?.(runtimePath) ?? runtimePath;\n const mimeType = IMAGE_MIME_TYPES[attachment.localPath.toLowerCase().split(\".\").pop() || \"\"];\n\n if (mimeType && existsSync(hostPath) && readAttachment) {\n try {\n imageAttachments.push({\n type: \"image\",\n mimeType,\n data: await readAttachment(runtimePath),\n });\n } catch {\n nonImagePaths.push(runtimePath);\n }\n } else {\n nonImagePaths.push(runtimePath);\n }\n }\n\n return { imageAttachments, nonImagePaths };\n}\n\nfunction buildRuntimePaths(runtimeWorkspaceRoot: string, office: Office) {\n const workspaceRoot = runtimeWorkspaceRoot.replace(/\\/+$/, \"\") || \"/\";\n const conversationPath = posix.join(workspaceRoot, office.key);\n return {\n workspaceRoot,\n conversationPath,\n scratchPath: posix.join(conversationPath, \"scratch\"),\n };\n}\nexport type { BuildSystemPromptOptions } from \"./types.js\";\n\nexport async function buildPromptPayload(\n message: ConversationMessage,\n workspacePath: string,\n pathContext?: RuntimePathContext,\n readAttachment?: (runtimePath: string) => Promise<string>,\n): Promise<{\n userMessage: string;\n imageAttachments: ImageContent[];\n}> {\n let userMessage = formatHistoryLine({\n date: new Date(),\n userName: message.userName,\n threadTs: message.threadTs,\n text: message.text,\n });\n const { imageAttachments, nonImagePaths } = await collectMessageAttachments(\n message,\n workspacePath,\n pathContext,\n readAttachment,\n );\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n return { userMessage, imageAttachments };\n}\n\n/** A memory file under its prompt heading; absent, empty and unreadable all yield nothing. */\nasync function memorySection(\n path: string | undefined,\n heading: string,\n label: string,\n): Promise<string | undefined> {\n if (!path || !isRegularFile(path)) return undefined;\n try {\n const content = (await readFile(path, \"utf-8\")).trim();\n return content ? `### ${heading}\\n${content}` : undefined;\n } catch (error) {\n log.logWarning(`Failed to read ${label}`, `${path}: ${error}`);\n return undefined;\n }\n}\n\nexport async function getMemory(projection: WorkspaceProjection): Promise<string> {\n const { globalMemoryPath, conversationMemoryPath } = projection.promptSources;\n const sections = await Promise.all([\n memorySection(globalMemoryPath, \"Global Workspace Memory\", \"workspace memory\"),\n memorySection(conversationMemoryPath, \"Conversation-Specific Memory\", \"conversation memory\"),\n ]);\n const parts = sections.filter((section) => section !== undefined);\n return parts.length > 0 ? parts.join(\"\\n\\n\") : \"(no working memory yet)\";\n}\n\nfunction isRegularFile(path: string): boolean {\n try {\n const stats = lstatSync(path);\n return stats.isFile() && !stats.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nfunction buildEnvDescription(sandboxType: SandboxConfig[\"type\"], workspaceRoot: string): string {\n switch (sandboxType) {\n case \"image\":\n return `You are running inside a managed per-conversation container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`;\n case \"container\":\n return `You are running inside a shared container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the container's package manager\n- Your changes persist across sessions`;\n case \"cloudflare\":\n return `You are running through a Cloudflare Sandbox bridge.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`;\n default:\n return `You are running directly on the host machine.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${process.cwd()}\n- Be careful with system modifications`;\n }\n}\n\nexport function resolveTriggerAttribution(\n message: Pick<ConversationMessage, \"id\" | \"text\" | \"userName\">,\n): string | undefined {\n const eventTextMatch = message.text.match(/^\\[EVENT:([^:]+):/);\n if (eventTextMatch) return `[event: ${eventTextMatch[1]}]`;\n const eventIdMatch = message.id.match(/^event:([^:]+)/);\n if (eventIdMatch) return `[event: ${eventIdMatch[1]}]`;\n if (message.userName) return `@${message.userName}`;\n return undefined;\n}\n\ntype RuntimePromptPaths = ReturnType<typeof buildRuntimePaths>;\n\n/** A tab-separated directory table, or a placeholder when the directory has not loaded. */\nfunction mappingTable(rows: string[], empty: string): string {\n return rows.length > 0 ? rows.join(\"\\n\") : empty;\n}\n\nfunction buildContextPrompt(input: BuildSystemPromptOptions, paths: RuntimePromptPaths): string {\n const { platform, sandboxConfig } = input;\n const { workspaceRoot, conversationPath, scratchPath } = paths;\n const channelMappings = mappingTable(\n platform.channels.map((c) => `${c.id}\\t#${c.name}`),\n \"(no channels loaded)\",\n );\n const userMappings = mappingTable(\n platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`),\n \"(no users loaded)\",\n );\n const envDescription = buildEnvDescription(sandboxConfig.type, workspaceRoot);\n const slackBlockKitInstructions =\n platform.name === \"slack\"\n ? `\n## Slack Tasks\n- In top-level Slack DMs, use start_task for multi-step investigations, changes/tests, or long waits so the user can keep chatting. Write a short, casual acknowledgement like a helpful colleague (e.g. 好,我來整理一下,弄好再通知你), not a formal restatement of the task. Do not invent an ETA. Separately provide a self-contained task with constraints and attachment paths. Call it alone before executing the work.\n- For questions about task progress, always call task_status before answering. Its observations are the only authority for current task status. Never infer progress, completion, or an ETA from elapsed time or your earlier promises. acknowledgement is only the original task description, NOT live progress. Only currentTool describes a current operation; if absent, say it is still running without inventing a phase. Never translate subagent into a more specific activity than the observation supports. If multiple tasks match, ask which one. If status is unknown, say so. For status-only questions, report the task_status observation directly; do not read session files, run shell probes, or repeat the investigation just to reconfirm it. Only inspect the result content when the user asks for that content.\n- In a thread, continue the task directly; do not hand it off again. Other platforms and shared channels do not support start_task yet.\n\n## Slack Rendering\n- The Slack adapter renders responses natively from standard Markdown. Answer in normal Markdown/GFM.\n- Markdown pipe tables are rendered as native Slack tables.\n- For interactive elements (buttons, select menus), use the slack_blockkit tool; user interactions arrive as \"[Slack action] <action_id>: <value>\" messages.\n`\n : \"\";\n\n return `You are mikan, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older human-readable history beyond your context, search \\`log.jsonl\\` (contains user messages and your final responses, but not tool results).\n- Structured session history with tool results lives in \\`${conversationPath}/sessions/\\`.\n- The active top-level session is selected by \\`${conversationPath}/sessions/current\\`, which points to a timestamped \\`.jsonl\\` file in the same directory.\n- Scoped/thread sessions use fixed files at \\`${conversationPath}/sessions/<scope_id>.jsonl\\` (for example \\`${conversationPath}/sessions/1777386320.800769.jsonl\\`).\n- If a user asks about something that should exist in conversation history but is not found in the current context window, do not answer \"I don't know\" or \"I don't have that\". Instead, search the thread session, top-level session, and \\`log.jsonl\\` before responding.\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.\n${platform.formattingGuide}${slackBlockKitInstructions}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, write <@userName> using the exact userName from the Users table above (e.g., <@mario>). Never invent handles from other platforms (GitHub, email); the platform adapter converts <@userName> to the platform's native mention form.\n\n## Environment\n${envDescription}\n- Default place for clones, downloads, and experiments: ${scratchPath}\n- Do not use host-only paths unless you are running in host mode and verified they exist.`;\n}\n\nfunction buildWorkspaceSkillsPrompt(\n input: BuildSystemPromptOptions,\n paths: RuntimePromptPaths,\n): string {\n const { office, projection, skills, skippedSkillLinks = [] } = input;\n const { workspaceRoot, conversationPath, scratchPath } = paths;\n const workspaceLayout =\n projection.layout === \"full\"\n ? `${workspaceRoot}/ contains the complete trusted workspace.`\n : projection.layout === \"shared-support\"\n ? `${workspaceRoot}/ contains shared MEMORY.md, skills/, and this conversation's directory.`\n : `${conversationPath}/ is the only conversation workspace mounted; global memory and skills are not available.`;\n const skillStorageGuidance =\n projection.doorPolicy === \"trusted\"\n ? `Store shared skills in \\`${workspaceRoot}/skills/<name>/\\` or conversation-specific skills in \\`${conversationPath}/skills/<name>/\\`.`\n : `Store skills in \\`${conversationPath}/skills/<name>/\\`; this office cannot access workspace-global skills.`;\n\n return `## Workspace Layout\n${workspaceLayout}\n${\n projection.layout === \"conversation\"\n ? `${conversationPath}/ # This conversation`\n : `${workspaceRoot}/\n├── MEMORY.md # Global memory (all conversations)\n├── skills/ # Global CLI tools you create\n└── ${office.key}/ # This conversation`\n}\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Human-readable message history (no tool results)\n ├── sessions/ # Structured session history used for context reconstruction\n │ ├── current # Active top-level session pointer\n │ ├── <timestamp>_<id>.jsonl # Top-level session files\n │ └── <scope_id>.jsonl # Scoped thread/reply session files\n ├── attachments/ # User-shared files\n ├── scratch/ # Working directory for clones/downloads/experiments: ${scratchPath}\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\n${skillStorageGuidance}\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}${\n skippedSkillLinks.length > 0\n ? `\\n\\nNote: these skill entries were skipped because they are symlinks, which the host never follows when reading this conversation's skills: ${skippedSkillLinks.join(\", \")}. Replace each with a real file or directory (for example \\`cp -rL\\`) to load it.`\n : \"\"\n }`;\n}\n\nfunction buildOperatingPrompt(input: BuildSystemPromptOptions, paths: RuntimePromptPaths): string {\n const { memory, projection, sandboxConfig } = input;\n const { workspaceRoot, conversationPath } = paths;\n const isContainerLike = sandboxConfig.type === \"container\" || sandboxConfig.type === \"image\";\n const globalMemoryReadOnly = projection.promptSources.globalMemoryReadOnly === true;\n const memoryGuidance =\n projection.doorPolicy === \"trusted\"\n ? globalMemoryReadOnly\n ? `\\`${workspaceRoot}/MEMORY.md\\` is shared workspace memory mounted read-only for this office (private visibility): you can read what other offices have learned, but writes to it are rejected. Write everything you learn here to \\`${conversationPath}/MEMORY.md\\` instead; it never leaves this conversation.`\n : `Write important shared knowledge to \\`${workspaceRoot}/MEMORY.md\\` and conversation-specific knowledge to \\`${conversationPath}/MEMORY.md\\`.`\n : `Write durable knowledge only to \\`${conversationPath}/MEMORY.md\\`; this office cannot access workspace-global memory.`;\n const systemLogPath =\n projection.layout === \"conversation\"\n ? `${conversationPath}/SYSTEM.md`\n : `${workspaceRoot}/SYSTEM.md`;\n\n return `## Events\nUse the \\`event\\` tool to schedule immediate, one-shot, or periodic follow-ups. It is the only way to manage this conversation's scheduled events: they live host-side, not in the workspace, and fill routing fields for the current conversation automatically.\n\nWrite event \\`text\\` as a self-contained future task with needed context, tone, and constraints because events do not inherit normal conversation history.\n\nFor one-shot reminders, include a timezone offset in \\`at\\`. For periodic events, use a cron schedule plus IANA timezone; assume ${Intl.DateTimeFormat().resolvedOptions().timeZone} when users omit timezone.\n\nWhen events trigger, messages are prefixed like \\`[EVENT:filename:type:time]\\`. Immediate and one-shot events auto-delete after triggering; periodic events persist until deleted.\n\nFor periodic events where there's nothing to report, respond with exactly \\`[SILENT]\\`.\n\n## Memory\n${memoryGuidance}\nUpdate it when you learn something important or when asked to remember something.\n\nMemory is a compact, revisable orientation anchor backed by conversation evidence, not a transcript or final truth.\nWhen memory conflicts with newer conversation evidence, prefer the newer evidence.\nFor mutable external state, query the Live source or current API in this run and prefer that fresh result over memory or older API observations. If the source cannot be queried successfully, say that the current state could not be verified; do not fall back to memory as current truth. A later Dream can revise the anchor.\n\nBefore writing an entry, ask whether it is a stable fact (a decision, a convention, an owner,\na recurring constraint) or a one-off event that belongs in \\`log.jsonl\\` instead; only write\nthe former. Keep entries short — a long running log of events crowds out the facts that matter.\n\nQuerying, correcting, and forgetting memory are normal, expected requests, not edge cases:\n- If asked what you remember, read the memory file(s) above and list the entries plainly.\n- If asked to correct or forget something, edit the relevant MEMORY.md to remove or update\n that entry, then confirm what changed.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${systemLogPath} to log all environment modifications:\n- Installed packages (apt install, npm install, uv pip install)\n- Environment variables set\n- Config files modified (~/.gitconfig, cron jobs, etc.)\n- Skill dependencies installed\n\nUpdate this file whenever you modify the environment. On fresh container, read it first to restore your setup.\n\n## Log Queries (for older history)\nFormat: \\`{\"date\":\"...\",\"ts\":\"...\",\"user\":\"...\",\"userName\":\"...\",\"text\":\"...\",\"isMessagingBot\":false}\\`\nThe log contains user messages and your final responses (not tool calls/results).\nUse \\`log.jsonl\\` for quick grep-style history. Use \\`${conversationPath}/sessions/\\` when you need structured turns, tool outputs, or thread/session lineage.\n${isContainerLike ? \"Install jq: apt-get install jq\" : \"\"}\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\n# Inspect top-level session pointer and available session files\ncat sessions/current\nls -1 sessions/\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- event: Schedule immediate, one-shot, or periodic follow-ups\n- sandbox: Inspect or temporarily adjust sandbox limits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n const paths = buildRuntimePaths(input.workspacePath, input.office);\n // Per-turn instructions stay in buildTurnInstructions(), keeping this prompt\n // byte-stable across a conversation so the provider cache remains warm.\n return `${buildContextPrompt(input, paths)}\\n\\n${buildWorkspaceSkillsPrompt(input, paths)}\\n\\n${buildOperatingPrompt(input, paths)}`;\n}\n\n/**\n * Instructions that vary per turn (event-trigger mode, response attribution).\n * These are delivered with the user message rather than baked into the system\n * prompt, so the system prompt stays cache-stable across a conversation's turns\n * (in a multi-user channel the attribution line alone changes every turn).\n * Returns an empty string when the turn needs no special framing.\n */\nexport function buildTurnInstructions(\n isEventTrigger: boolean,\n triggerAttribution: string | undefined,\n platformName: string,\n): string {\n const parts: string[] = [];\n if (isEventTrigger) {\n parts.push(`## Event Trigger Mode\n- You are handling a scheduled/background event, not opening a brand new chat with a stranger.\n- Treat the incoming user message as a self-contained task prepared by an earlier run.\n- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.\n- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.\n- If the event text includes tone, brevity, or language instructions, follow them literally.`);\n }\n if (triggerAttribution) {\n parts.push(`## Attribution\nAlways end your final ${platformName} response and any GitHub issue/PR comments or descriptions you write via tools with:\n_Triggered by ${triggerAttribution}_\n\nDo not add this to \\`[SILENT]\\` responses.`);\n }\n return parts.join(\"\\n\\n\");\n}\n\nexport function appendTriggerAttribution(\n text: string,\n triggerAttribution: string | undefined,\n sessionLink?: string,\n): string {\n if (!triggerAttribution) return text;\n const trimmed = text.trimEnd();\n const legacySuffix = `_Triggered by ${triggerAttribution}_`;\n // Slack mrkdwn italics cannot span a URL — a `_..._` wrapping a link renders\n // the underscores literally. Keep the session link outside the italic span.\n const suffix = sessionLink ? `${legacySuffix} · session: ${sessionLink}` : legacySuffix;\n if (trimmed.endsWith(suffix)) return text;\n const body = trimmed.endsWith(legacySuffix)\n ? trimmed.slice(0, -legacySuffix.length).trimEnd()\n : trimmed;\n return `${body}\\n\\n${suffix}`;\n}\n"]}
1
+ {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../src/harness/prompt.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGtF,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAGhE,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AAEjC,SAAS,gBAAgB,CAAC,IAAY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pB,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,IAAI,cAAc,EAAE,CAAC;QACnB,KAAK,CAAC,IAAI,CAAC;;;;;6FAK8E,CAAC,CAAC;IAC7F,CAAC;IACD,IAAI,kBAAkB,EAAE,CAAC;QACvB,KAAK,CAAC,IAAI,CAAC;wBACS,YAAY;gBACpB,kBAAkB;;2CAES,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC5B,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,IAAY,EACZ,kBAAsC,EACtC,WAAoB;IAEpB,IAAI,CAAC,kBAAkB;QAAE,OAAO,IAAI,CAAC;IACrC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;IAC/B,MAAM,YAAY,GAAG,iBAAiB,kBAAkB,GAAG,CAAC;IAC5D,6EAA6E;IAC7E,4EAA4E;IAC5E,MAAM,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,YAAY,eAAe,WAAW,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC;IACxF,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1C,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC;QACzC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE;QAClD,CAAC,CAAC,OAAO,CAAC;IACZ,OAAO,GAAG,IAAI,OAAO,MAAM,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { Office } from \"../office/index.js\";\nimport type { ImageContent } from \"@earendil-works/pi-ai\";\nimport { existsSync, lstatSync } from \"node:fs\";\nimport { chmod, mkdtemp, rm, writeFile, readFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, isAbsolute, join, posix, relative, resolve, sep } from \"node:path\";\nimport type { ConversationMessage } from \"../adapter.js\";\nimport type { Executor, RuntimePathContext, SandboxConfig } from \"../sandbox/index.js\";\nimport { formatSkillsForPrompt } from \"./skills.js\";\nimport type { WorkspaceProjection } from \"../office/types.js\";\nimport { formatHistoryLine } from \"../sessions/history-line.js\";\nimport type { BuildSystemPromptOptions } from \"./types.js\";\n\nimport * as log from \"../log.js\";\n\nfunction isWithinPathRoot(path: string, root: string): boolean {\n const pathRelative = relative(root, path);\n return (\n pathRelative === \"\" ||\n (pathRelative !== \"..\" && !pathRelative.startsWith(`..${sep}`) && !isAbsolute(pathRelative))\n );\n}\n\nfunction hasParentTraversal(path: string): boolean {\n return path.split(/[\\\\/]/).some((segment) => segment === \"..\");\n}\n\nexport function translateAttachPathToHost(\n filePath: string,\n pathContext: RuntimePathContext,\n): string {\n if (!pathContext.runtimeToHostPath) {\n throw new Error(\n \"Cannot attach files: this sandbox has no host-backed runtime path mapping; attachments are unavailable for remote sandboxes such as Cloudflare\",\n );\n }\n if (hasParentTraversal(filePath)) {\n throw new Error(\"Cannot attach files: parent-directory traversal is not allowed\");\n }\n\n const runtimeRoot = resolve(pathContext.runtimeWorkspaceRoot);\n const runtimePath = posix.isAbsolute(filePath)\n ? filePath\n : posix.join(pathContext.runtimeWorkspaceRoot, filePath);\n const normalizedRuntimePath = resolve(runtimePath);\n if (!isWithinPathRoot(normalizedRuntimePath, runtimeRoot)) {\n throw new Error(\"Cannot attach files: path must be within the runtime workspace\");\n }\n\n const hostRoot = resolve(pathContext.hostWorkspaceRoot);\n const translatedPath = pathContext.runtimeToHostPath(runtimePath);\n const hostPath = resolve(translatedPath);\n if (!isWithinPathRoot(hostPath, hostRoot)) {\n throw new Error(\"Cannot attach files: path must be within the host workspace\");\n }\n\n return hostPath;\n}\n\n/**\n * Normalize an attachment path using runtime lexical semantics only. The\n * executor remains the authority for reading the resulting runtime path.\n */\nexport function normalizeAttachRuntimePath(filePath: string, runtimeWorkspaceRoot: string): string {\n if (hasParentTraversal(filePath)) {\n throw new Error(\"Cannot attach files: parent-directory traversal is not allowed\");\n }\n\n const runtimeRoot = posix.resolve(runtimeWorkspaceRoot);\n const runtimePath = posix.resolve(runtimeRoot, filePath);\n const runtimeRelativePath = posix.relative(runtimeRoot, runtimePath);\n if (\n runtimeRelativePath === \"..\" ||\n runtimeRelativePath.startsWith(\"../\") ||\n posix.isAbsolute(runtimeRelativePath)\n ) {\n throw new Error(\"Cannot attach files: path must be within the runtime workspace\");\n }\n return runtimePath;\n}\n\nexport async function withStagedRuntimeFile(\n executor: Executor,\n runtimePath: string,\n upload: (stagedPath: string) => Promise<void>,\n): Promise<void> {\n const content = Buffer.from(await executor.readFileBase64(runtimePath), \"base64\");\n let stagingDir: string | undefined;\n try {\n stagingDir = await mkdtemp(join(tmpdir(), \"mikan-upload-\"));\n await chmod(stagingDir, 0o700);\n const stagedPath = join(stagingDir, basename(runtimePath));\n await writeFile(stagedPath, content, { mode: 0o600, flag: \"wx\" });\n await chmod(stagedPath, 0o600);\n await upload(stagedPath);\n } finally {\n if (stagingDir) await rm(stagingDir, { recursive: true, force: true });\n }\n}\n\nconst IMAGE_MIME_TYPES: Record<string, string> = {\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nasync function collectMessageAttachments(\n message: ConversationMessage,\n workspacePath: string,\n pathContext?: RuntimePathContext,\n readAttachment?: (runtimePath: string) => Promise<string>,\n): Promise<{ imageAttachments: ImageContent[]; nonImagePaths: string[] }> {\n const imageAttachments: ImageContent[] = [];\n const nonImagePaths: string[] = [];\n\n for (const attachment of message.attachments || []) {\n const runtimePath = `${workspacePath}/${attachment.localPath}`;\n const hostPath = pathContext?.runtimeToHostPath?.(runtimePath) ?? runtimePath;\n const mimeType = IMAGE_MIME_TYPES[attachment.localPath.toLowerCase().split(\".\").pop() || \"\"];\n\n if (mimeType && existsSync(hostPath) && readAttachment) {\n try {\n imageAttachments.push({\n type: \"image\",\n mimeType,\n data: await readAttachment(runtimePath),\n });\n } catch {\n nonImagePaths.push(runtimePath);\n }\n } else {\n nonImagePaths.push(runtimePath);\n }\n }\n\n return { imageAttachments, nonImagePaths };\n}\n\nfunction buildRuntimePaths(runtimeWorkspaceRoot: string, office: Office) {\n const workspaceRoot = runtimeWorkspaceRoot.replace(/\\/+$/, \"\") || \"/\";\n const conversationPath = posix.join(workspaceRoot, office.key);\n return {\n workspaceRoot,\n conversationPath,\n scratchPath: posix.join(conversationPath, \"scratch\"),\n };\n}\nexport type { BuildSystemPromptOptions } from \"./types.js\";\n\nexport async function buildPromptPayload(\n message: ConversationMessage,\n workspacePath: string,\n pathContext?: RuntimePathContext,\n readAttachment?: (runtimePath: string) => Promise<string>,\n): Promise<{\n userMessage: string;\n imageAttachments: ImageContent[];\n}> {\n let userMessage = formatHistoryLine({\n date: new Date(),\n userName: message.userName,\n threadTs: message.threadTs,\n text: message.text,\n });\n const { imageAttachments, nonImagePaths } = await collectMessageAttachments(\n message,\n workspacePath,\n pathContext,\n readAttachment,\n );\n\n if (nonImagePaths.length > 0) {\n userMessage += `\\n\\n<slack_attachments>\\n${nonImagePaths.join(\"\\n\")}\\n</slack_attachments>`;\n }\n\n return { userMessage, imageAttachments };\n}\n\n/** A memory file under its prompt heading; absent, empty and unreadable all yield nothing. */\nasync function memorySection(\n path: string | undefined,\n heading: string,\n label: string,\n): Promise<string | undefined> {\n if (!path || !isRegularFile(path)) return undefined;\n try {\n const content = (await readFile(path, \"utf-8\")).trim();\n return content ? `### ${heading}\\n${content}` : undefined;\n } catch (error) {\n log.logWarning(`Failed to read ${label}`, `${path}: ${error}`);\n return undefined;\n }\n}\n\nexport async function getMemory(projection: WorkspaceProjection): Promise<string> {\n const { globalMemoryPath, conversationMemoryPath } = projection.promptSources;\n const sections = await Promise.all([\n memorySection(globalMemoryPath, \"Global Workspace Memory\", \"workspace memory\"),\n memorySection(conversationMemoryPath, \"Conversation-Specific Memory\", \"conversation memory\"),\n ]);\n const parts = sections.filter((section) => section !== undefined);\n return parts.length > 0 ? parts.join(\"\\n\\n\") : \"(no working memory yet)\";\n}\n\nfunction isRegularFile(path: string): boolean {\n try {\n const stats = lstatSync(path);\n return stats.isFile() && !stats.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nfunction buildEnvDescription(sandboxType: SandboxConfig[\"type\"], workspaceRoot: string): string {\n switch (sandboxType) {\n case \"image\":\n return `You are running inside a managed per-conversation container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the image's package manager\n- Your changes persist for this user's container until it is recreated`;\n case \"container\":\n return `You are running inside a shared container.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Install tools with the container's package manager\n- Your changes persist across sessions`;\n case \"cloudflare\":\n return `You are running through a Cloudflare Sandbox bridge.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${workspaceRoot}\n- Your commands run in a remote container managed by Cloudflare\n- Important: the remote filesystem is not automatically synced back to the host workspace`;\n default:\n return `You are running directly on the host machine.\n- Runtime workspace root: ${workspaceRoot}\n- Bash commands start in: ${process.cwd()}\n- Be careful with system modifications`;\n }\n}\n\nexport function resolveTriggerAttribution(\n message: Pick<ConversationMessage, \"id\" | \"text\" | \"userName\">,\n): string | undefined {\n const eventTextMatch = message.text.match(/^\\[EVENT:([^:]+):/);\n if (eventTextMatch) return `[event: ${eventTextMatch[1]}]`;\n const eventIdMatch = message.id.match(/^event:([^:]+)/);\n if (eventIdMatch) return `[event: ${eventIdMatch[1]}]`;\n if (message.userName) return `@${message.userName}`;\n return undefined;\n}\n\ntype RuntimePromptPaths = ReturnType<typeof buildRuntimePaths>;\n\n/** A tab-separated directory table, or a placeholder when the directory has not loaded. */\nfunction mappingTable(rows: string[], empty: string): string {\n return rows.length > 0 ? rows.join(\"\\n\") : empty;\n}\n\nfunction buildContextPrompt(input: BuildSystemPromptOptions, paths: RuntimePromptPaths): string {\n const { platform, sandboxConfig } = input;\n const { workspaceRoot, conversationPath, scratchPath } = paths;\n const channelMappings = mappingTable(\n platform.channels.map((c) => `${c.id}\\t#${c.name}`),\n \"(no channels loaded)\",\n );\n const userMappings = mappingTable(\n platform.users.map((u) => `${u.id}\\t@${u.userName}\\t${u.displayName}`),\n \"(no users loaded)\",\n );\n const envDescription = buildEnvDescription(sandboxConfig.type, workspaceRoot);\n const slackBlockKitInstructions =\n platform.name === \"slack\"\n ? `\n## Slack Tasks\n- In top-level Slack DMs, use start_task for multi-step investigations, changes/tests, or long waits so the user can keep chatting. Write a short, casual acknowledgement like a helpful colleague (e.g. 好,我來整理一下,弄好再通知你), not a formal restatement of the task. Do not invent an ETA. Separately provide a self-contained task with constraints and attachment paths. Call it alone before executing the work.\n- For questions about task progress, always call task_status before answering. Its observations are the only authority for current task status. Never infer progress, completion, or an ETA from elapsed time or your earlier promises. acknowledgement is only the original task description, NOT live progress. Only currentTool describes a current operation; if absent, say it is still running without inventing a phase. Never translate subagent into a more specific activity than the observation supports. If multiple tasks match, ask which one. If status is unknown, say so. For status-only questions, report the task_status observation directly; do not read session files, run shell probes, or repeat the investigation just to reconfirm it. Only inspect the result content when the user asks for that content.\n- In a thread, continue the task directly; do not hand it off again. Other platforms and shared channels do not support start_task yet.\n\n## Slack Rendering\n- The Slack adapter renders responses natively from standard Markdown. Answer in normal Markdown/GFM.\n- Markdown pipe tables are rendered as native Slack tables.\n- For interactive elements (buttons, select menus), use the slack_blockkit tool; user interactions arrive as \"[Slack action] <action_id>: <value>\" messages.\n`\n : \"\";\n\n return `You are mikan, a ${platform.name} bot assistant. Be concise. No emojis.\n\n## Context\n- For current date/time, use: date\n- You have access to previous conversation context including tool results from prior turns.\n- For older human-readable history beyond your context, search \\`log.jsonl\\` (contains user messages and your final responses, but not tool results).\n- Structured session history with tool results lives in \\`${conversationPath}/sessions/\\`.\n- The active top-level session is selected by \\`${conversationPath}/sessions/current\\`, which points to a timestamped \\`.jsonl\\` file in the same directory.\n- Scoped/thread sessions use fixed files at \\`${conversationPath}/sessions/<scope_id>.jsonl\\` (for example \\`${conversationPath}/sessions/1777386320.800769.jsonl\\`).\n- If a user asks about something that should exist in conversation history but is not found in the current context window, do not answer \"I don't know\" or \"I don't have that\". Instead, search the thread session, top-level session, and \\`log.jsonl\\` before responding.\n- User messages include a \\`[in-thread:TS]\\` marker when sent from within a platform thread/reply (TS is the thread or parent message identifier). Without this marker, the message is a top-level conversation message.\n${platform.formattingGuide}${slackBlockKitInstructions}\n\n## Platform IDs\nChannels: ${channelMappings}\n\nUsers: ${userMappings}\n\nWhen mentioning users, write <@userName> using the exact userName from the Users table above (e.g., <@mario>). Never invent handles from other platforms (GitHub, email); the platform adapter converts <@userName> to the platform's native mention form.\n\n## Environment\n${envDescription}\n- Default place for clones, downloads, and experiments: ${scratchPath}\n- Do not use host-only paths unless you are running in host mode and verified they exist.`;\n}\n\nfunction buildWorkspaceSkillsPrompt(\n input: BuildSystemPromptOptions,\n paths: RuntimePromptPaths,\n): string {\n const { office, projection, skills, skippedSkillLinks = [] } = input;\n const { workspaceRoot, conversationPath, scratchPath } = paths;\n const knowledgeReadOnly = projection.promptSources.globalKnowledgeReadOnly === true;\n const workspaceLayout = knowledgeReadOnly\n ? `${workspaceRoot}/ contains this private conversation's directory, read-only shared MEMORY.md and skills/, and read-only public/ with every public channel's office.`\n : `${workspaceRoot}/ contains this public conversation's directory, shared MEMORY.md and skills/, and read-only public/ with every public channel's office.`;\n const skillStorageGuidance = knowledgeReadOnly\n ? `Store skills in \\`${conversationPath}/skills/<name>/\\`; shared \\`${workspaceRoot}/skills/\\` is read-only for this private office.`\n : `Store shared skills in \\`${workspaceRoot}/skills/<name>/\\` or conversation-specific skills in \\`${conversationPath}/skills/<name>/\\`.`;\n\n return `## Workspace Layout\n${workspaceLayout}\n${workspaceRoot}/\n├── MEMORY.md # Shared memory${knowledgeReadOnly ? \" (read-only here)\" : \" (all public conversations)\"}\n├── skills/ # Shared CLI tools${knowledgeReadOnly ? \" (read-only here)\" : \" you create\"}\n├── public/<office-key>/ # Other public channels' offices (read-only)\n└── ${office.key}/ # This conversation\n ├── MEMORY.md # Conversation-specific memory\n ├── log.jsonl # Human-readable message history (no tool results)\n ├── sessions/ # Structured session history used for context reconstruction\n │ ├── current # Active top-level session pointer\n │ ├── <timestamp>_<id>.jsonl # Top-level session files\n │ └── <scope_id>.jsonl # Scoped thread/reply session files\n ├── attachments/ # User-shared files\n ├── scratch/ # Working directory for clones/downloads/experiments: ${scratchPath}\n └── skills/ # Conversation-specific tools\n\n## Skills (Custom CLI Tools)\nYou can create reusable CLI tools for recurring tasks (email, APIs, data processing, etc.).\n\n### Creating Skills\n${skillStorageGuidance}\nEach skill directory needs a \\`SKILL.md\\` with YAML frontmatter:\n\n\\`\\`\\`markdown\n---\nname: skill-name\ndescription: Short description of what this skill does\n---\n\n# Skill Name\n\nUsage instructions, examples, etc.\nScripts are in: {baseDir}/\n\\`\\`\\`\n\n\\`name\\` and \\`description\\` are required. Use \\`{baseDir}\\` as placeholder for the skill's directory path.\n\n### Available Skills\n${skills.length > 0 ? formatSkillsForPrompt(skills) : \"(no skills installed yet)\"}${\n skippedSkillLinks.length > 0\n ? `\\n\\nNote: these skill entries were skipped because they are symlinks, which the host never follows when reading this conversation's skills: ${skippedSkillLinks.join(\", \")}. Replace each with a real file or directory (for example \\`cp -rL\\`) to load it.`\n : \"\"\n }`;\n}\n\nfunction buildOperatingPrompt(input: BuildSystemPromptOptions, paths: RuntimePromptPaths): string {\n const { memory, projection, sandboxConfig } = input;\n const { workspaceRoot, conversationPath } = paths;\n const isContainerLike = sandboxConfig.type === \"container\" || sandboxConfig.type === \"image\";\n const globalMemoryReadOnly = projection.promptSources.globalKnowledgeReadOnly === true;\n const memoryGuidance = globalMemoryReadOnly\n ? `\\`${workspaceRoot}/MEMORY.md\\` is shared workspace memory mounted read-only for this private office: you can read what public channels have learned, but writes to it are rejected. Write everything you learn here to \\`${conversationPath}/MEMORY.md\\` instead; it never leaves this conversation.`\n : `Write important shared knowledge to \\`${workspaceRoot}/MEMORY.md\\` and conversation-specific knowledge to \\`${conversationPath}/MEMORY.md\\`.`;\n const systemLogPath = globalMemoryReadOnly\n ? `${conversationPath}/SYSTEM.md`\n : `${workspaceRoot}/SYSTEM.md`;\n\n return `## Events\nUse the \\`event\\` tool to schedule immediate, one-shot, or periodic follow-ups. It is the only way to manage this conversation's scheduled events: they live host-side, not in the workspace, and fill routing fields for the current conversation automatically.\n\nWrite event \\`text\\` as a self-contained future task with needed context, tone, and constraints because events do not inherit normal conversation history.\n\nFor one-shot reminders, include a timezone offset in \\`at\\`. For periodic events, use a cron schedule plus IANA timezone; assume ${Intl.DateTimeFormat().resolvedOptions().timeZone} when users omit timezone.\n\nWhen events trigger, messages are prefixed like \\`[EVENT:filename:type:time]\\`. Immediate and one-shot events auto-delete after triggering; periodic events persist until deleted.\n\nFor periodic events where there's nothing to report, respond with exactly \\`[SILENT]\\`.\n\n## Memory\n${memoryGuidance}\nUpdate it when you learn something important or when asked to remember something.\n\nMemory is a compact, revisable orientation anchor backed by conversation evidence, not a transcript or final truth.\nWhen memory conflicts with newer conversation evidence, prefer the newer evidence.\nFor mutable external state, query the Live source or current API in this run and prefer that fresh result over memory or older API observations. If the source cannot be queried successfully, say that the current state could not be verified; do not fall back to memory as current truth. A later Dream can revise the anchor.\n\nBefore writing an entry, ask whether it is a stable fact (a decision, a convention, an owner,\na recurring constraint) or a one-off event that belongs in \\`log.jsonl\\` instead; only write\nthe former. Keep entries short — a long running log of events crowds out the facts that matter.\n\nQuerying, correcting, and forgetting memory are normal, expected requests, not edge cases:\n- If asked what you remember, read the memory file(s) above and list the entries plainly.\n- If asked to correct or forget something, edit the relevant MEMORY.md to remove or update\n that entry, then confirm what changed.\n\n### Current Memory\n${memory}\n\n## System Configuration Log\nMaintain ${systemLogPath} to log all environment modifications:\n- Installed packages (apt install, npm install, uv pip install)\n- Environment variables set\n- Config files modified (~/.gitconfig, cron jobs, etc.)\n- Skill dependencies installed\n\nUpdate this file whenever you modify the environment. On fresh container, read it first to restore your setup.\n\n## Log Queries (for older history)\nFormat: \\`{\"date\":\"...\",\"ts\":\"...\",\"user\":\"...\",\"userName\":\"...\",\"text\":\"...\",\"isMessagingBot\":false}\\`\nThe log contains user messages and your final responses (not tool calls/results).\nUse \\`log.jsonl\\` for quick grep-style history. Use \\`${conversationPath}/sessions/\\` when you need structured turns, tool outputs, or thread/session lineage.\n${isContainerLike ? \"Install jq: apt-get install jq\" : \"\"}\n\\`\\`\\`bash\n# Recent messages\ntail -30 log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Search for specific topic\ngrep -i \"topic\" log.jsonl | jq -c '{date: .date[0:19], user: (.userName // .user), text}'\n\n# Messages from specific user\ngrep '\"userName\":\"mario\"' log.jsonl | tail -20 | jq -c '{date: .date[0:19], text}'\n\n# Inspect top-level session pointer and available session files\ncat sessions/current\nls -1 sessions/\n\\`\\`\\`\n\n## Tools\n- bash: Run shell commands (primary tool). Install packages as needed.\n- read: Read files\n- write: Create/overwrite files\n- edit: Surgical file edits\n- event: Schedule immediate, one-shot, or periodic follow-ups\n- sandbox: Inspect or temporarily adjust sandbox limits\n- attach: Share files to the platform\n\nEach tool requires a \"label\" parameter (shown to user).\n`;\n}\n\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n const paths = buildRuntimePaths(input.workspacePath, input.office);\n // Per-turn instructions stay in buildTurnInstructions(), keeping this prompt\n // byte-stable across a conversation so the provider cache remains warm.\n return `${buildContextPrompt(input, paths)}\\n\\n${buildWorkspaceSkillsPrompt(input, paths)}\\n\\n${buildOperatingPrompt(input, paths)}`;\n}\n\n/**\n * Instructions that vary per turn (event-trigger mode, response attribution).\n * These are delivered with the user message rather than baked into the system\n * prompt, so the system prompt stays cache-stable across a conversation's turns\n * (in a multi-user channel the attribution line alone changes every turn).\n * Returns an empty string when the turn needs no special framing.\n */\nexport function buildTurnInstructions(\n isEventTrigger: boolean,\n triggerAttribution: string | undefined,\n platformName: string,\n): string {\n const parts: string[] = [];\n if (isEventTrigger) {\n parts.push(`## Event Trigger Mode\n- You are handling a scheduled/background event, not opening a brand new chat with a stranger.\n- Treat the incoming user message as a self-contained task prepared by an earlier run.\n- Complete the task directly. Avoid generic greetings, self-introductions, or boilerplate offers to help.\n- For reminders/follow-ups, prefer a short direct response that sounds like a continuation of prior intent.\n- If the event text includes tone, brevity, or language instructions, follow them literally.`);\n }\n if (triggerAttribution) {\n parts.push(`## Attribution\nAlways end your final ${platformName} response and any GitHub issue/PR comments or descriptions you write via tools with:\n_Triggered by ${triggerAttribution}_\n\nDo not add this to \\`[SILENT]\\` responses.`);\n }\n return parts.join(\"\\n\\n\");\n}\n\nexport function appendTriggerAttribution(\n text: string,\n triggerAttribution: string | undefined,\n sessionLink?: string,\n): string {\n if (!triggerAttribution) return text;\n const trimmed = text.trimEnd();\n const legacySuffix = `_Triggered by ${triggerAttribution}_`;\n // Slack mrkdwn italics cannot span a URL — a `_..._` wrapping a link renders\n // the underscores literally. Keep the session link outside the italic span.\n const suffix = sessionLink ? `${legacySuffix} · session: ${sessionLink}` : legacySuffix;\n if (trimmed.endsWith(suffix)) return text;\n const body = trimmed.endsWith(legacySuffix)\n ? trimmed.slice(0, -legacySuffix.length).trimEnd()\n : trimmed;\n return `${body}\\n\\n${suffix}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/harness/runner.ts"],"names":[],"mappings":"AAsCA,OAAO,KAAK,EAAE,mBAAmB,EAAiB,cAAc,EAAE,MAAM,aAAa,CAAC;AAmxBtF,wBAAsB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,cAAc,CAAC,CAuGxF"}
1
+ {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../src/harness/runner.ts"],"names":[],"mappings":"AAsCA,OAAO,KAAK,EAAE,mBAAmB,EAAiB,cAAc,EAAE,MAAM,aAAa,CAAC;AA+wBtF,wBAAsB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,cAAc,CAAC,CAmGxF"}
@@ -108,7 +108,7 @@ function createRunnerExecutionContext(sandboxConfig, vaultManager, provisioner,
108
108
  }
109
109
  const office = workspace.office(context.address);
110
110
  const projection = resolveWorkspaceProjection(office);
111
- assertSandboxSupportsWorkspacePolicy(sandboxConfig, projection.doorPolicy, projection.promptSources.globalMemoryReadOnly === true);
111
+ assertSandboxSupportsWorkspacePolicy(sandboxConfig, projection.visibility, office.key);
112
112
  return {
113
113
  pathContext: executor.getPathContext(workspace.root),
114
114
  projection,
@@ -520,7 +520,7 @@ export async function createRunner(options) {
520
520
  const projection = resolveWorkspaceProjection(office);
521
521
  // Bootstrap validation fails runner creation early. resolveForRun repeats
522
522
  // the check against the actor-specific decision before any provider call.
523
- assertSandboxSupportsWorkspacePolicy(sandboxConfig, projection.doorPolicy, projection.promptSources.globalMemoryReadOnly === true);
523
+ assertSandboxSupportsWorkspacePolicy(sandboxConfig, projection.visibility, office.key);
524
524
  const { executor, resolveForRun } = createRunnerExecutionContext(sandboxConfig, vaultManager, provisioner, office.workspace);
525
525
  const pathContext = getUnresolvedSandboxPathContext(sandboxConfig, workspaceDir);
526
526
  // The env wraps the stable executor wrapper, which delegates to the