@agentconnect.md/daemon 1.25.0-rc.21 → 1.25.0-rc.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-agents-BiEHZLkW.js","names":["z.enum","z.object","z.string","z.discriminatedUnion","z.literal","z.array","z.boolean","z.number","z.unknown","z.union","z.object","z.enum","z.string","z.boolean","z.number","z.object","z.string","z.number","z.enum","z.enum","z\n .object","z.string","z.object","z.number","z.record","z.unknown","z\n .object","z.literal","z\n .string","z\n .array","z\n .object","z.boolean","z.array","z\n .array","z\n .object","z.enum","z.number","z\n .number","z.object","z.boolean","z.string","z.literal","z.union","z\n .string","z.array","z.record","z.unknown","z.discriminatedUnion","z.preprocess","z.discriminatedUnion","z.object","z.literal","z.string","z\n .object","z.enum","z.boolean","z.array","z.discriminatedUnion","z.object","z.literal","z.enum","z.string","z\n .string","z.array","z\n .object","z.number","z.boolean","z.record","z\n .array","NameValueList","z.array","z.object","z.string","z\n .object","z.enum","z.object","z.string","z.enum","z.array","z.number","z.object","z.string","z.enum","z.array","z.literal","z.boolean","z.number","z.object","z.string","z.array","z.boolean","z.number","z.enum","z.array","z.object","z.string","z\n .object","z.enum","z\n .string","z.NEVER","z\n .string","z\n .array","z.record","z.literal","z\n .object","z.boolean","z.number","z\n .number","z.discriminatedUnion","z.object","z.literal","z.string","z.enum","z.boolean","z.array","z\n .object"],"sources":["../../protocol/dist/frames/route.js","../../protocol/dist/frames/cron.js","../../protocol/dist/frames/secrets.js","../../protocol/dist/memory-plugin.js","../../protocol/dist/frames/memory-connection.js","../../protocol/dist/frames/integration.js","../../protocol/dist/frames/agent.js","../../protocol/dist/frames/mcpserver.js","../../protocol/dist/frames/collab.js","../../protocol/dist/frames/gitcred.js","../../protocol/dist/frames/register.js","../src/config/config-schema.ts","../src/config/load-config.ts","../src/agents/agent-schema.ts","../src/agents/agent-json-file.ts","../src/agents/load-agents.ts"],"sourcesContent":["import { z } from 'zod';\n/**\n * Routing & orchestration (C→D control) — protocol §5.\n *\n * `SessionKey` is the canonical session primitive shared across route/*,\n * agent/*, and event/session. Its canonical string form is\n * `${platform}:${channel}:${thread ?? \"-\"}`.\n */\n// `webchat`, `hook`, and `dream` are session-identity platforms only (the\n// Playground conversation / a webhook trigger / a background memory-consolidation\n// run) — no integration, no bind rules, no routing-table participation, never a\n// persisted DB Platform.\nexport const Platform = z.enum(['slack', 'telegram', 'webchat', 'discord', 'feishu', 'hook', 'dream']);\nexport const SessionKey = z.object({\n platform: Platform,\n channel: z.string(),\n thread: z.string().optional() // absent = channel-root\n});\n/** Trigger-matching rule for a binding (protocol §5.1). */\nexport const BindRule = z.object({\n match: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('mention') }),\n z.object({ kind: z.literal('dm') }),\n z.object({ kind: z.literal('keyword'), value: z.string() }),\n z.object({ kind: z.literal('auto') }) // alert-channel auto-handle\n ])\n});\nexport const RouteAssign = z.object({\n // also appears in RegisterOk.assignments[]\n sessionKey: SessionKey,\n agentId: z.string().uuid(),\n workspaceId: z.string().uuid(), // which D9 workspace to prepare\n bindRules: z.array(BindRule).default([])\n});\nexport const RouteAssignAck = z.object({\n ok: z.boolean(),\n sessionKey: SessionKey,\n reason: z.string().optional()\n});\nexport const RouteUpdate = z.object({\n routingEpoch: z.number().int(),\n rules: z.array(z.object({ match: z.unknown(), agentId: z.string().uuid() }))\n});\n/** Graceful scale-down / rebalance — protocol §5.3. */\nexport const Drain = z.object({\n scope: z.union([\n z.object({ kind: z.literal('agent'), agentId: z.string().uuid() }),\n z.object({ kind: z.literal('daemon') }), // whole-daemon drain (shutdown/upgrade)\n z.object({ kind: z.literal('session'), sessionKey: SessionKey })\n ]),\n deadline: z.string().datetime() // hard cutoff; in-flight turns past this are cancelled\n});\nexport const DrainProgress = z.object({\n remaining: z.number().int(),\n drained: z.array(SessionKey)\n});\nexport const DrainDone = z.object({\n released: z.array(SessionKey) // CP may now reassign — fenced by new epoch\n});\n//# sourceMappingURL=route.js.map","import { z } from 'zod';\n/**\n * Cron sinks to the daemon (D5) — protocol §5.4.\n *\n * A cron periodically triggers ONE AGENT with a synthetic prompt (`trigger`) to\n * carry out some work. The CP owns the definition; the daemon owns firing +\n * last-run persistence, so crons fire even when the CP is down. On receipt the\n * daemon persists the def into the owning agent's `agent.json` `crons[]` (the\n * single source of truth, same model as integrations) — surviving a restart\n * with the CP down.\n *\n * `target` is OPTIONAL output routing: when present, the daemon posts the\n * trigger as a real message in that channel and the agent's session replies in\n * its thread; when absent the fire is headless (the agent works with no\n * platform output).\n */\nexport const CronTarget = z.object({\n platform: z.enum(['slack', 'telegram', 'discord', 'feishu']).default('slack'),\n channel: z.string(),\n // The agent integration whose connection posts the anchor — targets come from\n // the owning agent's integrations, so the daemon posts through the right bot\n // when the agent has several. Absent (legacy defs) ⇒ first integration.\n integrationId: z.string().uuid().optional()\n});\nexport const CronUpsert = z.object({\n cronId: z.string().uuid(),\n agentId: z.string().uuid(), // the agent this cron drives — routes the def to its daemon\n schedule: z.string(), // croner expression interpreted in `timezone`\n timezone: z.string().min(1), // resolved IANA timezone; daemon converts ticks to UTC instants\n target: CronTarget.optional(), // absent ⇒ headless fire\n trigger: z.string(), // synthetic prompt text injected on fire\n enabled: z.boolean().default(true)\n});\nexport const CronRemove = z.object({\n cronId: z.string().uuid()\n});\n/**\n * `cron/report` (D→C EVT, fire-and-forget) — one CP-owned cron fired. The\n * daemon stamps the fire into its local store first (it stays authoritative,\n * §5.4) and reports it here so the console's `lastRunAt` converges; the CP\n * upsert is latest-wins, so the daemon re-asserting its stored stamps on\n * reconnect (fires while the CP was unreachable) is idempotent and can never\n * regress the value. Hand-authored (no-origin) crons are never reported.\n *\n * Reports are keyed by `(cronId, firedAt)`: the FIRE report (no `status`)\n * opens the run, an optional SESSION report attaches the ACP session as soon\n * as it is initialized, and the COMPLETION report (with `status` + outcome\n * fields) closes the run once the dispatched turn ends. A completion without\n * a prior fire report (CP was down at fire time) still creates the run row.\n */\nexport const CronRunStatus = z.enum(['success', 'failed']);\nexport const CronReport = z.object({\n cronId: z.string().uuid(),\n agentId: z.string().uuid(), // the owning agent — scopes the report to its daemon\n firedAt: z.string().datetime(),\n // Terminal outcome fields (absent on fire/session progress reports).\n status: CronRunStatus.optional(),\n durationMs: z.number().int().nonnegative().optional(), // fire → turn end\n // Sent once the ACP session exists, then repeated on completion.\n sessionId: z.string().optional(), // ACP session the run prompted (console deep-link)\n reason: z.string().optional() // short failure text (status \"failed\")\n});\n/**\n * `cron/run` (C→D REQ → ack) — fire one CP-owned cron NOW (console \"Run now\").\n * The daemon accepts (`ok:true`) and runs the fire asynchronously — outcome\n * arrives as normal `cron/report`s; `ok:false` when it holds no such cron.\n */\nexport const CronRunNow = z.object({\n cronId: z.string().uuid()\n});\n//# sourceMappingURL=cron.js.map","import { z } from 'zod';\nimport { Platform } from './route.js';\n/**\n * Secrets (C5 ↔ D10) — protocol §6.\n *\n * Lease-based, no plaintext on the wire or in PG. Every frame carries a\n * REFERENCE to a Vault/KMS path, never the secret material itself.\n */\nexport const SecretsRequest = z.object({\n // D→C, REQ — daemon asks for a lease at session start\n scope: z.object({\n platform: Platform,\n workspaceId: z.string().uuid()\n })\n});\nexport const SecretsGrant = z.object({\n // C→D, REP (also in RegisterOk.leases[])\n leaseId: z.string().uuid(),\n scope: z.object({\n platform: z.string(),\n workspaceId: z.string().uuid()\n }),\n ref: z.string(), // Vault/KMS path or handle — NOT the secret\n ttl: z.number().int(), // seconds\n renewBeforeSec: z.number().int() // daemon should renew this many sec before expiry\n});\nexport const SecretsRenew = z.object({\n leaseId: z.string().uuid() // D→C REQ → new SecretsGrant\n});\nexport const SecretsRevoke = z.object({\n leaseId: z.string().uuid(),\n reason: z.string() // C→D EVT (hot revoke)\n});\n/** 🅼 Direct-to-store upload/download grant — protocol §3.2 / frame #25. */\nexport const ScopeAttestation = z.object({\n machineId: z.string().uuid(),\n scope: z.enum(['attachment.put', 'attachment.get', 'facts.put']),\n resourceRef: z.string(), // opaque object key/prefix\n jws: z.string(), // signed capability the store verifies offline\n exp: z.string().datetime()\n});\n//# sourceMappingURL=secrets.js.map","import { z } from 'zod';\n/**\n * Canonical, backend-neutral contract for an AgentConnect external-memory plugin.\n *\n * This is deliberately NOT a daemon↔CP frame group. Both the daemon's private MCP\n * client and first/third-party plugin implementations import these schemas so the\n * `agentconnect.memory/v1` profile has one executable source of truth. The model\n * never sees the plugin's raw MCP tools; AgentConnect core translates them into a\n * stable product surface.\n */\nexport const MEMORY_PLUGIN_PROFILE = 'agentconnect.memory/v1';\nexport const MEMORY_PLUGIN_PROFILE_MAJOR = 1;\nexport const MEMORY_PLUGIN_TOOL = {\n manifest: 'agentconnect_memory_manifest',\n recall: 'agentconnect_memory_recall',\n capture: 'agentconnect_memory_capture',\n health: 'agentconnect_memory_health',\n operationStatus: 'agentconnect_memory_operation_status',\n list: 'agentconnect_memory_list',\n get: 'agentconnect_memory_get',\n create: 'agentconnect_memory_create',\n update: 'agentconnect_memory_update',\n delete: 'agentconnect_memory_delete',\n history: 'agentconnect_memory_history'\n};\nexport const MEMORY_RECALL_DEFAULTS = {\n topK: 5,\n maxBytes: 8 * 1024,\n // The budget covers the complete daemon -> relay -> plugin -> embedder\n // round trip. A healthy remote Mem0 search can spend ~1s at the relay alone,\n // so 1s races successful responses instead of representing a useful SLA.\n timeoutMs: 3_000\n};\n// Recall runs before every activation and fails open, so the default budget\n// stays bounded while leaving transport headroom around the common warm path.\n// The ceiling is deliberately generous:\n// a local/self-hosted provider (e.g. Mem0 OSS) can need several seconds on a\n// cold first search — embedding-model load plus vector search — and an operator\n// must be able to configure a budget that a healthy cold start fits inside\n// rather than being forced to degrade it. This is the single source of truth\n// for the recall-timeout ceiling shared by the connection policy schema and,\n// by contract, the control-plane validation and console input.\nexport const MEMORY_RECALL_HARD_LIMITS = {\n topK: 20,\n maxBytes: 32 * 1024,\n timeoutMs: 10_000\n};\nexport const MemoryScopeKind = z.enum(['agent', 'user', 'session', 'shared']);\n/** The plugin-facing scope. `key` is always derived by daemon core, never tool input. */\nexport const CanonicalMemoryScope = z\n .object({\n kind: MemoryScopeKind,\n key: z.string().min(1).max(512)\n})\n .strict();\nexport const MemoryRecordProvenance = z\n .object({\n pluginId: z.string().min(1).max(255),\n backendId: z.string().min(1).max(512).optional()\n})\n .strict();\n/** The one record shape AgentConnect core understands, regardless of backend. */\nexport const CanonicalMemoryRecord = z.object({\n id: z.string().min(1).max(512),\n text: z.string().min(1),\n score: z.number().finite().optional(),\n scope: CanonicalMemoryScope,\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n provenance: MemoryRecordProvenance.optional(),\n /** Backend version/ETag for optimistic concurrency on update. */\n version: z.string().min(1).max(512).optional()\n});\nexport const CaptureReceipt = z.object({\n state: z.enum(['completed', 'accepted', 'failed', 'ambiguous']),\n backendOperationId: z.string().min(1).max(512).optional()\n});\n/** Every operation carries a core-created request, connection, and trusted scope. */\nexport const MemoryPluginCallContext = z\n .object({\n requestId: z.string().min(1).max(512),\n connection: z\n .object({\n id: z.string().min(1).max(512),\n config: z.record(z.string(), z.unknown())\n })\n .strict(),\n scope: CanonicalMemoryScope\n})\n .strict();\nexport const MemoryPluginOperation = z.enum([\n 'recall',\n 'capture',\n 'list',\n 'get',\n 'create',\n 'update',\n 'delete',\n 'history'\n]);\n/** Exact machine-readable text tokens for MCP tool results with `isError:true`.\n * MCP validates structuredContent against the success output schema even on an\n * error result, so profile errors use an exact token and never a free-form\n * plugin/upstream message. */\nexport const MEMORY_PLUGIN_ERROR_TOKEN = {\n conflict: 'agentconnect.memory.error/conflict'\n};\nconst unique = (xs) => new Set(xs).size === xs.length;\n/** The result of the required manifest tool (`structuredContent` directly). */\nexport const MemoryPluginManifest = z.object({\n profile: z.literal(MEMORY_PLUGIN_PROFILE),\n plugin: z.object({\n id: z\n .string()\n .max(255)\n .regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/, 'plugin id must be reverse-DNS-like'),\n version: z\n .string()\n .max(128)\n .regex(/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/, 'plugin version must be semver')\n }),\n connection: z.object({\n // A deliberately bounded JSON-Schema subset is enforced by daemon core during\n // conformance; this field remains JSON here so the console can render it later.\n configSchema: z.record(z.string(), z.unknown()),\n secretFields: z\n .array(z\n .object({\n name: z.string().min(1).max(128),\n required: z.boolean(),\n transportHeader: z.string().min(1).max(128).optional()\n })\n .strict())\n .max(64)\n .refine((fields) => unique(fields.map((field) => field.name)), 'secret field names must be unique')\n }),\n capabilities: z\n .object({\n scopes: z.array(MemoryScopeKind).min(1).max(4).refine(unique, 'scope capabilities must be unique'),\n operations: z.array(MemoryPluginOperation).min(2).max(8).refine(unique, 'operation capabilities must be unique'),\n asyncCapture: z.boolean(),\n idempotency: z.enum(['operation-id', 'none'])\n })\n .strict(),\n limits: z\n .object({\n maxQueryBytes: z.number().int().positive(),\n maxRecordBytes: z.number().int().positive(),\n maxBatchItems: z.number().int().positive()\n })\n .strict(),\n declaredEgressHosts: z\n .array(z.string().min(1).max(253))\n .max(128)\n .refine(unique, 'egress hosts must be unique')\n .optional()\n});\nexport const MemoryPluginRecallInput = z\n .object({\n context: MemoryPluginCallContext,\n query: z.string().min(1),\n topK: z.number().int().positive().max(MEMORY_RECALL_HARD_LIMITS.topK),\n maxBytes: z.number().int().positive().max(MEMORY_RECALL_HARD_LIMITS.maxBytes)\n})\n .strict();\nexport const MemoryPluginRecallOutput = z.object({ records: z.array(CanonicalMemoryRecord) }).strict();\nexport const MemoryPluginTurnObservation = z\n .object({\n turnId: z.string().min(1).max(512),\n input: z.string(),\n output: z.string(),\n sessionId: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginCaptureInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n turn: MemoryPluginTurnObservation\n})\n .strict();\nexport const MemoryPluginCaptureOutput = CaptureReceipt.strict();\nexport const MemoryPluginHealthInput = z.object({ context: MemoryPluginCallContext }).strict();\nexport const MemoryPluginHealthOutput = z\n .object({\n status: z.enum(['ready', 'degraded', 'invalid']),\n /** Stable, non-secret diagnostic code. Never an upstream response body. */\n reasonCode: z.string().min(1).max(128).optional()\n})\n .strict();\nexport const MemoryPluginOperationStatusInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n backendOperationId: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginOperationStatusOutput = CaptureReceipt.strict();\nconst OptionalCursor = z.string().min(1).max(2048).optional();\nexport const MemoryPluginListInput = z\n .object({\n context: MemoryPluginCallContext,\n cursor: OptionalCursor,\n limit: z.number().int().positive().max(100).default(50)\n})\n .strict();\nexport const MemoryPluginListOutput = z\n .object({ records: z.array(CanonicalMemoryRecord), nextCursor: OptionalCursor })\n .strict();\nexport const MemoryPluginGetInput = z\n .object({ context: MemoryPluginCallContext, id: z.string().min(1).max(512) })\n .strict();\nexport const MemoryPluginGetOutput = z.object({ record: CanonicalMemoryRecord.nullable() }).strict();\nexport const MemoryPluginCreateInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n text: z.string().min(1),\n metadata: z.record(z.string(), z.unknown()).optional()\n})\n .strict();\nexport const MemoryPluginCreateOutput = z.object({ record: CanonicalMemoryRecord }).strict();\nexport const MemoryPluginUpdateInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n id: z.string().min(1).max(512),\n text: z.string().min(1),\n metadata: z.record(z.string(), z.unknown()).optional(),\n version: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginUpdateOutput = z.object({ record: CanonicalMemoryRecord }).strict();\nexport const MemoryPluginDeleteInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n id: z.string().min(1).max(512),\n version: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginDeleteOutput = z.object({ deleted: z.boolean() }).strict();\nexport const MemoryPluginHistoryInput = z\n .object({\n context: MemoryPluginCallContext,\n id: z.string().min(1).max(512),\n cursor: OptionalCursor,\n limit: z.number().int().positive().max(100).default(50)\n})\n .strict();\nexport const MemoryPluginHistoryEvent = z\n .object({\n id: z.string().min(1).max(512),\n event: z.enum(['create', 'update', 'delete']),\n at: z.string().datetime(),\n record: CanonicalMemoryRecord.optional()\n})\n .strict();\nexport const MemoryPluginHistoryOutput = z\n .object({ events: z.array(MemoryPluginHistoryEvent), nextCursor: OptionalCursor })\n .strict();\n//# sourceMappingURL=memory-plugin.js.map","import { z } from 'zod';\nimport { MEMORY_PLUGIN_PROFILE, MEMORY_RECALL_DEFAULTS, MEMORY_RECALL_HARD_LIMITS, MemoryPluginManifest } from '../memory-plugin.js';\n/**\n * External-memory control-plane distribution (M-5A).\n *\n * The Control Plane owns installations and org connections. A daemon receives\n * a transport-specific private definition. Remote definitions carry a relay URL\n * and purpose-specific bearer grant; local definitions carry an operator\n * allowlist reference and daemon-private secret lease. Raw local commands never\n * cross this wire.\n */\nexport const MemoryRecallPolicy = z\n .object({\n mode: z.enum(['auto', 'tool-only']).default('auto'),\n topK: z.number().int().positive().max(MEMORY_RECALL_HARD_LIMITS.topK).default(MEMORY_RECALL_DEFAULTS.topK),\n maxBytes: z\n .number()\n .int()\n .positive()\n .max(MEMORY_RECALL_HARD_LIMITS.maxBytes)\n .default(MEMORY_RECALL_DEFAULTS.maxBytes),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .max(MEMORY_RECALL_HARD_LIMITS.timeoutMs)\n .default(MEMORY_RECALL_DEFAULTS.timeoutMs)\n})\n .strict();\nexport const MemoryCapturePolicy = z.object({ mode: z.enum(['turn', 'manual']).default('manual') }).strict();\n/**\n * Dreaming — periodic offline consolidation of the MANAGED store\n * (design: docs/designs/memory-dreaming.md). Valid only with\n * `provider: 'managed'`; the daemon stages a rebuilt store per dream and the\n * user reviews and adopts it, or an enabled auto-accept policy adopts it.\n * Bounds mirror the design: sessionWindow ≤ 100 mined transcripts,\n * instructions ≤ 4096 chars.\n */\nexport const MemoryDreamingPolicy = z\n .object({\n enabled: z.boolean(),\n /** How many recent sessions to mine (default 20). */\n sessionWindow: z.number().int().min(1).max(100).optional(),\n /** Cron expression for scheduled dreams (same syntax as agent crons). A tick\n * that lands while a dream is already in flight is skipped, not queued. */\n schedule: z.string().min(1).max(128).optional(),\n /** IANA zone the `schedule` is evaluated in (as on agent crons). Absent ⇒ the\n * daemon host's local time. */\n timezone: z.string().min(1).max(64).optional(),\n /** Operator steering text applied through the whole dream pipeline. */\n instructions: z.string().max(4096).optional(),\n /** Also mine reusable procedures into candidate skills (never auto-installed). */\n mineSkills: z.boolean().optional(),\n /** Adopt the staged store automatically on completion without content\n * review. Live-memory fence conflicts remain reviewable. Absent defaults\n * to true for effective managed-memory policies. */\n autoAdopt: z.boolean().optional()\n})\n .strict();\n/** Product default for managed memory with no explicit dreaming policy.\n *\n * The schedule is evaluated in the daemon host's timezone because no timezone\n * is set. Keeping this as an explicit policy lets a saved policy distinguish\n * manual-only dreaming (enabled with no schedule) from the default daily run.\n */\nexport const DEFAULT_MEMORY_DREAMING_POLICY = {\n enabled: true,\n schedule: '0 4 * * *',\n autoAdopt: true\n};\nconst BuiltInMemoryBinding = z\n .object({\n provider: z.enum(['none', 'native', 'managed']),\n autoDistill: z.boolean().optional(),\n dreaming: MemoryDreamingPolicy.optional()\n})\n .strict()\n .superRefine((binding, ctx) => {\n if (binding.dreaming && binding.provider !== 'managed') {\n ctx.addIssue({\n code: 'custom',\n path: ['dreaming'],\n message: 'dreaming is only supported with the managed memory provider'\n });\n }\n});\nexport const ExternalMemoryBinding = z\n .object({\n provider: z.literal('external'),\n connectionId: z.string().uuid(),\n recall: MemoryRecallPolicy.default({ mode: 'auto', ...MEMORY_RECALL_DEFAULTS }),\n // The safe default never exports a full turn. Console users must explicitly\n // acknowledge the egress disclosure before selecting turn capture.\n capture: MemoryCapturePolicy.default({ mode: 'manual' })\n})\n .strict();\n/** Agent-facing provider selection. External bindings carry policy, never endpoints or secrets. */\nexport const AgentMemoryBinding = z.union([BuiltInMemoryBinding, ExternalMemoryBinding]);\n/** Resolve the managed-memory dreaming policy used by the daemon.\n *\n * No memory binding means the managed provider, and no explicit dreaming policy\n * means the daily auto-adopting product default. Once a policy exists its absent\n * schedule remains meaningful (manual-only), while absent `autoAdopt` follows\n * the new default; an explicit false is the opt-out.\n */\nexport function effectiveMemoryDreamingPolicy(binding) {\n if (binding && binding.provider !== 'managed')\n return undefined;\n const policy = binding?.dreaming;\n if (!policy)\n return { ...DEFAULT_MEMORY_DREAMING_POLICY };\n return policy.autoAdopt === undefined ? { ...policy, autoAdopt: true } : policy;\n}\n/** Reviewed mapping from a logical secret field to the header the relay injects. */\nexport const MemoryPluginSecretHeaderPin = z\n .object({ name: z.string().min(1).max(128), header: z.string().min(1).max(128), required: z.boolean() })\n .strict();\nexport const MemoryPluginPin = z\n .object({\n pluginId: z.string().min(1).max(255),\n profileMajor: z.literal(1),\n manifestDigest: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/)\n .optional(),\n secretHeaders: z.array(MemoryPluginSecretHeaderPin).max(64).default([])\n})\n .strict();\nconst MemoryConnectionSpecBase = z\n .object({\n connectionId: z.string().uuid(),\n revision: z.number().int().positive(),\n config: z.record(z.string(), z.unknown()),\n secretKeys: z.array(z.string().min(1).max(128)).max(64).default([]),\n pin: MemoryPluginPin\n})\n .strict();\nconst RemoteMemoryConnectionSpec = MemoryConnectionSpecBase.extend({\n transport: z.literal('streamable-http'),\n relayUrl: z.string().url(),\n grantKey: z.string().min(1).max(512)\n}).strict();\n/** Plaintext values cross only the authenticated daemon control channel and\n * remain in its private registry until they are injected into the allowlisted\n * plugin child. They never enter AgentSpec, agent.json, or the agent runtime. */\nexport const MemoryConnectionSecretLease = z\n .object({\n values: z.record(z.string().min(1).max(128), z\n .string()\n .min(1)\n .max(16 * 1024)\n .refine((value) => !value.includes('\\0'), 'memory connection secret contains NUL'))\n})\n .strict()\n .superRefine((lease, ctx) => {\n if (new TextEncoder().encode(JSON.stringify(lease.values)).byteLength > 64 * 1024) {\n ctx.addIssue({ code: 'custom', path: ['values'], message: 'memory connection secret lease exceeds 64 KiB' });\n }\n});\nconst StdioMemoryConnectionSpec = MemoryConnectionSpecBase.extend({\n transport: z.literal('stdio'),\n // This is a logical lookup key in the daemon operator's local allowlist, not\n // a path/command supplied by the tenant or Control Plane.\n commandRef: z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, 'commandRef must be an allowlist key'),\n secretLease: MemoryConnectionSecretLease\n})\n .strict()\n .superRefine((spec, ctx) => {\n const keys = Object.keys(spec.secretLease.values).sort();\n const declared = [...spec.secretKeys].sort();\n if (keys.length !== declared.length || keys.some((key, index) => key !== declared[index])) {\n ctx.addIssue({ code: 'custom', path: ['secretLease'], message: 'secret lease keys must match secretKeys' });\n }\n});\nconst TransportedMemoryConnectionSpec = z.discriminatedUnion('transport', [\n RemoteMemoryConnectionSpec,\n StdioMemoryConnectionSpec\n]);\n/** One daemon-private connection definition. Both relay grants and local secret\n * leases are secret-bearing; callers must never log this frame or validation\n * payload. Local commands are resolved solely from the operator allowlist.\n *\n * M-5A remote frames predate the transport discriminator. Decode them as\n * Streamable HTTP so daemons can be upgraded before the Control Plane during a\n * rolling deployment; the encoder likewise keeps remote frames legacy-shaped\n * until the old daemon population is gone. */\nexport const MemoryConnectionSpec = z.preprocess((input) => {\n if (typeof input !== 'object' || input === null || Array.isArray(input) || 'transport' in input)\n return input;\n if ('relayUrl' in input && 'grantKey' in input)\n return { ...input, transport: 'streamable-http' };\n return input;\n}, TransportedMemoryConnectionSpec);\n/** C→D live CRUD; reconnect baseline is `register/ok.memoryConnections`. */\nexport const MemoryConnectionUpsert = MemoryConnectionSpec;\nexport const MemoryConnectionRemove = z.object({ connectionId: z.string().uuid() }).strict();\n/** Stable, body-free probe fact for one connection revision. */\nexport const MemoryConnectionFact = z\n .object({\n connectionId: z.string().uuid(),\n revision: z.number().int().positive(),\n pluginId: z.string().min(1).max(255),\n version: z.string().max(128).optional(),\n profile: z.literal(MEMORY_PLUGIN_PROFILE).optional(),\n manifestDigest: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/)\n .optional(),\n capabilities: MemoryPluginManifest.shape.capabilities.optional(),\n declaredEgressHosts: z.array(z.string().min(1).max(255)).max(128).optional(),\n status: z.enum(['probing', 'ready', 'degraded', 'invalid']),\n reasonCode: z.string().min(1).max(128).optional()\n})\n .strict();\n/** D→C full snapshot. Re-emitted on reconnect and after every probe transition. */\nexport const MemoryConnectionFacts = z.object({ connections: z.array(MemoryConnectionFact).max(1_024) }).strict();\n//# sourceMappingURL=memory-connection.js.map","import { z } from 'zod';\n/**\n * Platform integration distribution (C→D) — the Slack \"install\" flow.\n *\n * The Control Plane is the source of truth for platform integrations and pushes\n * them to the daemon that owns the integration's agent (`integration/upsert`, and\n * the reconcile snapshot `RegisterOk.integrations[]`). The daemon opens the Socket\n * Mode connection from the delivered config (see slack/connection.ts).\n *\n * SECURITY: `integration/upsert` and `RegisterOk.integrations[]` carry PLAINTEXT\n * platform tokens (botToken/appToken/appSecret). These payloads MUST NEVER be logged — no\n * body dump on decode error, no register/ok snapshot debug dump. The daemon\n * persists them into the owning agent's local `agent.json` (same trust boundary\n * as hand-authored agents, which already keep tokens there) so integrations\n * survive a restart with the CP down.\n *\n * `signingSecret` is intentionally absent: Socket Mode authenticates with the\n * app-level token, so the daemon never needs a signing secret.\n */\n/** Trigger match — mirrors the daemon BindRuleConfig.match (agents/agent-schema.ts). */\nexport const BindMatch = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('mention') }),\n z.object({ kind: z.literal('dm') }),\n z.object({ kind: z.literal('keyword'), value: z.string() }),\n z.object({ kind: z.literal('auto') })\n]);\n/** One channel/thread trigger binding — mirrors the daemon BindRuleConfig. */\nexport const IntegrationBindRule = z.object({\n channel: z.string().optional(), // absent = any channel\n thread: z.string().optional(),\n match: BindMatch\n});\n/**\n * The Slack config a daemon receives (no signingSecret). `mode` splits the two\n * distribution paths of shared-bot-relay.md §7.3:\n *\n * - `direct` (today's behaviour, the default): the daemon owns the whole bot —\n * it opens the Socket Mode connection itself (needs `appToken`) and arbitrates\n * inbound locally (`bindRules`). Unchanged from before shared bots existed.\n * - `shared`: the bot's INBOUND lives on a relay (§4.1), so the daemon gets\n * xoxb ONLY — enough to SEND (`chat.postMessage`, attachment fetch). No\n * `appToken` (credential domaining: the daemon must not be able to subscribe\n * the event stream) and no `bindRules` (routing is arbitrated in the relay,\n * delivered pre-addressed). `botUserId` is optional and lazily resolved by the\n * daemon via `auth.test` (same as direct) if the sender ever needs it.\n *\n * Modeled as a flat object with a defaulted discriminator (not a\n * `discriminatedUnion`) so specs persisted before this field existed still decode\n * as `direct`. `.superRefine` enforces the one hard per-mode requirement the union\n * would otherwise give: direct needs the app-level token.\n */\nexport const IntegrationSlackConfig = z\n .object({\n mode: z.enum(['direct', 'shared']).default('direct'),\n botToken: z.string(), // xoxb-… (plaintext — never log) — always present (send path)\n appToken: z.string().optional(), // xapp-… (plaintext — never log) — direct only (Socket Mode)\n appId: z.string().optional(), // A… public metadata — permission-update deep link (especially shared mode)\n // Multi-agent opt-in — the bot backs MANY agents, so an in-thread \"Switch agent\"\n // control is meaningful. ONLY ever true in `shared` mode (an http/relay bot); a\n // non-shareable http bot is still `shared` for routing but has one agent, so the\n // switch control is suppressed. Defaults false so pre-field specs (and every direct\n // bot) decode as non-shareable.\n shareable: z.boolean().default(false),\n botUserId: z.string().optional(), // lazily resolved via auth.test; may be seeded by CP\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]), // empty for shared (relay arbitrates)\n // Channels the operator switched OFF. bindRules can only ADD reach, so an\n // ungated integration — whose defaults are unscoped (@-mention anywhere + DMs) —\n // has no way to say \"not here\" without a subtractive fence. A muted channel\n // matches no rule of this integration at all: no mention, no thread continuity,\n // no control command. Channels only (a DM is never muted this way); a GATED\n // integration leaves this empty, since its Off is already the ABSENCE of a\n // conversation-scoped rule. Defaults empty (pre-field specs).\n mutedChannels: z.array(z.string()).default([]),\n // Conversation gating (resource-visibility.md §14): true ⇒ this integration is\n // fail-closed — the CP ships only conversation-scoped bindRules (no unscoped\n // defaults), and the daemon answers explicitly-addressed unrouted messages with\n // a one-time notice + reports DM conversations. Derived from the owning agent's\n // restricted visibility; carries NO identities. Defaults false (pre-field specs).\n gated: z.boolean().default(false)\n})\n .superRefine((c, ctx) => {\n if (c.mode === 'direct' && !c.appToken)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'direct slack requires appToken', path: ['appToken'] });\n});\n/**\n * The Telegram config the daemon needs to open long-polling + route (grammY).\n * Telegram has a SINGLE BotFather HTTP token — no app-level token and no signing\n * secret (long-polling authenticates every getUpdates call with the bot token).\n */\nexport const IntegrationTelegramConfig = z.object({\n botToken: z.string(), // BotFather \"123456:ABC…\" (plaintext — never log)\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see IntegrationSlackConfig.mutedChannels\n gated: z.boolean().default(false) // conversation gating — see IntegrationSlackConfig.gated\n});\n/**\n * The Discord config the daemon needs to open the Gateway + route (discord.js).\n * Discord authenticates the Gateway with a SINGLE bot token — no Slack-style\n * app-level token and no signing secret. `applicationId` is public metadata (the\n * client id for the OAuth2 bot-invite URL); it is not secret material.\n */\nexport const IntegrationDiscordConfig = z.object({\n botToken: z.string(), // Bot <token> (plaintext — never log)\n applicationId: z.string().optional(), // client/application id — public, for the invite URL\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see IntegrationSlackConfig.mutedChannels\n gated: z.boolean().default(false) // conversation gating — see IntegrationSlackConfig.gated\n});\n/**\n * The Feishu / Lark config the daemon needs to open the long-connection WebSocket\n * (`@larksuiteoapi/node-sdk` `WSClient`) + route. A Feishu self-built app\n * authenticates with an `appId` + `appSecret` PAIR — the SDK exchanges them for a\n * short-lived `tenant_access_token` internally (no Slack-style app-level token, no\n * signing secret). `appId` is a semi-public identifier (`cli_…`); `appSecret` is\n * plaintext secret material — NEVER log it. `botOpenId` is the bot's own open_id\n * for @-mention routing; lazily resolved by the daemon via `bot/info` if absent.\n *\n * `region` selects the open-platform gateway the daemon SDK (and CP verifier)\n * talk to — `'feishu'` = mainland China (`open.feishu.cn`, the SDK default) vs\n * `'lark'` = international (`open.larksuite.com`). Same app model, different host;\n * an app is registered in exactly one region. Defaults to `'feishu'` so existing\n * installs are unaffected.\n */\nexport const FeishuRegion = z.enum(['feishu', 'lark']);\nexport const IntegrationFeishuConfig = z.object({\n // `direct` opens the SDK long connection on the daemon. `shared` keeps only\n // the authenticated REST client on the daemon; HTTP callbacks arrive through\n // the relay and are delivered pre-addressed over rd/*.\n mode: z.enum(['direct', 'shared']).default('direct'),\n appId: z.string(), // cli_… — app identifier (semi-public), needed for REST and direct WS\n appSecret: z.string(), // app secret (plaintext — never log)\n botOpenId: z.string().optional(), // bot's own open_id; lazily resolved via bot/info\n region: FeishuRegion.default('feishu'), // open-platform gateway: feishu.cn vs larksuite.com\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see IntegrationSlackConfig.mutedChannels\n gated: z.boolean().default(false) // conversation gating — see IntegrationSlackConfig.gated\n});\n/**\n * One platform integration, owned by exactly one agent. Also the element type of\n * `RegisterOk.integrations[]` (the per-daemon reconcile set). Discriminated on\n * `platform`: the daemon opens a Slack Socket Mode connection, a Telegram\n * long-poll, a Discord Gateway, or a Feishu long-connection from whichever variant\n * is delivered.\n */\nexport const IntegrationSpec = z.discriminatedUnion('platform', [\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('slack'),\n slack: IntegrationSlackConfig\n }),\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('telegram'),\n telegram: IntegrationTelegramConfig\n }),\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('discord'),\n discord: IntegrationDiscordConfig\n }),\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('feishu'),\n feishu: IntegrationFeishuConfig\n })\n]);\n/** C→D EVT — install/update an integration on the owning agent's daemon. */\nexport const IntegrationUpsert = IntegrationSpec;\n/** C→D EVT — remove an integration from the daemon. */\nexport const IntegrationRemove = z.object({\n integrationId: z.string().uuid()\n});\n/**\n * One conversation the bot participates in (metadata only — no messages).\n * `kind` distinguishes member channels from direct conversations (resource-\n * visibility.md §14.3): absent = 'channel' for wire compatibility. DM rows\n * (`kind: 'im'`, Slack \"D…\" ids) are reported only for gated integrations, on\n * first inbound DM; their `name` is the counterpart's display name. Group DMs\n * (`kind: 'mpim'`, Slack multi-person DMs) are reported on observation the same\n * way — never enumerated, because Slack does not list them as bot membership —\n * but they behave like a channel: several humans share the room, so the agent\n * stays mention-gated there rather than answering every message.\n *\n * `spaceId`/`space` identify the container the conversation lives in — a Discord\n * GUILD, which a bot in several servers needs for the channel to be identifiable at\n * all (every server has a \"#general\"). The ID is the identity: two distinct guilds\n * may carry the SAME name, so grouping on the name alone would merge them and hide\n * the ambiguity it was meant to resolve. `space` is the display label only. Both are\n * absent on platforms with one implicit container per bot (Slack workspace, Telegram,\n * Feishu tenant) and on DM rows.\n */\nexport const IntegrationChannel = z.object({\n id: z.string(), // platform conversation id (Slack \"C…\" / DM \"D…\")\n name: z.string().optional(), // \"#deploys\" without the hash (or DM counterpart); absent if lookup failed\n spaceId: z.string().optional(), // enclosing Discord guild snowflake — the space's IDENTITY\n space: z.string().optional(), // that guild's display name; absent until resolved\n isPrivate: z.boolean().optional(),\n kind: z.enum(['channel', 'im', 'mpim']).optional() // absent = 'channel'\n});\n/**\n * D→C EVT — channels observed by an integration's bot (fire-and-forget,\n * latest-wins). Slack reports an authoritative membership snapshot; platforms\n * such as Telegram that cannot enumerate every chat set `authoritative:false`,\n * so the CP upserts what was observed without deleting older rows that are\n * absent from this report. An absent flag means authoritative for wire\n * compatibility. Channel names are control metadata, never message content.\n */\nexport const IntegrationChannels = z.object({\n integrationId: z.string().uuid(),\n channels: z.array(IntegrationChannel),\n authoritative: z.boolean().optional()\n});\n//# sourceMappingURL=integration.js.map","import { z } from 'zod';\nimport { AgentMemoryBinding } from './memory-connection.js';\nimport { IntegrationSpec } from './integration.js';\nimport { CronUpsert } from './cron.js';\n/**\n * Agent lifecycle (protocol §4.4, §7.4, §8).\n *\n * There is no CP→daemon prompt-delivery frame: the daemon prompts an agent from\n * its own ingress (platform adapters or relay `rd/*` delivery), never the CP.\n * The old `agent/prompt` + per-agent `seq` machinery was reserved infrastructure\n * with no live caller and has been removed.\n */\n/**\n * Where the agent runs. Two modes; the **path is always daemon-generated** —\n * never specified by the caller (UX picks the mode, the machine owns the dir).\n *\n * - `scratch`: a fresh empty working dir on the machine, with no default repo.\n * `gitCredential: github-app` enables credentials only for repositories that\n * were explicitly authorized for the agent.\n * - `github`: the daemon clones `gitRepo` @ `branch` and runs the agent in\n * `agentDir` (a subdir of the repo, repo-root if omitted). **Multiple agents\n * may share one repo** — they differ by `agentDir`, so the repo is not an\n * owned entity, just shared config on each agent.\n */\nexport const AgentWorkspace = z.discriminatedUnion('mode', [\n z.object({\n mode: z.literal('scratch'),\n // Scratch has no implicit/default repository. The credential helper still\n // lets git/gh request explicitly authorized repositories by name.\n gitCredential: z.enum(['github-app']).optional()\n }),\n z.object({\n mode: z.literal('github'),\n gitRepo: z.string(), // FULL cloneable address, e.g. https://github.com/acme/infra (normalizeGitUrl)\n branch: z.string().default('main'),\n agentDir: z.string().optional(), // subdir within the repo; omitted ⇒ repo root\n // Credential mode for remote git ops. Absent ⇒ anonymous (public repos,\n // the pre-github-app behavior). 'github-app' ⇒ the daemon pulls short-lived\n // CP-minted installation tokens over gitcred/request and injects them via\n // the local credential helper — no durable git credential on the host.\n gitCredential: z.enum(['github-app']).optional()\n })\n]);\n/**\n * MCP-server name reserved for the daemon's own injected stdio bridge (its\n * platform tools). A config-defined or agent-enabled server under this name\n * would collide with the bridge entry at ACP `session/new`, so the daemon\n * strips it and the CP rejects it in `AgentSpec.mcpServers` at the API edge.\n */\nexport const RESERVED_MCP_SERVER_NAME = 'agentconnect';\n/**\n * The curated Lucide glyph set a `glyph` icon may use — the single source of\n * truth for the picker, the DTO validation, and the CP icon-endpoint renderer.\n * `glyph` is constrained to this set so an API/CLI-created icon can't persist a\n * name the console `<Icon>` and the PNG endpoint don't both render. The web\n * picker mirrors this list (it does not import this package) — keep in sync.\n */\nexport const AGENT_ICON_GLYPHS = [\n // The AgentConnect brand diamond — the fixed identity of the built-in preset\n // agents (preset-agents.md §3.1). Renderers special-case it: a multi-color\n // brand mark (not a Lucide stroke glyph) drawn plateless — the native logo,\n // its `color` field inert. The web picker deliberately does NOT offer it in\n // its grid, though a stored value renders everywhere.\n 'agentconnect',\n 'bot',\n 'cpu',\n 'terminal',\n 'code',\n 'rocket',\n 'zap',\n 'bug',\n 'git-branch',\n 'message-square',\n 'sparkles',\n 'brain',\n 'wrench',\n 'ship',\n 'box',\n 'hexagon',\n 'compass',\n 'atom',\n 'flame',\n 'star',\n 'heart',\n 'globe',\n 'database',\n 'shield',\n 'feather'\n];\n/**\n * An agent's display icon (docs: the Console \"Agent Avatar\" picker). A\n * discriminated union on `kind`:\n * - `runtime` — derive the mark from the agent's runtime (Claude/Codex/…), the\n * legacy behavior; also the meaning of a null/absent icon.\n * - `glyph` — a curated Lucide glyph (see {@link AGENT_ICON_GLYPHS}) on a solid\n * color plate (the create-time random default is a `glyph`). An unknown glyph\n * fails to parse and degrades to the runtime mark on every surface.\n * - `image` — a user-uploaded avatar. The bytes live in the CP's configured\n * object store (S3-compatible; see docs/designs/icon-uploads.md), NOT in this\n * descriptor. Its optional opaque generation distinguishes successive writes\n * to the stable object key; legacy rows omit it. The display/serve URL is\n * resolved separately (the object store's public URL for the owner's key),\n * surfaced as the DTO `iconUrl` / `AgentSpec.iconUrl`. Set only via the upload\n * route; never via a create/update body.\n * This descriptor is CP-owned + stored on the agent and surfaced to the web\n * console. The daemon never receives it — it gets only the resolved public\n * `AgentSpec.iconUrl` (for the Slack per-message avatar), so it needs no renderer.\n */\nexport const AgentIcon = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('runtime') }),\n z.object({ kind: z.literal('glyph'), glyph: z.enum(AGENT_ICON_GLYPHS), color: z.string() }),\n z.object({ kind: z.literal('image'), generation: z.string().min(1).max(128).optional() })\n]);\n/**\n * A self-contained skill source the daemon installs via `npx skills` after the\n * workspace is ready and before the ACP host spawns (design: shared-skills.md §4).\n * The source definition rides INLINE on the AgentSpec (and lands in agent.json,\n * like mcpServers) — there is no separate skillsource frame or daemon-side def\n * cache. The CP resolves each agent's enabled org-level `SkillSource` rows into\n * these entries when it builds the spec.\n */\n// These strings become positional/`-s` arguments to `npx skills`, so a leading\n// \"-\" would be read as a flag rather than a value. Reject option-looking values at\n// the wire boundary — the daemon validates again in depth.\nconst SkillArg = z\n .string()\n .min(1)\n .refine((s) => !s.startsWith('-'), { message: 'must not start with \"-\"' });\nexport const AgentSkillEntry = z.object({\n // Display/log label — the org-level source name. NOT passed to the CLI.\n name: z.string(),\n // The source string fed straight to `npx skills add` (owner/repo, a full git\n // URL, or a tree/<ref>/<subdir> path). Everything else here is optional.\n source: SkillArg,\n // Optional branch/tag/commit. The daemon composes it into the source when set;\n // a tag/commit pins content, a branch/absent tracks the head (design §5).\n ref: z.string().optional(),\n // Optional repo-relative install directory.\n subDir: z.string().optional(),\n // Which skills from the source to install (passed as repeated `-s`). Empty ⇒\n // install every skill the source exposes (no `-s`).\n skills: z.array(SkillArg).default([])\n});\n/** One centrally accepted, immutable Agent Skills bundle enabled for an agent.\n * Content is fetched separately in bounded chunks; AgentSpec carries metadata\n * only so register/agent-upsert frames stay small. */\nexport const ManagedSkillEntry = z\n .object({\n id: z.string().uuid(),\n name: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/),\n revision: z.number().int().positive(),\n digest: z.string().regex(/^sha256:[a-f0-9]{64}$/)\n})\n .strict();\n/**\n * The editable agent definition the CP owns and the daemon needs to run it:\n * prompt + runtime selection. The launch protocol carries this config and the\n * daemon synthesizes the system prompt locally; `description` IS the prompt.\n */\nexport const AgentSpec = z.object({\n name: z.string(),\n // Human-readable bot name. CP snapshots/upserts always ship value or null so\n // clearing it removes a stale daemon-local display name; absent remains\n // available to hand-authored/partial specs as \"leave unchanged\".\n displayName: z.string().nullable().optional(),\n // Absolute, publicly-fetchable avatar URL the CP resolves from the agent's icon\n // (agent.icon → the CP icon endpoint for runtime/glyph, or the image URL directly).\n // The daemon uses it as the Slack per-message `icon_url` (chat:write.customize) —\n // the sibling of displayName→username (PR #539). CP ships value or null so clearing\n // the icon drops the override; null/absent ⇒ Slack keeps the app's default avatar.\n iconUrl: z.string().url().nullable().optional(),\n // The system prompt seed; appended to the daemon's standing prompt. The CP always\n // ships it as a string — a cleared description replicates as \"\" so the daemon\n // overwrites a stale seed; an absent key means \"leave unchanged\" (hand-authored/\n // partial specs). Deliberately NOT nullable: older daemons parse this as a plain\n // string and would reject a null register/ok roster entry, failing the whole\n // handshake. An empty prompt seed and \"no description\" are equivalent, so the \"\"\n // collapse is lossless.\n description: z.string().optional(),\n runtime: z.string().optional(), // which ACP runtime to run, e.g. \"claude\" / \"codex\"\n // Per-runtime override vocabularies (model / effort / permission mode). Switching\n // runtime invalidates them, so the CP must be able to CLEAR them, not just set them:\n // absent ⇒ leave the on-disk value alone (hand-authored agent.json / partial spec)\n // null ⇒ clear the override (revert to the runtime's own default)\n // string ⇒ set it\n // The CP's agentRecordToSpec always ships these (value or null) so a clear replicates.\n model: z.string().nullable().optional(), // runtime model, e.g. \"opus\"\n reasoningEffort: z.string().nullable().optional(),\n executionMode: z.string().optional(), // e.g. \"byoc\"\n outputMode: z.enum(['none', 'minimal', 'low', 'medium', 'high']).optional(), // platform output verbosity → agent.json output.mode ('none' = session-only, nothing to the IM)\n showFooter: z.boolean().optional(), // render platform attribution/session footers; absent ⇒ leave agent.json unchanged\n fastMode: z.boolean().optional(), // runtime fast mode (ACP `model_config` toggle); absent ⇒ leave runtime default\n permissionMode: z.string().nullable().optional(), // runtime permission/approval mode (ACP `mode` selector); absent ⇒ leave alone, null ⇒ clear\n // Explicit opt-in: when false, conversation participants cannot change runtime\n // settings (model, effort, permission mode, fast mode) or answer approval\n // requests. Agent editors decide pending requests from the console instead.\n allowRuntimeChangesInChat: z.boolean().optional(),\n // Operational message-processing toggle (orthogonal to placement). When true the\n // agent stays placed/connected but the daemon skips ALL turn dispatch (platform,\n // webchat, cron). Optional (not defaulted) so an absent value leaves the on-disk\n // agent.json pause untouched — same contract as fastMode/permissionMode.\n pause: z.boolean().optional(),\n workspace: AgentWorkspace.optional(), // where it runs; absent ⇒ daemon defaults to scratch\n env: z.record(z.string(), z.string()).optional(), // extra env injected into the runtime\n // Write-only secret env vars: same injection as `env` (merged into the spawned\n // child's environment, secrets winning on a key collision), but their VALUES never\n // travel back out — the CP DTO exposes only the key names, and the console masks\n // them. Plaintext at rest (like `env`) and shipped over the TLS WS; \"secret\" here\n // means write-only from the API/UI, not KMS-sealed. Always shipped (even {}) so a\n // removed secret replicates, same contract as `env` below.\n secrets: z.record(z.string(), z.string()).optional(),\n // Which memory backend the agent uses (design: docs/designs/memory-evolution.md):\n // managed — our <agent-root>/memory/ directory (default)\n // native — the runtime's own memory (Claude auto-memory / Codex memories),\n // redirected under the agent root for per-agent isolation\n // external — an outside service (mem0); not yet implemented\n // none — disable both daemon-managed and runtime-native persistent memory\n // Optional (absent ⇒ leave the on-disk agent.json value alone — same contract as\n // fastMode/pause). A brand-new agent with no value defaults to managed daemon-side.\n memory: AgentMemoryBinding.optional(),\n // Names of daemon-configured MCP servers (daemon config `mcpServers`, reported\n // via `facts/daemon-runtimes`) to attach at `session/new`. Empty/absent ⇒ none.\n mcpServers: z.array(z.string()).default([]),\n // Skill sources to install into the workspace before the ACP host spawns\n // (design: shared-skills.md). Unlike mcpServers (names resolved daemon-side),\n // these are SELF-CONTAINED entries — the daemon needs nothing but agent.json to\n // run `npx skills`. Always shipped (even []) so removing the last skill replicates.\n skills: z.array(AgentSkillEntry).default([]),\n // Centrally accepted `.skill` ZIP revisions. Unlike Git source entries above,\n // these are digest-addressed metadata; the daemon downloads/cache-verifies the\n // bundle through managed-skill/read before session start.\n managedSkills: z\n .array(ManagedSkillEntry)\n .max(64)\n .refine((entries) => new Set(entries.map((entry) => entry.id)).size === entries.length, {\n message: 'managed skill ids must be unique'\n })\n .default([]),\n // Agent→agent call authorization (design §2.5). `callPolicy` gates who may wake\n // this agent via the `messageAgent` tool: 'all' ⇒ any peer in the org, 'selected'\n // ⇒ only agents in `allowedCallerAgentIds`. Replicated CP→daemon so the daemon can\n // enforce the policy LOCALLY on same-daemon delivery (no CP hop on the hot path).\n // Optional (absent ⇒ leave the on-disk agent.json value alone — same contract as\n // pause/memory); `allowedCallerAgentIds` always ships (even []) so removing the last\n // allowed caller replicates.\n callPolicy: z.enum(['all', 'selected']).optional(),\n allowedCallerAgentIds: z.array(z.string()).default([]),\n // Outbound half of agent→agent authorization. `selected` means this agent may\n // discover/message only peers in `allowedTargetAgentIds`. The target's inbound\n // policy must also allow this agent; effective authorization is the intersection.\n // Both fields remain optional when decoding an older CP payload so a mixed-version\n // update cannot retain an on-disk `selected` mode while silently clearing its list.\n // A current CP always ships both fields, including [] to clear the final member.\n outboundPolicy: z.enum(['all', 'selected']).optional(),\n allowedTargetAgentIds: z.array(z.string()).optional(),\n // Self-introduce-on-join (issue #536): when true, on a genuine new channel join the\n // agent proactively introduces itself to the peers already there (via listAgents\n // → messageAgent) so they can record it in memory. Replicated CP→daemon. Optional\n // (absent ⇒ leave the on-disk agent.json value alone — same contract as pause/fastMode).\n introduceOnJoin: z.boolean().optional(),\n // Per-agent OS sandbox preference (issue #642). It is effective only when the\n // host has bwrap/sandbox-exec; daemon `security.requireSandbox` forces it on and\n // prevents daemon startup when no mechanism exists. Optional means leave the\n // on-disk agent.json value alone; a brand-new agent defaults to false.\n restrictFileAccess: z.boolean().optional()\n});\nexport const AgentLaunch = z.object({\n // C→D, carries ControlExt(epoch)\n agentId: z.string().uuid(),\n runtime: z.string(), // must be in RegisterReq.capabilities.runtimes\n workspaceId: z.string().uuid(),\n capabilities: z.array(z.string()), // the active-capability pin (§8.1)\n spec: AgentSpec, // prompt/model/env — arrives at start, no separate CRUD needed\n mode: z.enum(['long_lived', 'per_turn']).default('long_lived'), // 🅰️ decision #2 knob\n // Web API launch provenance (session-visibility.md §4.4): CP-minted when the\n // launch was requested by a console user, echoed back by the daemon on the\n // resulting session's `event/session` so ingest can classify it `private`\n // with that user as owner. Optional — CLI/orchestration launches and older\n // CPs omit it. NOT the launchId fence (which is per-launch, not per-user).\n launchCorrelationId: z.string().uuid().optional()\n});\n/**\n * Live agent CRUD (C→D): the console edited an agent's spec; push it so a\n * running daemon reloads without waiting for the next launch. `agent/remove`\n * tears the agent down. Deleting an agent never relaunches it.\n */\nexport const AgentUpsert = z.object({\n agentId: z.string().uuid(),\n spec: AgentSpec\n});\nexport const AgentRemove = z.object({\n agentId: z.string().uuid()\n});\n/**\n * Safe cold-move lifecycle (C→D REQ → generic `ack`). `agent/detach`\n * quiesces the agent and archives its daemon-local root; `agent/activate`\n * atomically applies the authoritative spec/integration/cron bundle, restores\n * and exact-prunes an archive when present, then makes the agent servable.\n */\nexport const AgentDetach = z.object({\n agentId: z.string().uuid(),\n /** Fences late lifecycle retries from a superseded move operation. */\n moveId: z.string().uuid(),\n /** Scratch→GitHub conversion guard. The daemon drains the agent first, then\n * ACKs only when the live scratch working directory is still empty. */\n requireEmptyWorkspace: z.boolean().optional()\n});\nexport const AgentActivate = z.object({\n agentId: z.string().uuid(),\n moveId: z.string().uuid(),\n /**\n * One authoritative, acknowledged bootstrap bundle. Unlike the live CRUD\n * EVTs, these definitions are synchronously persisted under the staging gate\n * before activation can ACK, so a same-id stale secret/spec cannot survive.\n */\n spec: AgentSpec,\n integrations: z.array(IntegrationSpec),\n crons: z.array(CronUpsert),\n /** Prove the requested workspace can be materialized before activation ACK.\n * Used by scratch→GitHub conversion so a failed clone can be rolled back. */\n prepareWorkspace: z.boolean().optional(),\n /** Reconcile the daemon-local workspace to the authoritative mode/repo/branch.\n * The daemon preserves the checkout when that materialization is unchanged,\n * and replaces its contents when it changed. */\n reconcileWorkspace: z.boolean().optional()\n});\nexport const AgentLaunched = z.object({\n // D→C, REP/EVT\n agentId: z.string().uuid(),\n launchId: z.string().uuid(), // new fence value\n acpSessionId: z.string().optional(), // 🅰️ present iff long-lived ACP session (default)\n startedAt: z.string().datetime(),\n runtime: z.string() // e.g. \"claude\" / \"codex\"\n});\nexport const AgentStop = z.object({\n agentId: z.string().uuid(),\n launchId: z.string().uuid(),\n reason: z.string()\n});\nexport const AgentActivity = z.object({\n // D→C, EVT — activity-probe (§7.4)\n agentId: z.string().uuid(),\n launchId: z.string().uuid(),\n state: z.enum(['thinking', 'tool_call', 'awaiting_permission', 'idle']),\n ts: z.string().datetime()\n});\nexport const AgentScopeDenied = z.object({\n // D→C, EVT — capability-scope audit (§8.1)\n agentId: z.string().uuid(),\n launchId: z.string().uuid(),\n capability: z.string()\n});\n/** Editor approval queue. The daemon owns the live resolver and durable local\n * history; the Control Plane only proxies this bounded, secret-masked summary. */\nexport const AgentPermissionRequestRecord = z.object({\n id: z.string().uuid(),\n agentId: z.string().uuid(),\n // Optional for rolling compatibility with daemons that predate session-scoped\n // approval rendering. Current daemons always report the owning ACP session id.\n sessionId: z.string().min(1).optional(),\n createdAt: z.string().datetime(),\n requesterId: z.string().nullable(),\n requesterName: z.string().nullable(),\n command: z.string().max(240),\n status: z.enum(['pending', 'allowed', 'denied', 'expired']),\n resolvedAt: z.string().datetime().nullable()\n});\nexport const AgentPermissionRequestList = z.object({\n agentId: z.string().uuid(),\n limit: z.number().int().min(1).max(100).default(50)\n});\nexport const AgentPermissionRequestPage = z.object({\n agentId: z.string().uuid(),\n requests: z.array(AgentPermissionRequestRecord)\n});\nexport const AgentPermissionDecision = z.object({\n agentId: z.string().uuid(),\n requestId: z.string().uuid(),\n decision: z.enum(['allow', 'deny'])\n});\n//# sourceMappingURL=agent.js.map","import { z } from 'zod';\n/**\n * Centralized MCP-provider distribution (C→D) — docs/designs/centralized-tool-management.md.\n *\n * The Control Plane owns MCP provider definitions and pushes them to the daemons\n * whose agents enable them (`mcpserver/upsert`, and the reconcile snapshot\n * `RegisterOk.mcpServers[]`). The daemon merges the spec into its `mcpServerDefs`\n * and attaches it at ACP `session/new` through the existing resolve path — a\n * pushed def is just an `http` MCP server.\n *\n * MCP-PROXY MODEL: in v1 the pushed `url` is a RELAY proxy URL and the injected\n * header is a short-lived **grant key** (`Authorization: Bearer …`) — never the\n * upstream endpoint or its real credential. Those stay on the CP + relay (§5).\n * SECURITY: `env`/`headers` may carry that bearer grant key — NEVER log this frame.\n */\n/** The `{name, value}[]` shape shared by MCP env + headers (mirrors the daemon's local McpServerDef). */\nconst NameValueList = z.array(z.object({ name: z.string(), value: z.string() })).default([]);\n/**\n * One MCP server definition the CP pushes to a daemon. Shape mirrors the daemon's\n * local `McpServerDef` (daemon config-schema.ts) with `name` inlined (the daemon\n * config keys the map by name). Transport-agnostic on the wire; the CP restricts\n * what it emits (v1 pushes proxied `http` defs only — the `sse`/`stdio`-only\n * restriction is a CP-side policy, not a wire constraint).\n */\nexport const McpServerSpec = z\n .object({\n name: z.string(),\n transport: z.enum(['stdio', 'http', 'sse']).default('stdio'),\n command: z.string().optional(),\n args: z.array(z.string()).default([]),\n env: NameValueList,\n url: z.string().optional(),\n headers: NameValueList\n})\n .superRefine((def, ctx) => {\n if (def.transport === 'stdio' && !def.command)\n ctx.addIssue({ code: 'custom', path: ['command'], message: 'a stdio MCP server requires \"command\"' });\n if (def.transport !== 'stdio' && !def.url)\n ctx.addIssue({ code: 'custom', path: ['url'], message: `a ${def.transport} MCP server requires \"url\"` });\n});\n/** C→D EVT (`mcpserver/upsert`) — add or replace a pushed MCP server def on the daemon. */\nexport const McpServerUpsert = McpServerSpec;\n/** C→D EVT (`mcpserver/remove`) — drop a pushed MCP server def by name. */\nexport const McpServerRemove = z.object({ name: z.string() });\n//# sourceMappingURL=mcpserver.js.map","import { z } from 'zod';\nimport { Platform } from './route.js';\n/**\n * Bot-AGNOSTIC agent-collaboration routing snapshot (agent-collaboration §2.3 / §6.2 / §6.5).\n *\n * The existing shared-bot `members` table is keyed by botId (`BotAssignment`) and\n * CANNOT address an agent on a DIFFERENT bot / arbitrary channel. This snapshot is\n * the fix: it maps a channel — `(orgId, platform, channelId)` — to the per-agent\n * placement + call policy the relay needs to route a cross-daemon `rd/agentmsg` and\n * the target daemon needs to terminal-verify a remote caller.\n *\n * It carries NO message body — pure routing/policy metadata, like the rest of the\n * control plane. The SAME shape is distributed two ways (§6.5):\n * - CP→relay over the `rc/*` wire (`rc/collab-routes`) — the relay routes\n * `toAgentId` → owning `daemonId` and authorizes the caller/target policy.\n * - CP→daemon over the daemon↔CP wire — as a `register/ok` field (reconnect\n * baseline) + a `collaboration/routes` EVT (hot push) — so the OWNING daemon of\n * the target can terminal-verify (defense in depth, §2.5 #4) the remote caller's\n * org/channel/placement against its OWN copy, never trusting the relay's claim\n * blindly.\n *\n * FOLLOW-UP (scoped down in P2, see PR description): the full versioned lifecycle\n * of §6.5 — per-entry tombstones, TTL/expiry after a CP disconnect, and\n * fail-closed-on-stale — is NOT fully implemented here. `generation` is present as\n * the version hook and the snapshot is FULL-REPLACE (converge-don't-diff, same as\n * `register/ok`), which is enough to route + authorize on a live CP. TTL-expiry and\n * tombstone semantics are a follow-up within this phase.\n */\n/** One agent's placement + call policy within a channel. `daemonId` is the owning\n * daemon the relay forwards to; `integrationId` is the DEFINITE reply integration\n * (§6.2 — no fallback to \"first connection\"). */\nexport const CollabAgentPlacement = z.object({\n agentId: z.string().uuid(),\n daemonId: z.string().uuid(),\n integrationId: z.string().uuid().optional(),\n /** Public Slack app id (`A…`) for this agent's bot. Receivers use it only to\n * recognize AgentConnect-authored platform messages and keep agent-to-agent\n * activation on the trusted `messageAgent` path. */\n botAppId: z.string().optional(),\n callPolicy: z.enum(['all', 'selected']).default('all'),\n allowedCallerAgentIds: z.array(z.string()).default([]),\n /** Caller-side authorization. Effective A→B access requires A's outbound\n * policy to admit B and B's inbound call policy to admit A. */\n outboundPolicy: z.enum(['all', 'selected']).default('all'),\n allowedTargetAgentIds: z.array(z.string()).default([]),\n // Directory name of the agent — carried so any daemon holding the snapshot can label a\n // REMOTE peer (caller or target) by name in a visible agent-call post, without a CP\n // round-trip or having listed the channel. `name` is the slug; `displayName` the\n // human-readable label. Optional for back-compat with an older CP that omits them.\n name: z.string().optional(),\n displayName: z.string().optional()\n});\n/**\n * One agent's placement + call policy carried OUTSIDE any channel — the org-scoped\n * peer directory entry.\n *\n * Every structure on the CP→daemon and CP→relay wires is channel-keyed, so an agent\n * with NO IM integration (webchat, hook, dream, memory-only) never appears in any\n * `channels[]` entry at all. The channel-keyed snapshot structurally cannot express\n * \"which agents exist in this org\", which is precisely the input channel-free\n * authorization needs: discovery and A2A authorization depend only on the directional\n * call policy (`outboundPolicy`/`allowedTargetAgentIds` on the caller,\n * `callPolicy`/`allowedCallerAgentIds` on the target), org-scoped, with channel\n * demoted to an optional filter. Hence the flat list below.\n */\nexport const CollabOrgAgent = CollabAgentPlacement.extend({\n // Org ids are opaque strings (see CollabChannelRoute) — carried per entry because\n // the flat list is not nested under an org-keyed parent. Cross-org pairs never resolve.\n orgId: z.string().min(1)\n});\n/** All agents present in one channel, across daemons. `orgId` scopes routing +\n * authorization: a cross-org caller/target pair never resolves (§2.5 — cross-org\n * rejected). */\nexport const CollabChannelRoute = z.object({\n // Org ids are opaque strings (Prisma uses cuid(); the seeded dev org uses\n // `org_default...`), unlike daemon/agent/integration ids which are UUIDs.\n orgId: z.string().min(1),\n platform: Platform,\n channelId: z.string().min(1),\n agents: z.array(CollabAgentPlacement)\n});\n/**\n * The full collaboration snapshot — FULL-REPLACE (converge-don't-diff): the\n * recipient replaces its whole table with `channels`. `generation` monotonically\n * increases per source so a recipient can ignore a stale re-order (version hook for\n * the §6.5 lifecycle follow-up).\n */\nexport const CollabRoutesSnapshot = z.object({\n generation: z.number().int().nonnegative().default(0),\n channels: z.array(CollabChannelRoute).default([]),\n /**\n * FLAT org-scoped directory, alongside (not instead of) `channels`. It is the only\n * place an integration-less agent can appear — see `CollabOrgAgent` — and therefore\n * the authorization input for channel-free A2A. `default([])` keeps a snapshot from\n * an older CP (which advertises no `agent-directory-org-scope-v1`) decodable.\n */\n agents: z.array(CollabOrgAgent).default([])\n});\n//# sourceMappingURL=collab.js.map","import { z } from 'zod';\n/**\n * Deployment GitHub App identity used for ordinary commits made by an agent.\n * This is public attribution metadata, not a credential.\n */\nexport const GitCommitIdentity = z.object({\n name: z.string().min(1),\n email: z.string().min(1)\n});\n/**\n * Git credentials (github-app workspaces) — daemon-pulled, CP-minted.\n *\n * The CP holds the GitHub App private key and mints short-lived (1h,\n * non-renewable) installation access tokens scoped to a single repository;\n * the daemon pulls one on demand right before a remote git operation and\n * holds it in memory only. Unlike `secrets/*` (lease + reference semantics,\n * still unwired), the grant here carries the TOKEN MATERIAL itself — same\n * plaintext-over-TLS-WS posture as `integration/upsert`, and the same\n * discipline: **never log the payload**.\n *\n * The daemon may only name an agentId — the CP resolves agent → workspace →\n * repo → installation itself, so a daemon can never pick a repo it wasn't\n * assigned. Failures come back as correlated `error` REPs: `SCOPE_DENIED`\n * (not a github-app workspace, or agent not placed on this daemon — stop\n * asking), `LEASE_DENIED` (installation uninstalled/suspended or the repo\n * left its grant set — recoverable only by an operator), `RATE_LIMITED`,\n * `INTERNAL`.\n */\n/**\n * Token capability classes (webhook-triggers-and-github-events.md P2.5 write-back).\n * `contents` is the git data plane (the pre-capabilities behavior); `issues` /\n * `pull_requests` buy the agent `gh` write-back (issue/PR comments), and\n * `actions` buys GitHub Actions inspection/execution. Every\n * General agent credentials mint every capability admitted by the repo's\n * `gitAccess` / authorization tier — a read-only agent gets read-only\n * issues/PR scopes and no Actions capability.\n * The one exception is purpose=github_hook_reply: a daemon-owned writer whose\n * token never enters the agent environment and is gated by an enabled hook.\n */\nexport const GitCredCapability = z.enum(['contents', 'issues', 'pull_requests', 'actions']);\nexport const GitCredRequest = z.object({\n // D→C, REQ\n agentId: z.string().uuid(),\n reason: z.enum(['clone', 'fetch', 'pull', 'push', 'helper']).optional(), // observability only\n // Absent ⇒ ['contents'] — pre-P2.5 daemons keep byte-identical behavior.\n capabilities: z.array(GitCredCapability).nonempty().optional(),\n // The daemon-owned GithubPoster is a narrower consumer than an agent's git/\n // gh tools: its token never enters the agent environment and may only back\n // the one final comment for an enabled GitHub hook turn. Marking that purpose\n // explicitly lets the CP apply the hook authorization instead of incorrectly\n // clamping the comment token to the workspace contents gitAccess.\n purpose: z.literal('github_hook_reply').optional(),\n // Trusted hook identity copied from the relay-delivered rd/msg. Required by\n // the CP for purpose=github_hook_reply so authorization stays rename-safe on\n // HookDef.repoId instead of comparing mutable owner/repo display names.\n hookId: z.string().uuid().optional(),\n // A poster sets this only after GitHub rejects a cached token with 401/403.\n // The CP then bypasses its installation-token cache exactly once; ordinary\n // git/gh requests ignore it.\n forceRefresh: z.boolean().optional(),\n // Absent ⇒ the agent's workspace repo (pre-multi-repo behavior). \"owner/repo\".\n // The CP admits only workspace ∪ the agent's AgentRepoAuthorization rows and\n // mints the requested capability subset at the row's access tier — the daemon\n // still cannot pick an arbitrary repo (agent-multi-repo-authorization.md\n // decision 2). A purpose=github_hook_reply request is separately gated by an\n // enabled GitHub hook and receives only issues/PR write, never contents. Old\n // CPs strip this field and answer with a WORKSPACE grant: consumers MUST\n // verify grant.repoFullName against what they asked for before trusting it.\n repoFullName: z.string().optional()\n});\nexport const GitCredGrant = z.object({\n // C→D, REP (plaintext token — never log)\n username: z.literal('x-access-token'), // fixed HTTPS basic-auth username for installation tokens\n token: z.string(), // ghs_… — new stateless format runs ~520 chars; never assume a length\n ttlSec: z.number().int(), // CP-computed remaining life, 60s clock-skew allowance already shaved.\n // Daemons MUST track expiry as monotonic receivedAt+ttlSec (a skewed local\n // clock must never resurrect a dead token); `expiresAt` is observability only.\n expiresAt: z.string().datetime(),\n repoFullName: z.string(), // owner/repo — helper path-match + diagnostics\n access: z.enum(['read', 'write'])\n});\n//# sourceMappingURL=gitcred.js.map","import { z } from 'zod';\nimport { Platform, RouteAssign } from './route.js';\nimport { CronUpsert } from './cron.js';\nimport { SecretsGrant } from './secrets.js';\nimport { AgentSpec } from './agent.js';\nimport { IntegrationSpec } from './integration.js';\nimport { McpServerSpec } from './mcpserver.js';\nimport { MemoryConnectionSpec } from './memory-connection.js';\nimport { CollabRoutesSnapshot } from './collab.js';\nimport { GitCommitIdentity } from './gitcred.js';\n/**\n * Capability upload + the reconcile snapshot — protocol §3.3.\n *\n * `register/ok` is the authoritative source of truth: the daemon converges its\n * local cache to it. CP wins all conflicts, so re-issuing the same snapshot is\n * idempotent.\n */\nexport const RegisterReq = z.object({\n host: z.string(), // hostname (display only)\n capabilities: z.object({\n platforms: z.array(Platform), // D3 adapters present\n runtimes: z.array(z.string()), // e.g. [\"claude\",\"codex\"]\n acp: z.boolean(), // can this daemon host ACP sessions (D6)?\n features: z.array(z.string()).default([]) // e.g. [\"cli-wrapper-fallback\",\"worktree-iso\"]\n }),\n maxAgents: z.number().int(), // concurrency ceiling for placement (C3)\n localState: z.object({\n // what the daemon currently believes it owns (for reconcile)\n assignments: z.array(z.string()), // sessionKeys it is actively serving\n crons: z.array(z.string()), // cronIds it has scheduled\n leases: z.array(z.string()), // leaseIds it holds\n // Active on-disk replicas. `unknown` is the rolling-upgrade/legacy value:\n // the CP may prune it only when the durable row proves the replica moved.\n // Defaults keep an older daemon compatible with a newer CP.\n agents: z.array(z.object({ agentId: z.string(), origin: z.enum(['cp', 'unknown']) })).default([]),\n integrations: z.array(z.object({ integrationId: z.string(), origin: z.enum(['cp', 'unknown']) })).default([]),\n // Durable fail-closed move tombstones. A newer CP repairs entries with a\n // valid token after register/ok. A missing token represents corrupt local\n // metadata: the daemon keeps that agent drained for manual repair without\n // making the whole registration undecodable.\n stagedAgents: z.array(z.object({ agentId: z.string(), moveId: z.string().uuid().optional() })).default([])\n })\n});\n/**\n * One relay the daemon SHOULD hold an outbound WS to (shared-bot-relay.md §5).\n * The roster is all-to-all by design: a webchat/webhook landing on ANY relay\n * instance must find this daemon's connection without cross-instance forwarding.\n * That only holds if `url` (the relay's registered `daemonUrl`) routes to that\n * SPECIFIC instance — the daemon confirms the landing spot against\n * `rd/hello/ok.relayId` and treats a mismatch as a deployment misroute.\n */\nexport const RelayRosterEntry = z.object({\n relayId: z.string().uuid(),\n url: z.string() // the relay's daemonUrl — per-instance routable, never a pool LB\n});\n/**\n * C→D EVT (`relay/roster`) — hot roster update (relay registered / swept).\n * Carries the WHOLE desired set, same converge-don't-diff semantics as the\n * `register/ok.relays` snapshot it refreshes.\n */\nexport const RelayRosterUpdate = z.object({\n relays: z.array(RelayRosterEntry)\n});\nexport const RegisterOk = z.object({\n routingEpoch: z.number().int(), // version of the routing table this snapshot reflects\n // CP protocol capabilities. Default keeps a new daemon compatible with an\n // older CP during rolling deploys; old daemons ignore this additive field.\n serverFeatures: z.array(z.string()).default([]),\n // Public attribution for github-app workspace commits. Derived from this\n // deployment's App slug; optional so new daemons still accept an older CP.\n gitCommitIdentity: GitCommitIdentity.optional(),\n // Authoritative reconcile snapshot — daemon converges its local cache to this:\n assignments: z.array(RouteAssign), // the route/assign set the daemon SHOULD own\n agents: z.array(AgentSpec.extend({ agentId: z.string().uuid() })).default([]), // spec set CP wants present; daemon converges\n crons: z.array(CronUpsert), // the cron set it SHOULD run\n // Platform integrations this daemon SHOULD hold — FILTERED to this daemon (never\n // org-wide), since each element carries plaintext tokens. Never log this array.\n integrations: z.array(IntegrationSpec).default([]),\n // MCP server defs this daemon SHOULD hold — FILTERED to this daemon (only providers\n // its agents enable). In the MCP-proxy model these carry a relay proxy URL + a bearer\n // grant key (not the upstream secret), but treat as sensitive — never log this array.\n // Defaulted so a pre-MCP-registry CP's snapshot still parses.\n mcpServers: z.array(McpServerSpec).default([]),\n // External-memory defs this daemon's agents reference. Relay grants and local\n // secret leases are daemon-private and must never be logged.\n memoryConnections: z.array(MemoryConnectionSpec).default([]),\n leases: z.array(SecretsGrant), // secret leases it SHOULD hold\n // Relay roster — the relays this daemon SHOULD dial (webchat ingress now;\n // shared-bot/webhook with milestone B). Hot updates ride `relay/roster`;\n // defaulted so a pre-relay CP's snapshot still parses.\n relays: z.array(RelayRosterEntry).default([]),\n // Bot-agnostic collaboration routing snapshot (agent-collaboration §2.3 / §6.5) —\n // the reconnect BASELINE for this daemon's terminal-verify of REMOTE agent callers.\n // Scoped to channels this daemon's agents participate in. Hot changes ride the\n // `collaboration/routes` EVT. Defaulted so a pre-collab CP's snapshot still parses.\n collabRoutes: CollabRoutesSnapshot.default({ generation: 0, channels: [], agents: [] }),\n drop: z.object({\n // things in localState the CP says to release\n assignments: z.array(z.string()),\n crons: z.array(z.string()),\n // A missed live move archives the replica (preserving workspace/memory); a\n // missed delete removes a replica that carries the explicit CP marker.\n agents: z.array(z.object({ agentId: z.string(), action: z.enum(['detach', 'remove']) })).default([]),\n integrations: z.array(z.string()).default([])\n })\n});\n//# sourceMappingURL=register.js.map","import { z } from 'zod'\nimport {\n DEFAULT_WORKSPACE_GIT_ALLOWED_ORIGINS,\n normalizeWorkspaceGitOrigin,\n RelayRosterEntry\n} from '@agentconnect.md/protocol'\n\n/** The `{name, value}[]` shape shared by runtime env, MCP env, and MCP headers. */\nconst NameValueList = z.array(z.object({ name: z.string(), value: z.string() })).default([])\n\nexport const RuntimeDefSchema = z.object({\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: NameValueList,\n // Operator/registry-owned read-only installation roots needed by a runtime\n // whose executable or dependencies live below a host path hidden from the\n // sandbox (most commonly HOME). Agent configuration can select a runtime but\n // cannot add entries here.\n readRoots: z.array(z.string()).optional()\n})\nexport type RuntimeDef = z.infer<typeof RuntimeDefSchema>\n\n// A daemon-configured MCP server, keyed by name in `config.mcpServers`. The name\n// is what an agent's `mcpServers` list references, and what the daemon reports\n// to the CP — definitions (command/url/headers) never leave the daemon.\n// The name \"agentconnect\" is reserved for the daemon's own injected bridge entry.\nexport const McpServerDefSchema = z\n .object({\n transport: z.enum(['stdio', 'http', 'sse']).default('stdio'),\n // stdio transport: the executable to spawn (required for stdio).\n command: z.string().optional(),\n args: z.array(z.string()).default([]),\n env: NameValueList,\n // Same trusted installation-root escape hatch as RuntimeDefSchema, for a\n // daemon-configured stdio MCP child spawned by the runtime.\n readRoots: z.array(z.string()).optional(),\n // http/sse transports: the server endpoint (required for http/sse).\n url: z.string().optional(),\n headers: NameValueList\n })\n .superRefine((def, ctx) => {\n if (def.transport === 'stdio' && !def.command)\n ctx.addIssue({ code: 'custom', path: ['command'], message: 'a stdio MCP server requires \"command\"' })\n if (def.transport !== 'stdio' && !def.url)\n ctx.addIssue({ code: 'custom', path: ['url'], message: `a ${def.transport} MCP server requires \"url\"` })\n })\nexport type McpServerDef = z.infer<typeof McpServerDefSchema>\n\nconst EnvironmentName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, 'invalid environment variable name')\nconst MemoryPluginCommandRef = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, 'invalid memory plugin commandRef')\nconst ProcessValue = z\n .string()\n .max(16 * 1024)\n .refine((value) => !value.includes('\\0'), 'process value contains NUL')\nconst WorkspaceGitOrigin = z.string().transform((value, ctx) => {\n try {\n return normalizeWorkspaceGitOrigin(value)\n } catch {\n ctx.addIssue({\n code: 'custom',\n message: 'workspace Git origins must be exact credential-free HTTPS or SSH origins without a path'\n })\n return z.NEVER\n }\n})\n\n/** Operator-owned local memory-plugin allowlist. A tenant/CP sends only the map\n * key (`commandRef`); command, args, static env, and logical-secret→env mapping\n * never cross the control plane. */\nexport const StdioMemoryPluginDefSchema = z\n .object({\n command: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => !value.includes('\\0'), 'command contains NUL'),\n args: z.array(ProcessValue).max(128).default([]),\n env: z\n .array(z.object({ name: EnvironmentName, value: ProcessValue }).strict())\n .max(128)\n .default([]),\n secretEnv: z.record(z.string().min(1).max(128), EnvironmentName).default({})\n })\n .strict()\n .superRefine((def, ctx) => {\n const staticNames = def.env.map((entry) => entry.name)\n if (new Set(staticNames).size !== staticNames.length) {\n ctx.addIssue({ code: 'custom', path: ['env'], message: 'stdio memory plugin env names must be unique' })\n }\n const secretTargets = Object.values(def.secretEnv)\n if (new Set(secretTargets).size !== secretTargets.length) {\n ctx.addIssue({\n code: 'custom',\n path: ['secretEnv'],\n message: 'stdio memory plugin secret env targets must be unique'\n })\n }\n if (secretTargets.some((name) => staticNames.includes(name))) {\n ctx.addIssue({ code: 'custom', path: ['secretEnv'], message: 'secret env must not overwrite static env' })\n }\n })\nexport type StdioMemoryPluginDef = z.infer<typeof StdioMemoryPluginDefSchema>\n\nexport const ConfigSchema = z.object({\n version: z.literal(1),\n daemonId: z.string().optional(),\n // Base URL of the Web App console; used to build the §9.1 \"details\" deep link\n // (`<webAppUrl>/sessions/<sessionId>`). Unset ⇒ the daemon adopts the URL the CP sends\n // down on `auth/ok` (the CP is authoritative for its own console origin); only truly\n // absent when neither is set. A local config value wins over the CP-provided one.\n webAppUrl: z.string().optional(),\n controlPlane: z\n .object({\n enabled: z.boolean().default(true),\n url: z.string().optional(),\n key: z.string().optional(), // CP API key (opaque); sent as `apiKey` on the auth frame\n heartbeatMs: z.number().int().default(15000)\n })\n .default({ enabled: false, heartbeatMs: 15000 }),\n agentsDir: z.string().optional(), // resolved against root if absent\n runtimes: z.record(z.string(), RuntimeDefSchema).optional(),\n // MCP servers this daemon can attach to agent sessions (reported to the CP as\n // facts by name + transport; agents opt in by name via their `mcpServers` list).\n mcpServers: z.record(z.string(), McpServerDefSchema).optional(),\n // Local memory plugins are daemon-private, operator-installed extensions.\n // Agent/tenant configuration can reference a key but can never supply a\n // command, path, args, or secret environment target.\n memoryPlugins: z.record(MemoryPluginCommandRef, StdioMemoryPluginDefSchema).optional(),\n security: z\n .object({\n // Prevent ACP runtimes from implicitly inheriting apps/connectors attached\n // to the signed-in cloud account. Explicit local and daemon-injected MCP\n // servers remain available. Set false only to opt this daemon out.\n isolateAccountApps: z.boolean().default(true),\n // Daemon-wide sandbox policy (issue #312). When true, startup fails unless\n // Linux SRT/bwrap is available and every agent runs sandboxed; the\n // console locks the per-agent option on. false leaves it agent-selectable.\n requireSandbox: z.boolean().default(false),\n // Operator-owned remote-origin policy for daemon-managed workspace clone/pull.\n // Exact scheme + host + port only; [] disables remote Git workspaces.\n workspaceGitAllowedOrigins: z.array(WorkspaceGitOrigin).default([...DEFAULT_WORKSPACE_GIT_ALLOWED_ORIGINS])\n })\n .default({\n isolateAccountApps: true,\n requireSandbox: false,\n workspaceGitAllowedOrigins: [...DEFAULT_WORKSPACE_GIT_ALLOWED_ORIGINS]\n }),\n // Relay roster the CP last published (shared-bot-relay.md §5). Persisted whole so\n // the daemon can re-dial its relays at boot while the CP is unreachable (graceful\n // degradation); the CP's register/ok snapshot re-converges it authoritatively once\n // connected. CP-owned — overwritten on every roster converge, not hand-edited.\n relays: z.array(RelayRosterEntry).default([]),\n logging: z\n .object({ level: z.enum(['trace', 'debug', 'info', 'warn', 'error']).default('info') })\n .default({ level: 'info' }),\n limits: z\n .object({\n maxAgents: z.number().int().default(32),\n maxConcurrentSessions: z.number().int().default(32),\n // Idle window before the sweep TTL-closes a session (§7.3) AND reaps its\n // agent's ACP host back to `provisioned` (§7.2). Background work is protected\n // by the SDK-lifecycle lease (a session with live background tasks or a running\n // SDK cycle is not reclaimed regardless of this window — see\n // docs/designs/background-task-aware-reclaim.md), so this no longer has to be\n // stretched to \"long enough that background jobs finish first\". 15min: reclaim\n // genuinely-idle hosts promptly (freeing runtime child RSS); the lease, not this\n // window, is what keeps background work alive. (Was widened to 2h by bb328c01 as\n // an interim workaround before the lease existed; now dialed back.)\n agentIdleTimeoutMs: z.number().int().default(900_000),\n // Absolute host lifetime ceiling (from host start). The background-task lease\n // defers idle reclaim while work is in flight; this bounds that deferral so a\n // wedged / never-ending background task (a hung build, a long-lived dev server)\n // can't pin an otherwise-idle host forever. Past this, the sweep force-reclaims\n // even with live background work (logged at warn). Must exceed agentIdleTimeoutMs\n // to have any effect. 6h.\n agentMaxLifetimeMs: z.number().int().default(21_600_000),\n // How often the idle sweep runs: reaps idle ACP adapter children back to\n // `provisioned` (§7.2) and TTL-closes idle sessions (§7.3). Keep well below\n // agentIdleTimeoutMs so a host lingers at most one interval past its window.\n idleSweepMs: z.number().int().default(60_000),\n // Quiet window before the sweep removes an agent's materialized config-file\n // secrets (agents/config-file-env.ts) — much shorter than the host TTL: the\n // files are re-written before the next turn is dispatched, so a warm host\n // stays fully usable and this only bounds how long the secret material\n // rests on disk while no turn or background task is running.\n configFilesIdleMs: z.number().int().default(60_000),\n // SIGTERM/daemon-drain grace window: in-flight turns get this long to finish\n // before the daemon cancels stragglers and tears children down (§2.5/§5.3).\n shutdownDrainMs: z.number().int().default(25_000),\n // §7.3 force-cancel backstop: after `!stop` we send session/cancel and wait\n // this long; if the turn still hasn't yielded, we force-stop the host.\n cancelBackstopMs: z.number().int().default(30_000),\n // How many times to (re)try launching an agent's ACP host — spawn + the\n // `initialize` handshake — before giving up and surfacing the failure to the\n // session. Covers transient failures (a resource race, a slow cold start). A\n // deterministic failure (missing binary) just burns all attempts then reports.\n agentStartAttempts: z.number().int().min(1).default(3),\n // Fixed backoff between agent-start attempts.\n agentStartBackoffMs: z.number().int().min(0).default(500),\n // Cap (bytes) for inlining an inbound attachment into the ACP prompt.\n // Files larger than this are passed as a resource_link pointer, never\n // downloaded/base64'd — bounds daemon RSS and the prompt frame size.\n maxAttachmentBytes: z\n .number()\n .int()\n .default(8 * 1024 * 1024)\n })\n .default({\n maxAgents: 32,\n maxConcurrentSessions: 32,\n agentIdleTimeoutMs: 900_000,\n agentMaxLifetimeMs: 21_600_000,\n idleSweepMs: 60_000,\n configFilesIdleMs: 60_000,\n shutdownDrainMs: 25_000,\n cancelBackstopMs: 30_000,\n agentStartAttempts: 3,\n agentStartBackoffMs: 500,\n maxAttachmentBytes: 8 * 1024 * 1024\n })\n})\nexport type Config = z.infer<typeof ConfigSchema>\n","import { chmodSync, readFileSync, existsSync, writeFileSync, mkdirSync, statSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { RelayRosterEntry } from '@agentconnect.md/protocol'\nimport { ConfigSchema, type Config } from './config-schema.js'\nimport { resolveRoot, configPath, defaultAgentsDir } from '../paths.js'\n\nexport interface FlatOverrides {\n apiUrl?: string\n apiKey?: string\n noCp?: boolean\n daemonId?: string\n logLevel?: Config['logging']['level']\n agentsDir?: string\n maxAgents?: number\n requireSandbox?: boolean\n}\n\nfunction protectConfigFile(file: string, writable = false): void {\n if (!existsSync(file)) return\n try {\n const current = statSync(file).mode & 0o777\n const desired = writable ? 0o600 : current & 0o700\n if (current !== desired) chmodSync(file, desired)\n } catch (err) {\n // Windows does not provide enforceable POSIX mode semantics. On POSIX,\n // never keep using a secret-bearing config if owner-only access cannot be\n // established.\n if (process.platform !== 'win32') throw err\n }\n}\n\nfunction writeConfigFile(file: string, raw: unknown): void {\n // `mode` protects new paths; chmod also repairs a legacy file created under a\n // loose umask. Do not chmod an existing custom parent directory.\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 })\n protectConfigFile(file, true)\n writeFileSync(file, JSON.stringify(raw, null, 2) + '\\n', { encoding: 'utf8', mode: 0o600 })\n protectConfigFile(file, true)\n}\n\nexport function loadConfig(\n opts: { root?: string; configPath?: string; overrides?: FlatOverrides; optional?: boolean; autoCreate?: boolean } = {}\n): Config {\n const root = resolveRoot(opts.root)\n const file = opts.configPath ?? configPath(root)\n // `optional` (used by `chat`) lets the daemon run with zero config: a missing\n // config.json yields the schema defaults, and runtimes fall back to the ACP registry.\n // `autoCreate` (used by `run`) goes a step further and writes that empty config to\n // disk so the daemon runs fully local (control plane disabled by default) and the\n // user has a file to edit later — no `agentconnect login` required.\n let raw: unknown\n if (existsSync(file)) {\n protectConfigFile(file)\n raw = JSON.parse(readFileSync(file, 'utf8'))\n } else if (opts.autoCreate) {\n raw = { version: 1 }\n writeConfigFile(file, raw)\n } else if (opts.optional) {\n raw = { version: 1 }\n } else {\n throw new Error(`config not found: ${file} (create it, pass --config, or run \\`agentconnect login\\`)`)\n }\n const cfg = ConfigSchema.parse(raw) // throws on invalid\n\n const o = opts.overrides ?? {}\n if (o.daemonId) cfg.daemonId = o.daemonId\n if (o.logLevel) cfg.logging.level = o.logLevel\n if (o.maxAgents !== undefined) cfg.limits.maxAgents = o.maxAgents\n if (o.requireSandbox) cfg.security.requireSandbox = true\n if (o.apiUrl) cfg.controlPlane.url = o.apiUrl\n if (o.apiKey) cfg.controlPlane.key = o.apiKey\n // Passing --api-url/--api-key implies \"connect to the CP\" (it defaults off),\n // so the one-line onboarding command works without a config edit. --no-cp wins.\n if (o.apiUrl || o.apiKey) cfg.controlPlane.enabled = true\n if (o.noCp) cfg.controlPlane.enabled = false\n\n cfg.agentsDir = o.agentsDir ?? cfg.agentsDir ?? defaultAgentsDir(root)\n return cfg\n}\n\n/**\n * Persist a (freshly-minted) `daemonId` back into config.json so it is stable\n * per install. Best-effort: a write failure is swallowed (the daemon still runs\n * with the in-memory id this session).\n */\nexport function persistDaemonId(root: string | undefined, daemonId: string, customConfigPath?: string): void {\n try {\n const file = customConfigPath ?? configPath(resolveRoot(root))\n protectConfigFile(file)\n const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n raw.daemonId = daemonId\n writeConfigFile(file, raw)\n } catch {\n // ignore — non-fatal\n }\n}\n\n/**\n * Persist the CP-published relay roster back into config.json so the daemon can\n * re-dial its relays at boot while the CP is unreachable (graceful degradation).\n * Whole-set (CP-owned): overwrites any prior value, so a swept relay is cleared.\n * Best-effort — a write failure is swallowed (the in-memory roster still drives\n * this session's dials).\n */\nexport function persistRelays(root: string | undefined, relays: RelayRosterEntry[], customConfigPath?: string): void {\n try {\n const file = customConfigPath ?? configPath(resolveRoot(root))\n protectConfigFile(file)\n const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n raw.relays = relays\n writeConfigFile(file, raw)\n } catch {\n // ignore — non-fatal\n }\n}\n","import { z } from 'zod'\nimport { AgentMemoryBinding, AgentSkillEntry, FeishuRegion, ManagedSkillEntry } from '@agentconnect.md/protocol'\n\nexport const BindMatchSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('mention') }),\n z.object({ kind: z.literal('dm') }),\n z.object({ kind: z.literal('keyword'), value: z.string() }),\n z.object({ kind: z.literal('auto') })\n])\nexport type BindMatch = z.infer<typeof BindMatchSchema>\n\nexport const BindRuleConfigSchema = z.object({\n channel: z.string().optional(), // absent = any channel\n thread: z.string().optional(),\n match: BindMatchSchema\n})\nexport type BindRuleConfig = z.infer<typeof BindRuleConfigSchema>\n\nexport const SlackConfigSchema = z.object({\n // 'direct' (default, and the shape of every pre-shared-bot agent.json): the daemon\n // opens the Socket Mode connection itself. 'shared': the bot's inbound lives on a\n // relay, so the daemon holds xoxb ONLY (send path) and opens no socket — routing is\n // arbitrated in the relay and delivered pre-addressed. See shared-bot-relay.md §7.3.\n mode: z.enum(['direct', 'shared']).default('direct'),\n // Multi-agent opt-in (shared mode only): the bot backs many agents, so the status\n // bar exposes an in-thread \"Switch agent\" control. A non-shareable shared bot routes\n // through the relay the same way but has one agent, so the control is suppressed.\n shareable: z.boolean().default(false),\n botToken: z.string(),\n appToken: z.string().optional(), // direct only (Socket Mode); absent for shared\n appId: z.string().optional(), // public A… app id used for Slack permission-update links\n signingSecret: z.string().optional(),\n botUserId: z.string().optional(), // filled at connect via auth.test if absent; provided by CP for shared\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n // Channels the operator switched OFF. bindRules only ADD reach, so an ungated\n // integration — which reaches every conversation through unscoped defaults — needs\n // this subtractive fence to say \"not here\". A muted channel matches no rule of this\n // integration: no mention, no thread continuity, no control command. A gated\n // integration leaves it empty; its Off is the ABSENCE of a conversation-scoped rule.\n mutedChannels: z.array(z.string()).default([]),\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type SlackConfig = z.infer<typeof SlackConfigSchema>\n\nexport const TelegramConfigSchema = z.object({\n botToken: z.string(), // BotFather \"123456:ABC…\" (single token; no app token / signing secret)\n botUserId: z.string().optional(), // numeric bot id, filled at connect via getMe if absent\n botUsername: z.string().optional(), // @username without the '@', for mention detection; filled via getMe\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see SlackConfigSchema.mutedChannels\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type TelegramConfig = z.infer<typeof TelegramConfigSchema>\n\nexport const DiscordConfigSchema = z.object({\n botToken: z.string(), // Discord Gateway bot token (single token; no app token / signing secret)\n applicationId: z.string().optional(), // public client id for the invite URL (not used to connect)\n botUserId: z.string().optional(), // numeric bot user id, filled at connect via the ready event if absent\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see SlackConfigSchema.mutedChannels\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type DiscordConfig = z.infer<typeof DiscordConfigSchema>\n\nexport const FeishuConfigSchema = z.object({\n // Direct opens the Feishu long connection. Shared is send-only: relay HTTP\n // ingress is delivered pre-addressed while this daemon keeps provider egress.\n mode: z.enum(['direct', 'shared']).default('direct'),\n appId: z.string(), // cli_… app identifier (semi-public); needed for REST and direct WS\n appSecret: z.string(), // app secret (single secret; no app token / signing secret)\n botOpenId: z.string().optional(), // bot's own open_id for mention detection; filled at connect via bot/info if absent\n region: FeishuRegion.default('feishu'), // open-platform gateway: feishu.cn (default) vs larksuite.com\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see SlackConfigSchema.mutedChannels\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type FeishuConfig = z.infer<typeof FeishuConfigSchema>\n\nexport const IntegrationSchema = z.discriminatedUnion('platform', [\n z.object({\n id: z.string(),\n // CP-pushed integrations are tagged so a reconnect snapshot can prune a\n // missed integration/remove without touching hand-authored local entries.\n origin: z.literal('cp').optional(),\n platform: z.literal('slack'),\n slack: SlackConfigSchema\n }),\n z.object({\n id: z.string(),\n origin: z.literal('cp').optional(),\n platform: z.literal('telegram'),\n telegram: TelegramConfigSchema\n }),\n z.object({\n id: z.string(),\n origin: z.literal('cp').optional(),\n platform: z.literal('discord'),\n discord: DiscordConfigSchema\n }),\n z.object({\n id: z.string(),\n origin: z.literal('cp').optional(),\n platform: z.literal('feishu'),\n feishu: FeishuConfigSchema\n })\n])\nexport type Integration = z.infer<typeof IntegrationSchema>\n\n/** A scheduled trigger for THIS agent: every `schedule` tick, prompt the agent\n * with `trigger`. `target` is optional output routing — when present the daemon\n * posts the trigger into that channel and the session replies in its thread;\n * absent ⇒ headless fire (no platform output). `origin:\"cp\"` marks CP-pushed\n * entries (written by cron/upsert, pruned by drop.crons); hand-authored entries\n * have no origin and are never touched by the CP. */\nexport const CronDefSchema = z.object({\n id: z.string(),\n schedule: z.string(),\n // CP-owned entries always include an IANA timezone. Hand-authored local\n // entries may omit it to retain daemon-local scheduling.\n timezone: z.string().min(1).optional(),\n // integrationId picks which of the agent's integrations posts the anchor;\n // absent (legacy defs) ⇒ the agent's first integration.\n target: z\n .object({\n platform: z.enum(['slack', 'telegram', 'discord', 'feishu']),\n channel: z.string(),\n integrationId: z.string().optional()\n })\n .optional(),\n trigger: z.string(),\n enabled: z.boolean().default(true),\n origin: z.literal('cp').optional()\n})\nexport type CronDef = z.infer<typeof CronDefSchema>\n\nexport const AgentSchema = z.object({\n id: z.string(),\n // Added when a CP spec is persisted. Absence continues to mean a genuinely\n // local agent (or a legacy replica, which the CP handles conservatively).\n origin: z.literal('cp').optional(),\n name: z.string(),\n // Optional human-facing bot name. `name` remains the stable agent identifier;\n // the CP may set or clear this field independently via AgentSpec.displayName.\n displayName: z.string().optional(),\n // CP-resolved public avatar URL (its icon endpoint, or a user image URL). Used\n // as the Slack per-message `icon_url` (chat:write.customize), the sibling of\n // displayName→username. Set/cleared by the CP via AgentSpec.iconUrl.\n iconUrl: z.string().optional(),\n status: z.enum(['active', 'inactive', 'paused']).default('active'),\n // Operational message-processing toggle, orthogonal to `status` (which gates\n // whether the agent is loaded/placed at all). When true the agent still loads and\n // connects its platform bot, but the daemon skips ALL turn dispatch (platform,\n // webchat, cron) — see Daemon.dispatch. Turning it on also cancels in-flight\n // turns and drops their queued follow-ups (including their durable inbox rows, so\n // restart cannot resurrect them), without tearing down the warm host or ACP sessions.\n // Silent: skipped turns are dropped, not recorded. A flip remains\n // a soft-only reconcile change (no host/session teardown).\n pause: z.boolean().default(false),\n runtime: z.string(),\n // System-prompt seed + runtime knobs. Settable in agent.json and overlaid by\n // the CP spec (agent/upsert + register/ok roster) — see cp/cp-agent-registry.ts.\n description: z.string().optional(),\n reasoningEffort: z.string().optional(),\n executionMode: z.string().optional(),\n // Runtime fast mode (ACP `model_config` toggle, claude/codex). Absent ⇒ leave\n // the runtime's own default; the daemon only pushes an explicit on/off.\n fastMode: z.boolean().optional(),\n // Runtime permission/approval mode (ACP `mode` selector). The values are\n // runtime-owned strings: claude-acp uses default/acceptEdits/auto/dontAsk/plan,\n // codex-acp uses read-only/agent/agent-full-access.\n permissionMode: z.string().default('default'),\n // Conversation participants are not authorization principals by default.\n // Editors may explicitly opt this agent back into chat-side runtime setting\n // changes (model, effort, permission mode, fast mode) and approval controls.\n allowRuntimeChangesInChat: z.boolean().default(false),\n runtimeOverrides: z\n .object({\n model: z.string().optional(),\n env: z.array(z.object({ name: z.string(), value: z.string() })).default([]),\n // Write-only secret env vars (CP AgentSpec.secrets). Same {name,value}[] shape as\n // env; merged into the spawned child's environment (secrets win on a key clash).\n secrets: z.array(z.object({ name: z.string(), value: z.string() })).default([])\n })\n .optional(),\n // Names of daemon-configured MCP servers (daemon config `mcpServers`) to attach\n // at ACP session/new|load, after the daemon's own bridge entry. Empty ⇒ none;\n // unknown names are skipped with a warn (see mcp/resolve-servers.ts).\n mcpServers: z.array(z.string()).default([]),\n // Skill sources to install into the workspace via `npx skills` after clone and\n // before the ACP host spawns (design: docs/designs/shared-skills.md). CP-owned,\n // shipped inline on AgentSpec.skills — each entry is self-contained so the daemon\n // needs nothing but agent.json to install. Supersedes the deprecated\n // `workspace.skills` string list below (which is now an unused no-op).\n skills: z.array(AgentSkillEntry).default([]),\n // Centrally accepted immutable `.skill` revisions. Content stays in the\n // daemon-owned cache and is materialized into the workspace before session\n // creation; this metadata is the exact CP-authorized revision set.\n managedSkills: z.array(ManagedSkillEntry).default([]),\n // Agent→agent call authorization (design §2.5), replicated from the CP so the\n // daemon enforces it LOCALLY when another agent uses `messageAgent` to wake this\n // one. `all` (the default) ⇒ any org peer may call; `selected` ⇒ only agents in\n // `allowedCallerAgentIds`. Absent callPolicy ⇒ treated as `all` (backward-compat;\n // see §6.5 for the fail-closed alternative — noted as a P1 gap).\n callPolicy: z.enum(['all', 'selected']).default('all'),\n allowedCallerAgentIds: z.array(z.string()).default([]),\n // Caller-side half of collaboration authorization. Defaults preserve the\n // historical unrestricted behavior for existing agent.json files.\n outboundPolicy: z.enum(['all', 'selected']).default('all'),\n allowedTargetAgentIds: z.array(z.string()).default([]),\n // Opt-in (issue #536): when true, on a GENUINE new channel join the agent\n // proactively introduces itself to the other agents already there (via\n // listAgents → a sendMessage wake) so peers can record it in memory. Default\n // off — the daemon seeds each integration's channel baseline silently, so only\n // channels joined AFTER the baseline (never a restart/re-list) trigger an intro.\n introduceOnJoin: z.boolean().default(false),\n // Request an OS sandbox for this agent (issue #312). Daemon policy may force it\n // on; an unavailable optional sandbox is ineffective. New agents default off.\n restrictFileAccess: z.boolean().default(false),\n // Which memory backend this agent uses (see agents/memory-provider.ts). Absent ⇒\n // managed (the default). External keeps only connection id + bounded policy on\n // disk; endpoint/grant/config live in the daemon-private CP registry.\n memory: AgentMemoryBinding.optional(),\n workspace: z.object({\n mode: z.enum(['git-repo', 'from-scratch']),\n path: z.string(),\n gitRepo: z.string().optional(), // full cloneable address (e.g. https://github.com/acme/infra)\n gitBranch: z.string().default('main'),\n // Repository-relative ACP cwd. Kept lexically lenient here so a historical or\n // hand-authored value cannot break daemon discovery; prepareWorkspace validates it.\n agentDir: z.string().optional(),\n // Remote-git credential mode. Absent ⇒ anonymous (public repos). 'github-app' ⇒\n // clone/fetch/push authenticate via the local credential helper backed by\n // CP-minted short-lived installation tokens — nothing durable on this host.\n gitCredential: z.enum(['github-app']).optional(),\n pullOnNewSession: z.boolean().default(true),\n // DEPRECATED: superseded by the top-level `skills` field (AgentSkillEntry[]).\n // Kept so historical agent.json files still parse; nothing consumes it.\n skills: z.array(z.string()).default([])\n }),\n integrations: z.array(IntegrationSchema).default([]),\n // zod 4: nested .default({}) does not apply inner field defaults — use explicit full literal\n output: z\n .object({\n mode: z.enum(['none', 'minimal', 'low', 'medium', 'high']).default('low'),\n showFooter: z.boolean().default(true)\n })\n .default({ mode: 'low', showFooter: true }),\n permissions: z\n .object({ policy: z.enum(['ask', 'auto']).default('ask'), autoApprove: z.array(z.string()).default([]) })\n .default({ policy: 'ask', autoApprove: [] }),\n crons: z.array(CronDefSchema).default([])\n})\nexport type Agent = z.infer<typeof AgentSchema>\n","import { chmodSync, existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\nconst PRIVATE_DIR_MODE = 0o700\nconst PRIVATE_FILE_MODE = 0o600\n\nfunction chmodIfNeeded(path: string, target: number | ((current: number) => number)): void {\n try {\n const current = statSync(path).mode & 0o777\n const mode = typeof target === 'function' ? target(current) : target\n if (current !== mode) chmodSync(path, mode)\n } catch (err) {\n if (process.platform !== 'win32') throw err\n }\n}\n\nexport function ensurePrivateAgentDirectory(path: string): void {\n mkdirSync(path, { recursive: true, mode: PRIVATE_DIR_MODE })\n chmodIfNeeded(path, PRIVATE_DIR_MODE)\n}\n\n/** Tighten a hand-authored or legacy agent.json before reading its secrets. */\nexport function protectAgentJson(file: string, writable = false): void {\n if (!existsSync(file)) return\n chmodIfNeeded(file, (current) => (writable ? PRIVATE_FILE_MODE : current & 0o700))\n}\n\n/** Preserve the existing inode/symlink while enforcing owner-only access. */\nexport function writeAgentJson(file: string, contents: string): void {\n if (!existsSync(file)) ensurePrivateAgentDirectory(dirname(file))\n protectAgentJson(file, true)\n writeFileSync(file, contents, { encoding: 'utf8', mode: PRIVATE_FILE_MODE })\n protectAgentJson(file, true)\n}\n","import { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { join, resolve, isAbsolute, dirname } from 'node:path'\nimport { AgentSchema, type Agent } from './agent-schema.js'\nimport { protectAgentJson } from './agent-json-file.js'\n\nconst IGNORED_DIRS = new Set(['node_modules', '.git'])\nconst MAX_DEPTH = 4\nconst DETACHED_DIR = '.detached'\n\n// Agent plus loader-derived data: the directory containing agent.json.\nexport type LoadedAgent = Agent & { dir: string }\n\n// Parse one agent.json, then resolve workspace.path relative to the agent dir.\nfunction parseAgentFile(file: string): LoadedAgent {\n protectAgentJson(file)\n const dir = dirname(file)\n const agent = AgentSchema.parse(JSON.parse(readFileSync(file, 'utf8')))\n if (!isAbsolute(agent.workspace.path)) {\n agent.workspace.path = resolve(dir, agent.workspace.path)\n }\n return { ...agent, dir }\n}\n\n// Bounded recursive walk: collect every agent.json under `dir`. A directory that\n// contains an agent.json is treated as a leaf (we do not recurse into it), so an\n// agent's own workspace checkout can't masquerade as nested agents.\nexport function findAgentFiles(dir: string, depth = 0): string[] {\n if (depth > MAX_DEPTH || !existsSync(dir)) return []\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n if (entries.some((e) => e.isFile() && e.name === 'agent.json')) {\n return [join(dir, 'agent.json')]\n }\n const out: string[] = []\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('.')) continue\n out.push(...findAgentFiles(join(dir, entry.name), depth + 1))\n }\n return out\n}\n\nfunction protectDetachedAgentFiles(agentsDir: string): void {\n for (const file of findAgentFiles(join(agentsDir, DETACHED_DIR))) {\n protectAgentJson(file)\n }\n}\n\n// All parsed agents under `agentsDir`, no status filter. `dir` is the directory\n// holding each agent.json.\nexport function discoverAgents(agentsDir: string): { agent: LoadedAgent; dir: string }[] {\n // Hidden cold-move archives are intentionally excluded from discovery, but\n // legacy copies may still contain runtime secrets and must converge too.\n protectDetachedAgentFiles(agentsDir)\n return findAgentFiles(agentsDir).map((file) => {\n try {\n return { agent: parseAgentFile(file), dir: dirname(file) }\n } catch (err) {\n throw new Error(`invalid agent.json at ${file}: ${(err as Error).message}`)\n }\n })\n}\n\n// Active agents only — the daemon's multi-agent path.\nexport function loadAgents(agentsDir: string): LoadedAgent[] {\n return discoverAgents(agentsDir)\n .map((d) => d.agent)\n .filter((a) => a.status === 'active')\n}\n\n// Resolve a single agent from `agentsDir`. With `name`, matches the agent `id`.\n// Without `name`: requires exactly one discovered agent. Used by `chat` and by\n// `run --agent`. Does NOT filter by status.\nexport function selectAgent(agentsDir: string, name?: string): LoadedAgent {\n const agents = discoverAgents(agentsDir).map((d) => d.agent)\n if (name) {\n const match = agents.find((a) => a.id === name)\n if (!match) {\n const available =\n agents\n .map((a) => a.id)\n .sort()\n .join(', ') || '(none)'\n throw new Error(`agent \"${name}\" not found in ${agentsDir}. Available: ${available}`)\n }\n return match\n }\n if (agents.length === 0) throw new Error(`no agent.json found in ${agentsDir}`)\n if (agents.length > 1) {\n const ids = agents\n .map((a) => a.id)\n .sort()\n .join(', ')\n throw new Error(`multiple agents found in ${agentsDir}: ${ids}; use --agent <name> to specify one`)\n }\n return agents[0]!\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,WAAWA,MAAO;CAAC;CAAS;CAAY;CAAW;CAAW;CAAU;CAAQ;AAAO,CAAC;AACrG,MAAa,aAAaC,OAAS;CAC/B,UAAU;CACV,SAASC,OAAS;CAClB,QAAQA,OAAS,CAAC,CAAC,SAAS;AAChC,CAAC;;AAED,MAAa,WAAWD,OAAS,EAC7B,OAAOE,mBAAqB,QAAQ;CAChCF,OAAS,EAAE,MAAMG,QAAU,SAAS,EAAE,CAAC;CACvCH,OAAS,EAAE,MAAMG,QAAU,IAAI,EAAE,CAAC;CAClCH,OAAS;EAAE,MAAMG,QAAU,SAAS;EAAG,OAAOF,OAAS;CAAE,CAAC;CAC1DD,OAAS,EAAE,MAAMG,QAAU,MAAM,EAAE,CAAC;AACxC,CAAC,EACL,CAAC;AACD,MAAa,cAAcH,OAAS;CAEhC,YAAY;CACZ,SAASC,OAAS,CAAC,CAAC,KAAK;CACzB,aAAaA,OAAS,CAAC,CAAC,KAAK;CAC7B,WAAWG,MAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC;AACD,MAAa,iBAA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AK,MAAM,EAAE,KAAK,CAAC,CACnB,QAAQ,MAAM,EAAE,WAAW,QAAQ;AACxC;AAKA,SAAgB,YAAY,WAAmB,MAA4B;CACzE,MAAM,SAAS,eAAe,SAAS,CAAC,CAAC,KAAK,MAAM,EAAE,KAAK;CAC3D,IAAI,MAAM;EACR,MAAM,QAAQ,OAAO,MAAM,MAAM,EAAE,OAAO,IAAI;EAC9C,IAAI,CAAC,OAAO;GACV,MAAM,YACJ,OACG,KAAK,MAAM,EAAE,EAAE,CAAC,CAChB,KAAK,CAAC,CACN,KAAK,IAAI,KAAK;GACnB,MAAM,IAAI,MAAM,UAAU,KAAK,iBAAiB,UAAU,eAAe,WAAW;EACtF;EACA,OAAO;CACT;CACA,IAAI,OAAO,WAAW,GAAG,MAAM,IAAI,MAAM,0BAA0B,WAAW;CAC9E,IAAI,OAAO,SAAS,GAAG;EACrB,MAAM,MAAM,OACT,KAAK,MAAM,EAAE,EAAE,CAAC,CAChB,KAAK,CAAC,CACN,KAAK,IAAI;EACZ,MAAM,IAAI,MAAM,4BAA4B,UAAU,IAAI,IAAI,oCAAoC;CACpG;CACA,OAAO,OAAO;AAChB"}
|
|
1
|
+
{"version":3,"file":"load-agents-BiEHZLkW.js","names":["z.enum","z.object","z.string","z.discriminatedUnion","z.literal","z.array","z.boolean","z.number","z.unknown","z.union","z.object","z.enum","z.string","z.boolean","z.number","z.object","z.string","z.number","z.enum","z.enum","z\n .object","z.string","z.object","z.number","z.record","z.unknown","z\n .object","z.literal","z\n .string","z\n .array","z\n .object","z.boolean","z.array","z\n .array","z\n .object","z.enum","z.number","z\n .number","z.object","z.boolean","z.string","z.literal","z.union","z\n .string","z.array","z.record","z.unknown","z.discriminatedUnion","z.preprocess","z.discriminatedUnion","z.object","z.literal","z.string","z\n .object","z.enum","z.boolean","z.array","z.discriminatedUnion","z.object","z.literal","z.enum","z.string","z\n .string","z.array","z\n .object","z.number","z.boolean","z.record","z\n .array","NameValueList","z.array","z.object","z.string","z\n .object","z.enum","z.object","z.string","z.enum","z.array","z.number","z.object","z.string","z.enum","z.array","z.literal","z.boolean","z.number","z.object","z.string","z.array","z.boolean","z.number","z.enum","z.array","z.object","z.string","z\n .object","z.enum","z\n .string","z.NEVER","z\n .string","z\n .array","z.record","z.literal","z\n .object","z.boolean","z.number","z\n .number","z.discriminatedUnion","z.object","z.literal","z.string","z.enum","z.boolean","z.array","z\n .object"],"sources":["../../protocol/dist/frames/route.js","../../protocol/dist/frames/cron.js","../../protocol/dist/frames/secrets.js","../../protocol/dist/memory-plugin.js","../../protocol/dist/frames/memory-connection.js","../../protocol/dist/frames/integration.js","../../protocol/dist/frames/agent.js","../../protocol/dist/frames/mcpserver.js","../../protocol/dist/frames/collab.js","../../protocol/dist/frames/gitcred.js","../../protocol/dist/frames/register.js","../src/config/config-schema.ts","../src/config/load-config.ts","../src/agents/agent-schema.ts","../src/agents/agent-json-file.ts","../src/agents/load-agents.ts"],"sourcesContent":["import { z } from 'zod';\n/**\n * Routing & orchestration (C→D control) — protocol §5.\n *\n * `SessionKey` is the canonical session primitive shared across route/*,\n * agent/*, and event/session. Its canonical string form is\n * `${platform}:${channel}:${thread ?? \"-\"}`.\n */\n// `webchat`, `hook`, and `dream` are session-identity platforms only (the\n// Playground conversation / a webhook trigger / a background memory-consolidation\n// run) — no integration, no bind rules, no routing-table participation, never a\n// persisted DB Platform.\nexport const Platform = z.enum(['slack', 'telegram', 'webchat', 'discord', 'feishu', 'hook', 'dream']);\nexport const SessionKey = z.object({\n platform: Platform,\n channel: z.string(),\n thread: z.string().optional() // absent = channel-root\n});\n/** Trigger-matching rule for a binding (protocol §5.1). */\nexport const BindRule = z.object({\n match: z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('mention') }),\n z.object({ kind: z.literal('dm') }),\n z.object({ kind: z.literal('keyword'), value: z.string() }),\n z.object({ kind: z.literal('auto') }) // alert-channel auto-handle\n ])\n});\nexport const RouteAssign = z.object({\n // also appears in RegisterOk.assignments[]\n sessionKey: SessionKey,\n agentId: z.string().uuid(),\n workspaceId: z.string().uuid(), // which D9 workspace to prepare\n bindRules: z.array(BindRule).default([])\n});\nexport const RouteAssignAck = z.object({\n ok: z.boolean(),\n sessionKey: SessionKey,\n reason: z.string().optional()\n});\nexport const RouteUpdate = z.object({\n routingEpoch: z.number().int(),\n rules: z.array(z.object({ match: z.unknown(), agentId: z.string().uuid() }))\n});\n/** Graceful scale-down / rebalance — protocol §5.3. */\nexport const Drain = z.object({\n scope: z.union([\n z.object({ kind: z.literal('agent'), agentId: z.string().uuid() }),\n z.object({ kind: z.literal('daemon') }), // whole-daemon drain (shutdown/upgrade)\n z.object({ kind: z.literal('session'), sessionKey: SessionKey })\n ]),\n deadline: z.string().datetime() // hard cutoff; in-flight turns past this are cancelled\n});\nexport const DrainProgress = z.object({\n remaining: z.number().int(),\n drained: z.array(SessionKey)\n});\nexport const DrainDone = z.object({\n released: z.array(SessionKey) // CP may now reassign — fenced by new epoch\n});\n//# sourceMappingURL=route.js.map","import { z } from 'zod';\n/**\n * Cron sinks to the daemon (D5) — protocol §5.4.\n *\n * A cron periodically triggers ONE AGENT with a synthetic prompt (`trigger`) to\n * carry out some work. The CP owns the definition; the daemon owns firing +\n * last-run persistence, so crons fire even when the CP is down. On receipt the\n * daemon persists the def into the owning agent's `agent.json` `crons[]` (the\n * single source of truth, same model as integrations) — surviving a restart\n * with the CP down.\n *\n * `target` is OPTIONAL output routing: when present, the daemon posts the\n * trigger as a real message in that channel and the agent's session replies in\n * its thread; when absent the fire is headless (the agent works with no\n * platform output).\n */\nexport const CronTarget = z.object({\n platform: z.enum(['slack', 'telegram', 'discord', 'feishu']).default('slack'),\n channel: z.string(),\n // The agent integration whose connection posts the anchor — targets come from\n // the owning agent's integrations, so the daemon posts through the right bot\n // when the agent has several. Absent (legacy defs) ⇒ first integration.\n integrationId: z.string().uuid().optional()\n});\nexport const CronUpsert = z.object({\n cronId: z.string().uuid(),\n agentId: z.string().uuid(), // the agent this cron drives — routes the def to its daemon\n schedule: z.string(), // croner expression interpreted in `timezone`\n timezone: z.string().min(1), // resolved IANA timezone; daemon converts ticks to UTC instants\n target: CronTarget.optional(), // absent ⇒ headless fire\n trigger: z.string(), // synthetic prompt text injected on fire\n enabled: z.boolean().default(true)\n});\nexport const CronRemove = z.object({\n cronId: z.string().uuid()\n});\n/**\n * `cron/report` (D→C EVT, fire-and-forget) — one CP-owned cron fired. The\n * daemon stamps the fire into its local store first (it stays authoritative,\n * §5.4) and reports it here so the console's `lastRunAt` converges; the CP\n * upsert is latest-wins, so the daemon re-asserting its stored stamps on\n * reconnect (fires while the CP was unreachable) is idempotent and can never\n * regress the value. Hand-authored (no-origin) crons are never reported.\n *\n * Reports are keyed by `(cronId, firedAt)`: the FIRE report (no `status`)\n * opens the run, an optional SESSION report attaches the ACP session as soon\n * as it is initialized, and the COMPLETION report (with `status` + outcome\n * fields) closes the run once the dispatched turn ends. A completion without\n * a prior fire report (CP was down at fire time) still creates the run row.\n */\nexport const CronRunStatus = z.enum(['success', 'failed']);\nexport const CronReport = z.object({\n cronId: z.string().uuid(),\n agentId: z.string().uuid(), // the owning agent — scopes the report to its daemon\n firedAt: z.string().datetime(),\n // Terminal outcome fields (absent on fire/session progress reports).\n status: CronRunStatus.optional(),\n durationMs: z.number().int().nonnegative().optional(), // fire → turn end\n // Sent once the ACP session exists, then repeated on completion.\n sessionId: z.string().optional(), // ACP session the run prompted (console deep-link)\n reason: z.string().optional() // short failure text (status \"failed\")\n});\n/**\n * `cron/run` (C→D REQ → ack) — fire one CP-owned cron NOW (console \"Run now\").\n * The daemon accepts (`ok:true`) and runs the fire asynchronously — outcome\n * arrives as normal `cron/report`s; `ok:false` when it holds no such cron.\n */\nexport const CronRunNow = z.object({\n cronId: z.string().uuid()\n});\n//# sourceMappingURL=cron.js.map","import { z } from 'zod';\nimport { Platform } from './route.js';\n/**\n * Secrets (C5 ↔ D10) — protocol §6.\n *\n * Lease-based, no plaintext on the wire or in PG. Every frame carries a\n * REFERENCE to a Vault/KMS path, never the secret material itself.\n */\nexport const SecretsRequest = z.object({\n // D→C, REQ — daemon asks for a lease at session start\n scope: z.object({\n platform: Platform,\n workspaceId: z.string().uuid()\n })\n});\nexport const SecretsGrant = z.object({\n // C→D, REP (also in RegisterOk.leases[])\n leaseId: z.string().uuid(),\n scope: z.object({\n platform: z.string(),\n workspaceId: z.string().uuid()\n }),\n ref: z.string(), // Vault/KMS path or handle — NOT the secret\n ttl: z.number().int(), // seconds\n renewBeforeSec: z.number().int() // daemon should renew this many sec before expiry\n});\nexport const SecretsRenew = z.object({\n leaseId: z.string().uuid() // D→C REQ → new SecretsGrant\n});\nexport const SecretsRevoke = z.object({\n leaseId: z.string().uuid(),\n reason: z.string() // C→D EVT (hot revoke)\n});\n/** 🅼 Direct-to-store upload/download grant — protocol §3.2 / frame #25. */\nexport const ScopeAttestation = z.object({\n machineId: z.string().uuid(),\n scope: z.enum(['attachment.put', 'attachment.get', 'facts.put']),\n resourceRef: z.string(), // opaque object key/prefix\n jws: z.string(), // signed capability the store verifies offline\n exp: z.string().datetime()\n});\n//# sourceMappingURL=secrets.js.map","import { z } from 'zod';\n/**\n * Canonical, backend-neutral contract for an AgentConnect external-memory plugin.\n *\n * This is deliberately NOT a daemon↔CP frame group. Both the daemon's private MCP\n * client and first/third-party plugin implementations import these schemas so the\n * `agentconnect.memory/v1` profile has one executable source of truth. The model\n * never sees the plugin's raw MCP tools; AgentConnect core translates them into a\n * stable product surface.\n */\nexport const MEMORY_PLUGIN_PROFILE = 'agentconnect.memory/v1';\nexport const MEMORY_PLUGIN_PROFILE_MAJOR = 1;\nexport const MEMORY_PLUGIN_TOOL = {\n manifest: 'agentconnect_memory_manifest',\n recall: 'agentconnect_memory_recall',\n capture: 'agentconnect_memory_capture',\n health: 'agentconnect_memory_health',\n operationStatus: 'agentconnect_memory_operation_status',\n list: 'agentconnect_memory_list',\n get: 'agentconnect_memory_get',\n create: 'agentconnect_memory_create',\n update: 'agentconnect_memory_update',\n delete: 'agentconnect_memory_delete',\n history: 'agentconnect_memory_history'\n};\nexport const MEMORY_RECALL_DEFAULTS = {\n topK: 5,\n maxBytes: 8 * 1024,\n // The budget covers the complete daemon -> relay -> plugin -> embedder\n // round trip. A healthy remote Mem0 search can spend ~1s at the relay alone,\n // so 1s races successful responses instead of representing a useful SLA.\n timeoutMs: 3_000\n};\n// Recall runs before every activation and fails open, so the default budget\n// stays bounded while leaving transport headroom around the common warm path.\n// The ceiling is deliberately generous:\n// a local/self-hosted provider (e.g. Mem0 OSS) can need several seconds on a\n// cold first search — embedding-model load plus vector search — and an operator\n// must be able to configure a budget that a healthy cold start fits inside\n// rather than being forced to degrade it. This is the single source of truth\n// for the recall-timeout ceiling shared by the connection policy schema and,\n// by contract, the control-plane validation and console input.\nexport const MEMORY_RECALL_HARD_LIMITS = {\n topK: 20,\n maxBytes: 32 * 1024,\n timeoutMs: 10_000\n};\nexport const MemoryScopeKind = z.enum(['agent', 'user', 'session', 'shared']);\n/** The plugin-facing scope. `key` is always derived by daemon core, never tool input. */\nexport const CanonicalMemoryScope = z\n .object({\n kind: MemoryScopeKind,\n key: z.string().min(1).max(512)\n})\n .strict();\nexport const MemoryRecordProvenance = z\n .object({\n pluginId: z.string().min(1).max(255),\n backendId: z.string().min(1).max(512).optional()\n})\n .strict();\n/** The one record shape AgentConnect core understands, regardless of backend. */\nexport const CanonicalMemoryRecord = z.object({\n id: z.string().min(1).max(512),\n text: z.string().min(1),\n score: z.number().finite().optional(),\n scope: CanonicalMemoryScope,\n metadata: z.record(z.string(), z.unknown()).optional(),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n provenance: MemoryRecordProvenance.optional(),\n /** Backend version/ETag for optimistic concurrency on update. */\n version: z.string().min(1).max(512).optional()\n});\nexport const CaptureReceipt = z.object({\n state: z.enum(['completed', 'accepted', 'failed', 'ambiguous']),\n backendOperationId: z.string().min(1).max(512).optional()\n});\n/** Every operation carries a core-created request, connection, and trusted scope. */\nexport const MemoryPluginCallContext = z\n .object({\n requestId: z.string().min(1).max(512),\n connection: z\n .object({\n id: z.string().min(1).max(512),\n config: z.record(z.string(), z.unknown())\n })\n .strict(),\n scope: CanonicalMemoryScope\n})\n .strict();\nexport const MemoryPluginOperation = z.enum([\n 'recall',\n 'capture',\n 'list',\n 'get',\n 'create',\n 'update',\n 'delete',\n 'history'\n]);\n/** Exact machine-readable text tokens for MCP tool results with `isError:true`.\n * MCP validates structuredContent against the success output schema even on an\n * error result, so profile errors use an exact token and never a free-form\n * plugin/upstream message. */\nexport const MEMORY_PLUGIN_ERROR_TOKEN = {\n conflict: 'agentconnect.memory.error/conflict'\n};\nconst unique = (xs) => new Set(xs).size === xs.length;\n/** The result of the required manifest tool (`structuredContent` directly). */\nexport const MemoryPluginManifest = z.object({\n profile: z.literal(MEMORY_PLUGIN_PROFILE),\n plugin: z.object({\n id: z\n .string()\n .max(255)\n .regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)+$/, 'plugin id must be reverse-DNS-like'),\n version: z\n .string()\n .max(128)\n .regex(/^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$/, 'plugin version must be semver')\n }),\n connection: z.object({\n // A deliberately bounded JSON-Schema subset is enforced by daemon core during\n // conformance; this field remains JSON here so the console can render it later.\n configSchema: z.record(z.string(), z.unknown()),\n secretFields: z\n .array(z\n .object({\n name: z.string().min(1).max(128),\n required: z.boolean(),\n transportHeader: z.string().min(1).max(128).optional()\n })\n .strict())\n .max(64)\n .refine((fields) => unique(fields.map((field) => field.name)), 'secret field names must be unique')\n }),\n capabilities: z\n .object({\n scopes: z.array(MemoryScopeKind).min(1).max(4).refine(unique, 'scope capabilities must be unique'),\n operations: z.array(MemoryPluginOperation).min(2).max(8).refine(unique, 'operation capabilities must be unique'),\n asyncCapture: z.boolean(),\n idempotency: z.enum(['operation-id', 'none'])\n })\n .strict(),\n limits: z\n .object({\n maxQueryBytes: z.number().int().positive(),\n maxRecordBytes: z.number().int().positive(),\n maxBatchItems: z.number().int().positive()\n })\n .strict(),\n declaredEgressHosts: z\n .array(z.string().min(1).max(253))\n .max(128)\n .refine(unique, 'egress hosts must be unique')\n .optional()\n});\nexport const MemoryPluginRecallInput = z\n .object({\n context: MemoryPluginCallContext,\n query: z.string().min(1),\n topK: z.number().int().positive().max(MEMORY_RECALL_HARD_LIMITS.topK),\n maxBytes: z.number().int().positive().max(MEMORY_RECALL_HARD_LIMITS.maxBytes)\n})\n .strict();\nexport const MemoryPluginRecallOutput = z.object({ records: z.array(CanonicalMemoryRecord) }).strict();\nexport const MemoryPluginTurnObservation = z\n .object({\n turnId: z.string().min(1).max(512),\n input: z.string(),\n output: z.string(),\n sessionId: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginCaptureInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n turn: MemoryPluginTurnObservation\n})\n .strict();\nexport const MemoryPluginCaptureOutput = CaptureReceipt.strict();\nexport const MemoryPluginHealthInput = z.object({ context: MemoryPluginCallContext }).strict();\nexport const MemoryPluginHealthOutput = z\n .object({\n status: z.enum(['ready', 'degraded', 'invalid']),\n /** Stable, non-secret diagnostic code. Never an upstream response body. */\n reasonCode: z.string().min(1).max(128).optional()\n})\n .strict();\nexport const MemoryPluginOperationStatusInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n backendOperationId: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginOperationStatusOutput = CaptureReceipt.strict();\nconst OptionalCursor = z.string().min(1).max(2048).optional();\nexport const MemoryPluginListInput = z\n .object({\n context: MemoryPluginCallContext,\n cursor: OptionalCursor,\n limit: z.number().int().positive().max(100).default(50)\n})\n .strict();\nexport const MemoryPluginListOutput = z\n .object({ records: z.array(CanonicalMemoryRecord), nextCursor: OptionalCursor })\n .strict();\nexport const MemoryPluginGetInput = z\n .object({ context: MemoryPluginCallContext, id: z.string().min(1).max(512) })\n .strict();\nexport const MemoryPluginGetOutput = z.object({ record: CanonicalMemoryRecord.nullable() }).strict();\nexport const MemoryPluginCreateInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n text: z.string().min(1),\n metadata: z.record(z.string(), z.unknown()).optional()\n})\n .strict();\nexport const MemoryPluginCreateOutput = z.object({ record: CanonicalMemoryRecord }).strict();\nexport const MemoryPluginUpdateInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n id: z.string().min(1).max(512),\n text: z.string().min(1),\n metadata: z.record(z.string(), z.unknown()).optional(),\n version: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginUpdateOutput = z.object({ record: CanonicalMemoryRecord }).strict();\nexport const MemoryPluginDeleteInput = z\n .object({\n context: MemoryPluginCallContext,\n operationId: z.string().min(1).max(512),\n id: z.string().min(1).max(512),\n version: z.string().min(1).max(512).optional()\n})\n .strict();\nexport const MemoryPluginDeleteOutput = z.object({ deleted: z.boolean() }).strict();\nexport const MemoryPluginHistoryInput = z\n .object({\n context: MemoryPluginCallContext,\n id: z.string().min(1).max(512),\n cursor: OptionalCursor,\n limit: z.number().int().positive().max(100).default(50)\n})\n .strict();\nexport const MemoryPluginHistoryEvent = z\n .object({\n id: z.string().min(1).max(512),\n event: z.enum(['create', 'update', 'delete']),\n at: z.string().datetime(),\n record: CanonicalMemoryRecord.optional()\n})\n .strict();\nexport const MemoryPluginHistoryOutput = z\n .object({ events: z.array(MemoryPluginHistoryEvent), nextCursor: OptionalCursor })\n .strict();\n//# sourceMappingURL=memory-plugin.js.map","import { z } from 'zod';\nimport { MEMORY_PLUGIN_PROFILE, MEMORY_RECALL_DEFAULTS, MEMORY_RECALL_HARD_LIMITS, MemoryPluginManifest } from '../memory-plugin.js';\n/**\n * External-memory control-plane distribution (M-5A).\n *\n * The Control Plane owns installations and org connections. A daemon receives\n * a transport-specific private definition. Remote definitions carry a relay URL\n * and purpose-specific bearer grant; local definitions carry an operator\n * allowlist reference and daemon-private secret lease. Raw local commands never\n * cross this wire.\n */\nexport const MemoryRecallPolicy = z\n .object({\n mode: z.enum(['auto', 'tool-only']).default('auto'),\n topK: z.number().int().positive().max(MEMORY_RECALL_HARD_LIMITS.topK).default(MEMORY_RECALL_DEFAULTS.topK),\n maxBytes: z\n .number()\n .int()\n .positive()\n .max(MEMORY_RECALL_HARD_LIMITS.maxBytes)\n .default(MEMORY_RECALL_DEFAULTS.maxBytes),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .max(MEMORY_RECALL_HARD_LIMITS.timeoutMs)\n .default(MEMORY_RECALL_DEFAULTS.timeoutMs)\n})\n .strict();\nexport const MemoryCapturePolicy = z.object({ mode: z.enum(['turn', 'manual']).default('manual') }).strict();\n/**\n * Dreaming — periodic offline consolidation of the MANAGED store\n * (design: docs/designs/memory-dreaming.md). Valid only with\n * `provider: 'managed'`; the daemon stages a rebuilt store per dream and the\n * user reviews and adopts it, or an enabled auto-accept policy adopts it.\n * Bounds mirror the design: sessionWindow ≤ 100 mined transcripts,\n * instructions ≤ 4096 chars.\n */\nexport const MemoryDreamingPolicy = z\n .object({\n enabled: z.boolean(),\n /** How many recent sessions to mine (default 20). */\n sessionWindow: z.number().int().min(1).max(100).optional(),\n /** Cron expression for scheduled dreams (same syntax as agent crons). A tick\n * that lands while a dream is already in flight is skipped, not queued. */\n schedule: z.string().min(1).max(128).optional(),\n /** IANA zone the `schedule` is evaluated in (as on agent crons). Absent ⇒ the\n * daemon host's local time. */\n timezone: z.string().min(1).max(64).optional(),\n /** Operator steering text applied through the whole dream pipeline. */\n instructions: z.string().max(4096).optional(),\n /** Also mine reusable procedures into candidate skills (never auto-installed). */\n mineSkills: z.boolean().optional(),\n /** Adopt the staged store automatically on completion without content\n * review. Live-memory fence conflicts remain reviewable. Absent defaults\n * to true for effective managed-memory policies. */\n autoAdopt: z.boolean().optional()\n})\n .strict();\n/** Product default for managed memory with no explicit dreaming policy.\n *\n * The schedule is evaluated in the daemon host's timezone because no timezone\n * is set. Keeping this as an explicit policy lets a saved policy distinguish\n * manual-only dreaming (enabled with no schedule) from the default daily run.\n */\nexport const DEFAULT_MEMORY_DREAMING_POLICY = {\n enabled: true,\n schedule: '0 4 * * *',\n autoAdopt: true\n};\nconst BuiltInMemoryBinding = z\n .object({\n provider: z.enum(['none', 'native', 'managed']),\n autoDistill: z.boolean().optional(),\n dreaming: MemoryDreamingPolicy.optional()\n})\n .strict()\n .superRefine((binding, ctx) => {\n if (binding.dreaming && binding.provider !== 'managed') {\n ctx.addIssue({\n code: 'custom',\n path: ['dreaming'],\n message: 'dreaming is only supported with the managed memory provider'\n });\n }\n});\nexport const ExternalMemoryBinding = z\n .object({\n provider: z.literal('external'),\n connectionId: z.string().uuid(),\n recall: MemoryRecallPolicy.default({ mode: 'auto', ...MEMORY_RECALL_DEFAULTS }),\n // The safe default never exports a full turn. Console users must explicitly\n // acknowledge the egress disclosure before selecting turn capture.\n capture: MemoryCapturePolicy.default({ mode: 'manual' })\n})\n .strict();\n/** Agent-facing provider selection. External bindings carry policy, never endpoints or secrets. */\nexport const AgentMemoryBinding = z.union([BuiltInMemoryBinding, ExternalMemoryBinding]);\n/** Resolve the managed-memory dreaming policy used by the daemon.\n *\n * No memory binding means the managed provider, and no explicit dreaming policy\n * means the daily auto-adopting product default. Once a policy exists its absent\n * schedule remains meaningful (manual-only), while absent `autoAdopt` follows\n * the new default; an explicit false is the opt-out.\n */\nexport function effectiveMemoryDreamingPolicy(binding) {\n if (binding && binding.provider !== 'managed')\n return undefined;\n const policy = binding?.dreaming;\n if (!policy)\n return { ...DEFAULT_MEMORY_DREAMING_POLICY };\n return policy.autoAdopt === undefined ? { ...policy, autoAdopt: true } : policy;\n}\n/** Reviewed mapping from a logical secret field to the header the relay injects. */\nexport const MemoryPluginSecretHeaderPin = z\n .object({ name: z.string().min(1).max(128), header: z.string().min(1).max(128), required: z.boolean() })\n .strict();\nexport const MemoryPluginPin = z\n .object({\n pluginId: z.string().min(1).max(255),\n profileMajor: z.literal(1),\n manifestDigest: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/)\n .optional(),\n secretHeaders: z.array(MemoryPluginSecretHeaderPin).max(64).default([])\n})\n .strict();\nconst MemoryConnectionSpecBase = z\n .object({\n connectionId: z.string().uuid(),\n revision: z.number().int().positive(),\n config: z.record(z.string(), z.unknown()),\n secretKeys: z.array(z.string().min(1).max(128)).max(64).default([]),\n pin: MemoryPluginPin\n})\n .strict();\nconst RemoteMemoryConnectionSpec = MemoryConnectionSpecBase.extend({\n transport: z.literal('streamable-http'),\n relayUrl: z.string().url(),\n grantKey: z.string().min(1).max(512)\n}).strict();\n/** Plaintext values cross only the authenticated daemon control channel and\n * remain in its private registry until they are injected into the allowlisted\n * plugin child. They never enter AgentSpec, agent.json, or the agent runtime. */\nexport const MemoryConnectionSecretLease = z\n .object({\n values: z.record(z.string().min(1).max(128), z\n .string()\n .min(1)\n .max(16 * 1024)\n .refine((value) => !value.includes('\\0'), 'memory connection secret contains NUL'))\n})\n .strict()\n .superRefine((lease, ctx) => {\n if (new TextEncoder().encode(JSON.stringify(lease.values)).byteLength > 64 * 1024) {\n ctx.addIssue({ code: 'custom', path: ['values'], message: 'memory connection secret lease exceeds 64 KiB' });\n }\n});\nconst StdioMemoryConnectionSpec = MemoryConnectionSpecBase.extend({\n transport: z.literal('stdio'),\n // This is a logical lookup key in the daemon operator's local allowlist, not\n // a path/command supplied by the tenant or Control Plane.\n commandRef: z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, 'commandRef must be an allowlist key'),\n secretLease: MemoryConnectionSecretLease\n})\n .strict()\n .superRefine((spec, ctx) => {\n const keys = Object.keys(spec.secretLease.values).sort();\n const declared = [...spec.secretKeys].sort();\n if (keys.length !== declared.length || keys.some((key, index) => key !== declared[index])) {\n ctx.addIssue({ code: 'custom', path: ['secretLease'], message: 'secret lease keys must match secretKeys' });\n }\n});\nconst TransportedMemoryConnectionSpec = z.discriminatedUnion('transport', [\n RemoteMemoryConnectionSpec,\n StdioMemoryConnectionSpec\n]);\n/** One daemon-private connection definition. Both relay grants and local secret\n * leases are secret-bearing; callers must never log this frame or validation\n * payload. Local commands are resolved solely from the operator allowlist.\n *\n * M-5A remote frames predate the transport discriminator. Decode them as\n * Streamable HTTP so daemons can be upgraded before the Control Plane during a\n * rolling deployment; the encoder likewise keeps remote frames legacy-shaped\n * until the old daemon population is gone. */\nexport const MemoryConnectionSpec = z.preprocess((input) => {\n if (typeof input !== 'object' || input === null || Array.isArray(input) || 'transport' in input)\n return input;\n if ('relayUrl' in input && 'grantKey' in input)\n return { ...input, transport: 'streamable-http' };\n return input;\n}, TransportedMemoryConnectionSpec);\n/** C→D live CRUD; reconnect baseline is `register/ok.memoryConnections`. */\nexport const MemoryConnectionUpsert = MemoryConnectionSpec;\nexport const MemoryConnectionRemove = z.object({ connectionId: z.string().uuid() }).strict();\n/** Stable, body-free probe fact for one connection revision. */\nexport const MemoryConnectionFact = z\n .object({\n connectionId: z.string().uuid(),\n revision: z.number().int().positive(),\n pluginId: z.string().min(1).max(255),\n version: z.string().max(128).optional(),\n profile: z.literal(MEMORY_PLUGIN_PROFILE).optional(),\n manifestDigest: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/)\n .optional(),\n capabilities: MemoryPluginManifest.shape.capabilities.optional(),\n declaredEgressHosts: z.array(z.string().min(1).max(255)).max(128).optional(),\n status: z.enum(['probing', 'ready', 'degraded', 'invalid']),\n reasonCode: z.string().min(1).max(128).optional()\n})\n .strict();\n/** D→C full snapshot. Re-emitted on reconnect and after every probe transition. */\nexport const MemoryConnectionFacts = z.object({ connections: z.array(MemoryConnectionFact).max(1_024) }).strict();\n//# sourceMappingURL=memory-connection.js.map","import { z } from 'zod';\n/**\n * Platform integration distribution (C→D) — the Slack \"install\" flow.\n *\n * The Control Plane is the source of truth for platform integrations and pushes\n * them to the daemon that owns the integration's agent (`integration/upsert`, and\n * the reconcile snapshot `RegisterOk.integrations[]`). The daemon opens the Socket\n * Mode connection from the delivered config (see slack/connection.ts).\n *\n * SECURITY: `integration/upsert` and `RegisterOk.integrations[]` carry PLAINTEXT\n * platform tokens (botToken/appToken/appSecret). These payloads MUST NEVER be logged — no\n * body dump on decode error, no register/ok snapshot debug dump. The daemon\n * persists them into the owning agent's local `agent.json` (same trust boundary\n * as hand-authored agents, which already keep tokens there) so integrations\n * survive a restart with the CP down.\n *\n * `signingSecret` is intentionally absent: Socket Mode authenticates with the\n * app-level token, so the daemon never needs a signing secret.\n */\n/** Trigger match — mirrors the daemon BindRuleConfig.match (agents/agent-schema.ts). */\nexport const BindMatch = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('mention') }),\n z.object({ kind: z.literal('dm') }),\n z.object({ kind: z.literal('keyword'), value: z.string() }),\n z.object({ kind: z.literal('auto') })\n]);\n/** One channel/thread trigger binding — mirrors the daemon BindRuleConfig. */\nexport const IntegrationBindRule = z.object({\n channel: z.string().optional(), // absent = any channel\n thread: z.string().optional(),\n match: BindMatch\n});\n/**\n * The Slack config a daemon receives (no signingSecret). `mode` splits the two\n * distribution paths of shared-bot-relay.md §7.3:\n *\n * - `direct` (today's behaviour, the default): the daemon owns the whole bot —\n * it opens the Socket Mode connection itself (needs `appToken`) and arbitrates\n * inbound locally (`bindRules`). Unchanged from before shared bots existed.\n * - `shared`: the bot's INBOUND lives on a relay (§4.1), so the daemon gets\n * xoxb ONLY — enough to SEND (`chat.postMessage`, attachment fetch). No\n * `appToken` (credential domaining: the daemon must not be able to subscribe\n * the event stream) and no `bindRules` (routing is arbitrated in the relay,\n * delivered pre-addressed). `botUserId` is optional and lazily resolved by the\n * daemon via `auth.test` (same as direct) if the sender ever needs it.\n *\n * Modeled as a flat object with a defaulted discriminator (not a\n * `discriminatedUnion`) so specs persisted before this field existed still decode\n * as `direct`. `.superRefine` enforces the one hard per-mode requirement the union\n * would otherwise give: direct needs the app-level token.\n */\nexport const IntegrationSlackConfig = z\n .object({\n mode: z.enum(['direct', 'shared']).default('direct'),\n botToken: z.string(), // xoxb-… (plaintext — never log) — always present (send path)\n appToken: z.string().optional(), // xapp-… (plaintext — never log) — direct only (Socket Mode)\n appId: z.string().optional(), // A… public metadata — permission-update deep link (especially shared mode)\n // Multi-agent opt-in — the bot backs MANY agents, so an in-thread \"Switch agent\"\n // control is meaningful. ONLY ever true in `shared` mode (an http/relay bot); a\n // non-shareable http bot is still `shared` for routing but has one agent, so the\n // switch control is suppressed. Defaults false so pre-field specs (and every direct\n // bot) decode as non-shareable.\n shareable: z.boolean().default(false),\n botUserId: z.string().optional(), // lazily resolved via auth.test; may be seeded by CP\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]), // empty for shared (relay arbitrates)\n // Channels the operator switched OFF. bindRules can only ADD reach, so an\n // ungated integration — whose defaults are unscoped (@-mention anywhere + DMs) —\n // has no way to say \"not here\" without a subtractive fence. A muted channel\n // matches no rule of this integration at all: no mention, no thread continuity,\n // no control command. Channels only (a DM is never muted this way); a GATED\n // integration leaves this empty, since its Off is already the ABSENCE of a\n // conversation-scoped rule. Defaults empty (pre-field specs).\n mutedChannels: z.array(z.string()).default([]),\n // Conversation gating (resource-visibility.md §14): true ⇒ this integration is\n // fail-closed — the CP ships only conversation-scoped bindRules (no unscoped\n // defaults), and the daemon answers explicitly-addressed unrouted messages with\n // a one-time notice + reports DM conversations. Derived from the owning agent's\n // restricted visibility; carries NO identities. Defaults false (pre-field specs).\n gated: z.boolean().default(false)\n})\n .superRefine((c, ctx) => {\n if (c.mode === 'direct' && !c.appToken)\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'direct slack requires appToken', path: ['appToken'] });\n});\n/**\n * The Telegram config the daemon needs to open long-polling + route (grammY).\n * Telegram has a SINGLE BotFather HTTP token — no app-level token and no signing\n * secret (long-polling authenticates every getUpdates call with the bot token).\n */\nexport const IntegrationTelegramConfig = z.object({\n botToken: z.string(), // BotFather \"123456:ABC…\" (plaintext — never log)\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see IntegrationSlackConfig.mutedChannels\n gated: z.boolean().default(false) // conversation gating — see IntegrationSlackConfig.gated\n});\n/**\n * The Discord config the daemon needs to open the Gateway + route (discord.js).\n * Discord authenticates the Gateway with a SINGLE bot token — no Slack-style\n * app-level token and no signing secret. `applicationId` is public metadata (the\n * client id for the OAuth2 bot-invite URL); it is not secret material.\n */\nexport const IntegrationDiscordConfig = z.object({\n botToken: z.string(), // Bot <token> (plaintext — never log)\n applicationId: z.string().optional(), // client/application id — public, for the invite URL\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see IntegrationSlackConfig.mutedChannels\n gated: z.boolean().default(false) // conversation gating — see IntegrationSlackConfig.gated\n});\n/**\n * The Feishu / Lark config the daemon needs to open the long-connection WebSocket\n * (`@larksuiteoapi/node-sdk` `WSClient`) + route. A Feishu self-built app\n * authenticates with an `appId` + `appSecret` PAIR — the SDK exchanges them for a\n * short-lived `tenant_access_token` internally (no Slack-style app-level token, no\n * signing secret). `appId` is a semi-public identifier (`cli_…`); `appSecret` is\n * plaintext secret material — NEVER log it. `botOpenId` is the bot's own open_id\n * for @-mention routing; lazily resolved by the daemon via `bot/info` if absent.\n *\n * `region` selects the open-platform gateway the daemon SDK (and CP verifier)\n * talk to — `'feishu'` = mainland China (`open.feishu.cn`, the SDK default) vs\n * `'lark'` = international (`open.larksuite.com`). Same app model, different host;\n * an app is registered in exactly one region. Defaults to `'feishu'` so existing\n * installs are unaffected.\n */\nexport const FeishuRegion = z.enum(['feishu', 'lark']);\nexport const IntegrationFeishuConfig = z.object({\n // `direct` opens the SDK long connection on the daemon. `shared` keeps only\n // the authenticated REST client on the daemon; HTTP callbacks arrive through\n // the relay and are delivered pre-addressed over rd/*.\n mode: z.enum(['direct', 'shared']).default('direct'),\n appId: z.string(), // cli_… — app identifier (semi-public), needed for REST and direct WS\n appSecret: z.string(), // app secret (plaintext — never log)\n botOpenId: z.string().optional(), // bot's own open_id; lazily resolved via bot/info\n region: FeishuRegion.default('feishu'), // open-platform gateway: feishu.cn vs larksuite.com\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(IntegrationBindRule).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see IntegrationSlackConfig.mutedChannels\n gated: z.boolean().default(false) // conversation gating — see IntegrationSlackConfig.gated\n});\n/**\n * One platform integration, owned by exactly one agent. Also the element type of\n * `RegisterOk.integrations[]` (the per-daemon reconcile set). Discriminated on\n * `platform`: the daemon opens a Slack Socket Mode connection, a Telegram\n * long-poll, a Discord Gateway, or a Feishu long-connection from whichever variant\n * is delivered.\n */\nexport const IntegrationSpec = z.discriminatedUnion('platform', [\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('slack'),\n slack: IntegrationSlackConfig\n }),\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('telegram'),\n telegram: IntegrationTelegramConfig\n }),\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('discord'),\n discord: IntegrationDiscordConfig\n }),\n z.object({\n integrationId: z.string().uuid(),\n agentId: z.string().uuid(),\n platform: z.literal('feishu'),\n feishu: IntegrationFeishuConfig\n })\n]);\n/** C→D EVT — install/update an integration on the owning agent's daemon. */\nexport const IntegrationUpsert = IntegrationSpec;\n/** C→D EVT — remove an integration from the daemon. */\nexport const IntegrationRemove = z.object({\n integrationId: z.string().uuid()\n});\n/**\n * One conversation the bot participates in (metadata only — no messages).\n * `kind` distinguishes member channels from direct conversations (resource-\n * visibility.md §14.3): absent = 'channel' for wire compatibility. DM rows\n * (`kind: 'im'`, Slack \"D…\" ids) are reported only for gated integrations, on\n * first inbound DM; their `name` is the counterpart's display name. Group DMs\n * (`kind: 'mpim'`, Slack multi-person DMs) are reported on observation the same\n * way — never enumerated, because Slack does not list them as bot membership —\n * but they behave like a channel: several humans share the room, so the agent\n * stays mention-gated there rather than answering every message.\n *\n * `spaceId`/`space` identify the container the conversation lives in — a Discord\n * GUILD, which a bot in several servers needs for the channel to be identifiable at\n * all (every server has a \"#general\"). The ID is the identity: two distinct guilds\n * may carry the SAME name, so grouping on the name alone would merge them and hide\n * the ambiguity it was meant to resolve. `space` is the display label only. Both are\n * absent on platforms with one implicit container per bot (Slack workspace, Telegram,\n * Feishu tenant) and on DM rows.\n */\nexport const IntegrationChannel = z.object({\n id: z.string(), // platform conversation id (Slack \"C…\" / DM \"D…\")\n name: z.string().optional(), // \"#deploys\" without the hash (or DM counterpart); absent if lookup failed\n spaceId: z.string().optional(), // enclosing Discord guild snowflake — the space's IDENTITY\n space: z.string().optional(), // that guild's display name; absent until resolved\n isPrivate: z.boolean().optional(),\n kind: z.enum(['channel', 'im', 'mpim']).optional() // absent = 'channel'\n});\n/**\n * D→C EVT — channels observed by an integration's bot (fire-and-forget,\n * latest-wins). Slack reports an authoritative membership snapshot; platforms\n * such as Telegram that cannot enumerate every chat set `authoritative:false`,\n * so the CP upserts what was observed without deleting older rows that are\n * absent from this report. An absent flag means authoritative for wire\n * compatibility. Channel names are control metadata, never message content.\n */\nexport const IntegrationChannels = z.object({\n integrationId: z.string().uuid(),\n channels: z.array(IntegrationChannel),\n authoritative: z.boolean().optional()\n});\n//# sourceMappingURL=integration.js.map","import { z } from 'zod';\nimport { AgentMemoryBinding } from './memory-connection.js';\nimport { IntegrationSpec } from './integration.js';\nimport { CronUpsert } from './cron.js';\n/**\n * Agent lifecycle (protocol §4.4, §7.4, §8).\n *\n * There is no CP→daemon prompt-delivery frame: the daemon prompts an agent from\n * its own ingress (platform adapters or relay `rd/*` delivery), never the CP.\n * The old `agent/prompt` + per-agent `seq` machinery was reserved infrastructure\n * with no live caller and has been removed.\n */\n/**\n * Where the agent runs. Two modes; the **path is always daemon-generated** —\n * never specified by the caller (UX picks the mode, the machine owns the dir).\n *\n * - `scratch`: a fresh empty working dir on the machine, with no default repo.\n * `gitCredential: github-app` enables credentials only for repositories that\n * were explicitly authorized for the agent.\n * - `github`: the daemon clones `gitRepo` @ `branch` and runs the agent in\n * `agentDir` (a subdir of the repo, repo-root if omitted). **Multiple agents\n * may share one repo** — they differ by `agentDir`, so the repo is not an\n * owned entity, just shared config on each agent.\n */\nexport const AgentWorkspace = z.discriminatedUnion('mode', [\n z.object({\n mode: z.literal('scratch'),\n // Scratch has no implicit/default repository. The credential helper still\n // lets git/gh request explicitly authorized repositories by name.\n gitCredential: z.enum(['github-app']).optional()\n }),\n z.object({\n mode: z.literal('github'),\n gitRepo: z.string(), // FULL cloneable address, e.g. https://github.com/acme/infra (normalizeGitUrl)\n branch: z.string().default('main'),\n agentDir: z.string().optional(), // subdir within the repo; omitted ⇒ repo root\n // Credential mode for remote git ops. Absent ⇒ anonymous (public repos,\n // the pre-github-app behavior). 'github-app' ⇒ the daemon pulls short-lived\n // CP-minted installation tokens over gitcred/request and injects them via\n // the local credential helper — no durable git credential on the host.\n gitCredential: z.enum(['github-app']).optional()\n })\n]);\n/**\n * MCP-server name reserved for the daemon's own injected stdio bridge (its\n * platform tools). A config-defined or agent-enabled server under this name\n * would collide with the bridge entry at ACP `session/new`, so the daemon\n * strips it and the CP rejects it in `AgentSpec.mcpServers` at the API edge.\n */\nexport const RESERVED_MCP_SERVER_NAME = 'agentconnect';\n/**\n * The curated Lucide glyph set a `glyph` icon may use — the single source of\n * truth for the picker, the DTO validation, and the CP icon-endpoint renderer.\n * `glyph` is constrained to this set so an API/CLI-created icon can't persist a\n * name the console `<Icon>` and the PNG endpoint don't both render. The web\n * picker mirrors this list (it does not import this package) — keep in sync.\n */\nexport const AGENT_ICON_GLYPHS = [\n // The AgentConnect brand diamond — the fixed identity of the built-in preset\n // agents (preset-agents.md §3.1). Renderers special-case it: a multi-color\n // brand mark (not a Lucide stroke glyph) drawn plateless — the native logo,\n // its `color` field inert. The web picker deliberately does NOT offer it in\n // its grid, though a stored value renders everywhere.\n 'agentconnect',\n 'bot',\n 'cpu',\n 'terminal',\n 'code',\n 'rocket',\n 'zap',\n 'bug',\n 'git-branch',\n 'message-square',\n 'sparkles',\n 'brain',\n 'wrench',\n 'ship',\n 'box',\n 'hexagon',\n 'compass',\n 'atom',\n 'flame',\n 'star',\n 'heart',\n 'globe',\n 'database',\n 'shield',\n 'feather'\n];\n/**\n * An agent's display icon (docs: the Console \"Agent Avatar\" picker). A\n * discriminated union on `kind`:\n * - `runtime` — derive the mark from the agent's runtime (Claude/Codex/…), the\n * legacy behavior; also the meaning of a null/absent icon.\n * - `glyph` — a curated Lucide glyph (see {@link AGENT_ICON_GLYPHS}) on a solid\n * color plate (the create-time random default is a `glyph`). An unknown glyph\n * fails to parse and degrades to the runtime mark on every surface.\n * - `image` — a user-uploaded avatar. The bytes live in the CP's configured\n * object store (S3-compatible; see docs/designs/icon-uploads.md), NOT in this\n * descriptor. Its optional opaque generation distinguishes successive writes\n * to the stable object key; legacy rows omit it. The display/serve URL is\n * resolved separately (the object store's public URL for the owner's key),\n * surfaced as the DTO `iconUrl` / `AgentSpec.iconUrl`. Set only via the upload\n * route; never via a create/update body.\n * This descriptor is CP-owned + stored on the agent and surfaced to the web\n * console. The daemon never receives it — it gets only the resolved public\n * `AgentSpec.iconUrl` (for the Slack per-message avatar), so it needs no renderer.\n */\nexport const AgentIcon = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('runtime') }),\n z.object({ kind: z.literal('glyph'), glyph: z.enum(AGENT_ICON_GLYPHS), color: z.string() }),\n z.object({ kind: z.literal('image'), generation: z.string().min(1).max(128).optional() })\n]);\n/**\n * A self-contained skill source the daemon installs via `npx skills` after the\n * workspace is ready and before the ACP host spawns (design: shared-skills.md §4).\n * The source definition rides INLINE on the AgentSpec (and lands in agent.json,\n * like mcpServers) — there is no separate skillsource frame or daemon-side def\n * cache. The CP resolves each agent's enabled org-level `SkillSource` rows into\n * these entries when it builds the spec.\n */\n// These strings become positional/`-s` arguments to `npx skills`, so a leading\n// \"-\" would be read as a flag rather than a value. Reject option-looking values at\n// the wire boundary — the daemon validates again in depth.\nconst SkillArg = z\n .string()\n .min(1)\n .refine((s) => !s.startsWith('-'), { message: 'must not start with \"-\"' });\nexport const AgentSkillEntry = z.object({\n // Display/log label — the org-level source name. NOT passed to the CLI.\n name: z.string(),\n // The source string fed straight to `npx skills add` (owner/repo, a full git\n // URL, or a tree/<ref>/<subdir> path). Everything else here is optional.\n source: SkillArg,\n // Optional branch/tag/commit. The daemon composes it into the source when set;\n // a tag/commit pins content, a branch/absent tracks the head (design §5).\n ref: z.string().optional(),\n // Optional repo-relative install directory.\n subDir: z.string().optional(),\n // Which skills from the source to install (passed as repeated `-s`). Empty ⇒\n // install every skill the source exposes (no `-s`).\n skills: z.array(SkillArg).default([])\n});\n/** One centrally accepted, immutable Agent Skills bundle enabled for an agent.\n * Content is fetched separately in bounded chunks; AgentSpec carries metadata\n * only so register/agent-upsert frames stay small. */\nexport const ManagedSkillEntry = z\n .object({\n id: z.string().uuid(),\n name: z.string().regex(/^[a-z0-9][a-z0-9-]{0,62}$/),\n revision: z.number().int().positive(),\n digest: z.string().regex(/^sha256:[a-f0-9]{64}$/)\n})\n .strict();\n/**\n * The editable agent definition the CP owns and the daemon needs to run it:\n * prompt + runtime selection. The launch protocol carries this config and the\n * daemon synthesizes the system prompt locally; `description` IS the prompt.\n */\nexport const AgentSpec = z.object({\n name: z.string(),\n // Human-readable bot name. CP snapshots/upserts always ship value or null so\n // clearing it removes a stale daemon-local display name; absent remains\n // available to hand-authored/partial specs as \"leave unchanged\".\n displayName: z.string().nullable().optional(),\n // Absolute, publicly-fetchable avatar URL the CP resolves from the agent's icon\n // (agent.icon → the CP icon endpoint for runtime/glyph, or the image URL directly).\n // The daemon uses it as the Slack per-message `icon_url` (chat:write.customize) —\n // the sibling of displayName→username (PR #539). CP ships value or null so clearing\n // the icon drops the override; null/absent ⇒ Slack keeps the app's default avatar.\n iconUrl: z.string().url().nullable().optional(),\n // The system prompt seed; appended to the daemon's standing prompt. The CP always\n // ships it as a string — a cleared description replicates as \"\" so the daemon\n // overwrites a stale seed; an absent key means \"leave unchanged\" (hand-authored/\n // partial specs). Deliberately NOT nullable: older daemons parse this as a plain\n // string and would reject a null register/ok roster entry, failing the whole\n // handshake. An empty prompt seed and \"no description\" are equivalent, so the \"\"\n // collapse is lossless.\n description: z.string().optional(),\n runtime: z.string().optional(), // which ACP runtime to run, e.g. \"claude\" / \"codex\"\n // Per-runtime override vocabularies (model / effort / permission mode). Switching\n // runtime invalidates them, so the CP must be able to CLEAR them, not just set them:\n // absent ⇒ leave the on-disk value alone (hand-authored agent.json / partial spec)\n // null ⇒ clear the override (revert to the runtime's own default)\n // string ⇒ set it\n // The CP's agentRecordToSpec always ships these (value or null) so a clear replicates.\n model: z.string().nullable().optional(), // runtime model, e.g. \"opus\"\n reasoningEffort: z.string().nullable().optional(),\n executionMode: z.string().optional(), // e.g. \"byoc\"\n outputMode: z.enum(['none', 'minimal', 'low', 'medium', 'high']).optional(), // platform output verbosity → agent.json output.mode ('none' = session-only, nothing to the IM)\n showFooter: z.boolean().optional(), // render platform attribution/session footers; absent ⇒ leave agent.json unchanged\n fastMode: z.boolean().optional(), // runtime fast mode (ACP `model_config` toggle); absent ⇒ leave runtime default\n permissionMode: z.string().nullable().optional(), // runtime permission/approval mode (ACP `mode` selector); absent ⇒ leave alone, null ⇒ clear\n // Explicit opt-in: when false, conversation participants cannot change runtime\n // settings (model, effort, permission mode, fast mode) or answer approval\n // requests. Agent editors decide pending requests from the console instead.\n allowRuntimeChangesInChat: z.boolean().optional(),\n // Operational message-processing toggle (orthogonal to placement). When true the\n // agent stays placed/connected but the daemon skips ALL turn dispatch (platform,\n // webchat, cron). Optional (not defaulted) so an absent value leaves the on-disk\n // agent.json pause untouched — same contract as fastMode/permissionMode.\n pause: z.boolean().optional(),\n workspace: AgentWorkspace.optional(), // where it runs; absent ⇒ daemon defaults to scratch\n env: z.record(z.string(), z.string()).optional(), // extra env injected into the runtime\n // Write-only secret env vars: same injection as `env` (merged into the spawned\n // child's environment, secrets winning on a key collision), but their VALUES never\n // travel back out — the CP DTO exposes only the key names, and the console masks\n // them. Plaintext at rest (like `env`) and shipped over the TLS WS; \"secret\" here\n // means write-only from the API/UI, not KMS-sealed. Always shipped (even {}) so a\n // removed secret replicates, same contract as `env` below.\n secrets: z.record(z.string(), z.string()).optional(),\n // Which memory backend the agent uses (design: docs/designs/memory-evolution.md):\n // managed — our <agent-root>/memory/ directory (default)\n // native — the runtime's own memory (Claude auto-memory / Codex memories),\n // redirected under the agent root for per-agent isolation\n // external — an outside service (mem0); not yet implemented\n // none — disable both daemon-managed and runtime-native persistent memory\n // Optional (absent ⇒ leave the on-disk agent.json value alone — same contract as\n // fastMode/pause). A brand-new agent with no value defaults to managed daemon-side.\n memory: AgentMemoryBinding.optional(),\n // Names of daemon-configured MCP servers (daemon config `mcpServers`, reported\n // via `facts/daemon-runtimes`) to attach at `session/new`. Empty/absent ⇒ none.\n mcpServers: z.array(z.string()).default([]),\n // Skill sources to install into the workspace before the ACP host spawns\n // (design: shared-skills.md). Unlike mcpServers (names resolved daemon-side),\n // these are SELF-CONTAINED entries — the daemon needs nothing but agent.json to\n // run `npx skills`. Always shipped (even []) so removing the last skill replicates.\n skills: z.array(AgentSkillEntry).default([]),\n // Centrally accepted `.skill` ZIP revisions. Unlike Git source entries above,\n // these are digest-addressed metadata; the daemon downloads/cache-verifies the\n // bundle through managed-skill/read before session start.\n managedSkills: z\n .array(ManagedSkillEntry)\n .max(64)\n .refine((entries) => new Set(entries.map((entry) => entry.id)).size === entries.length, {\n message: 'managed skill ids must be unique'\n })\n .default([]),\n // Agent→agent call authorization (design §2.5). `callPolicy` gates who may wake\n // this agent via the `messageAgent` tool: 'all' ⇒ any peer in the org, 'selected'\n // ⇒ only agents in `allowedCallerAgentIds`. Replicated CP→daemon so the daemon can\n // enforce the policy LOCALLY on same-daemon delivery (no CP hop on the hot path).\n // Optional (absent ⇒ leave the on-disk agent.json value alone — same contract as\n // pause/memory); `allowedCallerAgentIds` always ships (even []) so removing the last\n // allowed caller replicates.\n callPolicy: z.enum(['all', 'selected']).optional(),\n allowedCallerAgentIds: z.array(z.string()).default([]),\n // Outbound half of agent→agent authorization. `selected` means this agent may\n // discover/message only peers in `allowedTargetAgentIds`. The target's inbound\n // policy must also allow this agent; effective authorization is the intersection.\n // Both fields remain optional when decoding an older CP payload so a mixed-version\n // update cannot retain an on-disk `selected` mode while silently clearing its list.\n // A current CP always ships both fields, including [] to clear the final member.\n outboundPolicy: z.enum(['all', 'selected']).optional(),\n allowedTargetAgentIds: z.array(z.string()).optional(),\n // Self-introduce-on-join (issue #536): when true, on a genuine new channel join the\n // agent proactively introduces itself to the peers already there (via listAgents\n // → messageAgent) so they can record it in memory. Replicated CP→daemon. Optional\n // (absent ⇒ leave the on-disk agent.json value alone — same contract as pause/fastMode).\n introduceOnJoin: z.boolean().optional(),\n // Per-agent OS sandbox preference (issue #642). It is effective only when the\n // host has bwrap/sandbox-exec; daemon `security.requireSandbox` forces it on and\n // prevents daemon startup when no mechanism exists. Optional means leave the\n // on-disk agent.json value alone; a brand-new agent defaults to false.\n restrictFileAccess: z.boolean().optional()\n});\nexport const AgentLaunch = z.object({\n // C→D, carries ControlExt(epoch)\n agentId: z.string().uuid(),\n runtime: z.string(), // must be in RegisterReq.capabilities.runtimes\n workspaceId: z.string().uuid(),\n capabilities: z.array(z.string()), // the active-capability pin (§8.1)\n spec: AgentSpec, // prompt/model/env — arrives at start, no separate CRUD needed\n mode: z.enum(['long_lived', 'per_turn']).default('long_lived'), // 🅰️ decision #2 knob\n // Web API launch provenance (session-visibility.md §4.4): CP-minted when the\n // launch was requested by a console user, echoed back by the daemon on the\n // resulting session's `event/session` so ingest can classify it `private`\n // with that user as owner. Optional — CLI/orchestration launches and older\n // CPs omit it. NOT the launchId fence (which is per-launch, not per-user).\n launchCorrelationId: z.string().uuid().optional()\n});\n/**\n * Live agent CRUD (C→D): the console edited an agent's spec; push it so a\n * running daemon reloads without waiting for the next launch. `agent/remove`\n * tears the agent down. Deleting an agent never relaunches it.\n */\nexport const AgentUpsert = z.object({\n agentId: z.string().uuid(),\n spec: AgentSpec\n});\nexport const AgentRemove = z.object({\n agentId: z.string().uuid()\n});\n/**\n * Safe cold-move lifecycle (C→D REQ → generic `ack`). `agent/detach`\n * quiesces the agent and archives its daemon-local root; `agent/activate`\n * atomically applies the authoritative spec/integration/cron bundle, restores\n * and exact-prunes an archive when present, then makes the agent servable.\n */\nexport const AgentDetach = z.object({\n agentId: z.string().uuid(),\n /** Fences late lifecycle retries from a superseded move operation. */\n moveId: z.string().uuid(),\n /** Scratch→GitHub conversion guard. The daemon drains the agent first, then\n * ACKs only when the live scratch working directory is still empty. */\n requireEmptyWorkspace: z.boolean().optional()\n});\nexport const AgentActivate = z.object({\n agentId: z.string().uuid(),\n moveId: z.string().uuid(),\n /**\n * One authoritative, acknowledged bootstrap bundle. Unlike the live CRUD\n * EVTs, these definitions are synchronously persisted under the staging gate\n * before activation can ACK, so a same-id stale secret/spec cannot survive.\n */\n spec: AgentSpec,\n integrations: z.array(IntegrationSpec),\n crons: z.array(CronUpsert),\n /** Prove the requested workspace can be materialized before activation ACK.\n * Used by scratch→GitHub conversion so a failed clone can be rolled back. */\n prepareWorkspace: z.boolean().optional(),\n /** Reconcile the daemon-local workspace to the authoritative mode/repo/branch.\n * The daemon preserves the checkout when that materialization is unchanged,\n * and replaces its contents when it changed. */\n reconcileWorkspace: z.boolean().optional()\n});\nexport const AgentLaunched = z.object({\n // D→C, REP/EVT\n agentId: z.string().uuid(),\n launchId: z.string().uuid(), // new fence value\n acpSessionId: z.string().optional(), // 🅰️ present iff long-lived ACP session (default)\n startedAt: z.string().datetime(),\n runtime: z.string() // e.g. \"claude\" / \"codex\"\n});\nexport const AgentStop = z.object({\n agentId: z.string().uuid(),\n launchId: z.string().uuid(),\n reason: z.string()\n});\nexport const AgentActivity = z.object({\n // D→C, EVT — activity-probe (§7.4)\n agentId: z.string().uuid(),\n launchId: z.string().uuid(),\n state: z.enum(['thinking', 'tool_call', 'awaiting_permission', 'idle']),\n ts: z.string().datetime()\n});\nexport const AgentScopeDenied = z.object({\n // D→C, EVT — capability-scope audit (§8.1)\n agentId: z.string().uuid(),\n launchId: z.string().uuid(),\n capability: z.string()\n});\n/** Editor approval queue. The daemon owns the live resolver and durable local\n * history; the Control Plane only proxies this bounded, secret-masked summary. */\nexport const AgentPermissionRequestRecord = z.object({\n id: z.string().uuid(),\n agentId: z.string().uuid(),\n // Optional for rolling compatibility with daemons that predate session-scoped\n // approval rendering. Current daemons always report the owning ACP session id.\n sessionId: z.string().min(1).optional(),\n createdAt: z.string().datetime(),\n requesterId: z.string().nullable(),\n requesterName: z.string().nullable(),\n command: z.string().max(240),\n status: z.enum(['pending', 'allowed', 'denied', 'expired']),\n resolvedAt: z.string().datetime().nullable()\n});\nexport const AgentPermissionRequestList = z.object({\n agentId: z.string().uuid(),\n limit: z.number().int().min(1).max(100).default(50)\n});\nexport const AgentPermissionRequestPage = z.object({\n agentId: z.string().uuid(),\n requests: z.array(AgentPermissionRequestRecord)\n});\nexport const AgentPermissionDecision = z.object({\n agentId: z.string().uuid(),\n requestId: z.string().uuid(),\n decision: z.enum(['allow', 'deny'])\n});\n//# sourceMappingURL=agent.js.map","import { z } from 'zod';\n/**\n * Centralized MCP-provider distribution (C→D) — docs/designs/centralized-tool-management.md.\n *\n * The Control Plane owns MCP provider definitions and pushes them to the daemons\n * whose agents enable them (`mcpserver/upsert`, and the reconcile snapshot\n * `RegisterOk.mcpServers[]`). The daemon merges the spec into its `mcpServerDefs`\n * and attaches it at ACP `session/new` through the existing resolve path — a\n * pushed def is just an `http` MCP server.\n *\n * MCP-PROXY MODEL: in v1 the pushed `url` is a RELAY proxy URL and the injected\n * header is a short-lived **grant key** (`Authorization: Bearer …`) — never the\n * upstream endpoint or its real credential. Those stay on the CP + relay (§5).\n * SECURITY: `env`/`headers` may carry that bearer grant key — NEVER log this frame.\n */\n/** The `{name, value}[]` shape shared by MCP env + headers (mirrors the daemon's local McpServerDef). */\nconst NameValueList = z.array(z.object({ name: z.string(), value: z.string() })).default([]);\n/**\n * One MCP server definition the CP pushes to a daemon. Shape mirrors the daemon's\n * local `McpServerDef` (daemon config-schema.ts) with `name` inlined (the daemon\n * config keys the map by name). Transport-agnostic on the wire; the CP restricts\n * what it emits (v1 pushes proxied `http` defs only — the `sse`/`stdio`-only\n * restriction is a CP-side policy, not a wire constraint).\n */\nexport const McpServerSpec = z\n .object({\n name: z.string(),\n transport: z.enum(['stdio', 'http', 'sse']).default('stdio'),\n command: z.string().optional(),\n args: z.array(z.string()).default([]),\n env: NameValueList,\n url: z.string().optional(),\n headers: NameValueList\n})\n .superRefine((def, ctx) => {\n if (def.transport === 'stdio' && !def.command)\n ctx.addIssue({ code: 'custom', path: ['command'], message: 'a stdio MCP server requires \"command\"' });\n if (def.transport !== 'stdio' && !def.url)\n ctx.addIssue({ code: 'custom', path: ['url'], message: `a ${def.transport} MCP server requires \"url\"` });\n});\n/** C→D EVT (`mcpserver/upsert`) — add or replace a pushed MCP server def on the daemon. */\nexport const McpServerUpsert = McpServerSpec;\n/** C→D EVT (`mcpserver/remove`) — drop a pushed MCP server def by name. */\nexport const McpServerRemove = z.object({ name: z.string() });\n//# sourceMappingURL=mcpserver.js.map","import { z } from 'zod';\nimport { Platform } from './route.js';\n/**\n * Bot-AGNOSTIC agent-collaboration routing snapshot (agent-collaboration §2.3 / §6.2 / §6.5).\n *\n * The existing shared-bot `members` table is keyed by botId (`BotAssignment`) and\n * CANNOT address an agent on a DIFFERENT bot / arbitrary channel. This snapshot is\n * the fix: it maps a channel — `(orgId, platform, channelId)` — to the per-agent\n * placement + call policy the relay needs to route a cross-daemon `rd/agentmsg` and\n * the target daemon needs to terminal-verify a remote caller.\n *\n * It carries NO message body — pure routing/policy metadata, like the rest of the\n * control plane. The SAME shape is distributed two ways (§6.5):\n * - CP→relay over the `rc/*` wire (`rc/collab-routes`) — the relay routes\n * `toAgentId` → owning `daemonId` and authorizes the caller/target policy.\n * - CP→daemon over the daemon↔CP wire — as a `register/ok` field (reconnect\n * baseline) + a `collaboration/routes` EVT (hot push) — so the OWNING daemon of\n * the target can terminal-verify (defense in depth, §2.5 #4) the remote caller's\n * org/channel/placement against its OWN copy, never trusting the relay's claim\n * blindly.\n *\n * FOLLOW-UP (scoped down in P2, see PR description): the full versioned lifecycle\n * of §6.5 — per-entry tombstones, TTL/expiry after a CP disconnect, and\n * fail-closed-on-stale — is NOT fully implemented here. `generation` is present as\n * the version hook and the snapshot is FULL-REPLACE (converge-don't-diff, same as\n * `register/ok`), which is enough to route + authorize on a live CP. TTL-expiry and\n * tombstone semantics are a follow-up within this phase.\n */\n/** One agent's placement + call policy within a channel. `daemonId` is the owning\n * daemon the relay forwards to; `integrationId` is the DEFINITE reply integration\n * (§6.2 — no fallback to \"first connection\"). */\nexport const CollabAgentPlacement = z.object({\n agentId: z.string().uuid(),\n daemonId: z.string().uuid(),\n integrationId: z.string().uuid().optional(),\n /** Public Slack app id (`A…`) for this agent's bot. Receivers use it only to\n * recognize AgentConnect-authored platform messages and keep agent-to-agent\n * activation on the trusted `messageAgent` path. */\n botAppId: z.string().optional(),\n callPolicy: z.enum(['all', 'selected']).default('all'),\n allowedCallerAgentIds: z.array(z.string()).default([]),\n /** Caller-side authorization. Effective A→B access requires A's outbound\n * policy to admit B and B's inbound call policy to admit A. */\n outboundPolicy: z.enum(['all', 'selected']).default('all'),\n allowedTargetAgentIds: z.array(z.string()).default([]),\n // Directory name of the agent — carried so any daemon holding the snapshot can label a\n // REMOTE peer (caller or target) by name in a visible agent-call post, without a CP\n // round-trip or having listed the channel. `name` is the slug; `displayName` the\n // human-readable label. Optional for back-compat with an older CP that omits them.\n name: z.string().optional(),\n displayName: z.string().optional()\n});\n/**\n * One agent's placement + call policy carried OUTSIDE any channel — the org-scoped\n * peer directory entry.\n *\n * Every structure on the CP→daemon and CP→relay wires is channel-keyed, so an agent\n * with NO IM integration (webchat, hook, dream, memory-only) never appears in any\n * `channels[]` entry at all. The channel-keyed snapshot structurally cannot express\n * \"which agents exist in this org\", which is precisely the input channel-free\n * authorization needs: discovery and A2A authorization depend only on the directional\n * call policy (`outboundPolicy`/`allowedTargetAgentIds` on the caller,\n * `callPolicy`/`allowedCallerAgentIds` on the target), org-scoped, with channel\n * demoted to an optional filter. Hence the flat list below.\n */\nexport const CollabOrgAgent = CollabAgentPlacement.extend({\n // Org ids are opaque strings (see CollabChannelRoute) — carried per entry because\n // the flat list is not nested under an org-keyed parent. Cross-org pairs never resolve.\n orgId: z.string().min(1)\n});\n/** All agents present in one channel, across daemons. `orgId` scopes routing +\n * authorization: a cross-org caller/target pair never resolves (§2.5 — cross-org\n * rejected). */\nexport const CollabChannelRoute = z.object({\n // Org ids are opaque strings (Prisma uses cuid(); the seeded dev org uses\n // `org_default...`), unlike daemon/agent/integration ids which are UUIDs.\n orgId: z.string().min(1),\n platform: Platform,\n channelId: z.string().min(1),\n agents: z.array(CollabAgentPlacement)\n});\n/**\n * The full collaboration snapshot — FULL-REPLACE (converge-don't-diff): the\n * recipient replaces its whole table with `channels`. `generation` monotonically\n * increases per source so a recipient can ignore a stale re-order (version hook for\n * the §6.5 lifecycle follow-up).\n */\nexport const CollabRoutesSnapshot = z.object({\n generation: z.number().int().nonnegative().default(0),\n channels: z.array(CollabChannelRoute).default([]),\n /**\n * FLAT org-scoped directory, alongside (not instead of) `channels`. It is the only\n * place an integration-less agent can appear — see `CollabOrgAgent` — and therefore\n * the authorization input for channel-free A2A. `default([])` keeps a snapshot from\n * an older CP (which advertises no `agent-directory-org-scope-v1`) decodable.\n */\n agents: z.array(CollabOrgAgent).default([])\n});\n//# sourceMappingURL=collab.js.map","import { z } from 'zod';\n/**\n * Deployment GitHub App identity used for ordinary commits made by an agent.\n * This is public attribution metadata, not a credential.\n */\nexport const GitCommitIdentity = z.object({\n name: z.string().min(1),\n email: z.string().min(1)\n});\n/**\n * Git credentials (github-app workspaces) — daemon-pulled, CP-minted.\n *\n * The CP holds the GitHub App private key and mints short-lived (1h,\n * non-renewable) installation access tokens scoped to a single repository;\n * the daemon pulls one on demand right before a remote git operation and\n * holds it in memory only. Unlike `secrets/*` (lease + reference semantics,\n * still unwired), the grant here carries the TOKEN MATERIAL itself — same\n * plaintext-over-TLS-WS posture as `integration/upsert`, and the same\n * discipline: **never log the payload**.\n *\n * The daemon may only name an agentId — the CP resolves agent → workspace →\n * repo → installation itself, so a daemon can never pick a repo it wasn't\n * assigned. Failures come back as correlated `error` REPs: `SCOPE_DENIED`\n * (not a github-app workspace, or agent not placed on this daemon — stop\n * asking), `LEASE_DENIED` (installation uninstalled/suspended or the repo\n * left its grant set — recoverable only by an operator), `RATE_LIMITED`,\n * `INTERNAL`.\n */\n/**\n * Token capability classes (webhook-triggers-and-github-events.md P2.5 write-back).\n * `contents` is the git data plane (the pre-capabilities behavior); `issues` /\n * `pull_requests` buy the agent `gh` write-back (issue/PR comments), and\n * `actions` buys GitHub Actions inspection/execution. Every\n * General agent credentials mint every capability admitted by the repo's\n * `gitAccess` / authorization tier — a read-only agent gets read-only\n * issues/PR scopes and no Actions capability.\n * The one exception is purpose=github_hook_reply: a daemon-owned writer whose\n * token never enters the agent environment and is gated by an enabled hook.\n */\nexport const GitCredCapability = z.enum(['contents', 'issues', 'pull_requests', 'actions']);\nexport const GitCredRequest = z.object({\n // D→C, REQ\n agentId: z.string().uuid(),\n reason: z.enum(['clone', 'fetch', 'pull', 'push', 'helper']).optional(), // observability only\n // Absent ⇒ ['contents'] — pre-P2.5 daemons keep byte-identical behavior.\n capabilities: z.array(GitCredCapability).nonempty().optional(),\n // The daemon-owned GithubPoster is a narrower consumer than an agent's git/\n // gh tools: its token never enters the agent environment and may only back\n // the one final comment for an enabled GitHub hook turn. Marking that purpose\n // explicitly lets the CP apply the hook authorization instead of incorrectly\n // clamping the comment token to the workspace contents gitAccess.\n purpose: z.literal('github_hook_reply').optional(),\n // Trusted hook identity copied from the relay-delivered rd/msg. Required by\n // the CP for purpose=github_hook_reply so authorization stays rename-safe on\n // HookDef.repoId instead of comparing mutable owner/repo display names.\n hookId: z.string().uuid().optional(),\n // A poster sets this only after GitHub rejects a cached token with 401/403.\n // The CP then bypasses its installation-token cache exactly once; ordinary\n // git/gh requests ignore it.\n forceRefresh: z.boolean().optional(),\n // Absent ⇒ the agent's workspace repo (pre-multi-repo behavior). \"owner/repo\".\n // The CP admits only workspace ∪ the agent's AgentRepoAuthorization rows and\n // mints the requested capability subset at the row's access tier — the daemon\n // still cannot pick an arbitrary repo (agent-multi-repo-authorization.md\n // decision 2). A purpose=github_hook_reply request is separately gated by an\n // enabled GitHub hook and receives only issues/PR write, never contents. Old\n // CPs strip this field and answer with a WORKSPACE grant: consumers MUST\n // verify grant.repoFullName against what they asked for before trusting it.\n repoFullName: z.string().optional()\n});\nexport const GitCredGrant = z.object({\n // C→D, REP (plaintext token — never log)\n username: z.literal('x-access-token'), // fixed HTTPS basic-auth username for installation tokens\n token: z.string(), // ghs_… — new stateless format runs ~520 chars; never assume a length\n ttlSec: z.number().int(), // CP-computed remaining life, 60s clock-skew allowance already shaved.\n // Daemons MUST track expiry as monotonic receivedAt+ttlSec (a skewed local\n // clock must never resurrect a dead token); `expiresAt` is observability only.\n expiresAt: z.string().datetime(),\n repoFullName: z.string(), // owner/repo — helper path-match + diagnostics\n access: z.enum(['read', 'write'])\n});\n//# sourceMappingURL=gitcred.js.map","import { z } from 'zod';\nimport { Platform, RouteAssign } from './route.js';\nimport { CronUpsert } from './cron.js';\nimport { SecretsGrant } from './secrets.js';\nimport { AgentSpec } from './agent.js';\nimport { IntegrationSpec } from './integration.js';\nimport { McpServerSpec } from './mcpserver.js';\nimport { MemoryConnectionSpec } from './memory-connection.js';\nimport { CollabRoutesSnapshot } from './collab.js';\nimport { GitCommitIdentity } from './gitcred.js';\n/**\n * Capability upload + the reconcile snapshot — protocol §3.3.\n *\n * `register/ok` is the authoritative source of truth: the daemon converges its\n * local cache to it. CP wins all conflicts, so re-issuing the same snapshot is\n * idempotent.\n */\nexport const RegisterReq = z.object({\n host: z.string(), // hostname (display only)\n capabilities: z.object({\n platforms: z.array(Platform), // D3 adapters present\n runtimes: z.array(z.string()), // e.g. [\"claude\",\"codex\"]\n acp: z.boolean(), // can this daemon host ACP sessions (D6)?\n features: z.array(z.string()).default([]) // e.g. [\"cli-wrapper-fallback\",\"worktree-iso\"]\n }),\n maxAgents: z.number().int(), // concurrency ceiling for placement (C3)\n localState: z.object({\n // what the daemon currently believes it owns (for reconcile)\n assignments: z.array(z.string()), // sessionKeys it is actively serving\n crons: z.array(z.string()), // cronIds it has scheduled\n leases: z.array(z.string()), // leaseIds it holds\n // Active on-disk replicas. `unknown` is the rolling-upgrade/legacy value:\n // the CP may prune it only when the durable row proves the replica moved.\n // Defaults keep an older daemon compatible with a newer CP.\n agents: z.array(z.object({ agentId: z.string(), origin: z.enum(['cp', 'unknown']) })).default([]),\n integrations: z.array(z.object({ integrationId: z.string(), origin: z.enum(['cp', 'unknown']) })).default([]),\n // Durable fail-closed move tombstones. A newer CP repairs entries with a\n // valid token after register/ok. A missing token represents corrupt local\n // metadata: the daemon keeps that agent drained for manual repair without\n // making the whole registration undecodable.\n stagedAgents: z.array(z.object({ agentId: z.string(), moveId: z.string().uuid().optional() })).default([])\n })\n});\n/**\n * One relay the daemon SHOULD hold an outbound WS to (shared-bot-relay.md §5).\n * The roster is all-to-all by design: a webchat/webhook landing on ANY relay\n * instance must find this daemon's connection without cross-instance forwarding.\n * That only holds if `url` (the relay's registered `daemonUrl`) routes to that\n * SPECIFIC instance — the daemon confirms the landing spot against\n * `rd/hello/ok.relayId` and treats a mismatch as a deployment misroute.\n */\nexport const RelayRosterEntry = z.object({\n relayId: z.string().uuid(),\n url: z.string() // the relay's daemonUrl — per-instance routable, never a pool LB\n});\n/**\n * C→D EVT (`relay/roster`) — hot roster update (relay registered / swept).\n * Carries the WHOLE desired set, same converge-don't-diff semantics as the\n * `register/ok.relays` snapshot it refreshes.\n */\nexport const RelayRosterUpdate = z.object({\n relays: z.array(RelayRosterEntry)\n});\nexport const RegisterOk = z.object({\n routingEpoch: z.number().int(), // version of the routing table this snapshot reflects\n // CP protocol capabilities. Default keeps a new daemon compatible with an\n // older CP during rolling deploys; old daemons ignore this additive field.\n serverFeatures: z.array(z.string()).default([]),\n // Public attribution for github-app workspace commits. Derived from this\n // deployment's App slug; optional so new daemons still accept an older CP.\n gitCommitIdentity: GitCommitIdentity.optional(),\n // Authoritative reconcile snapshot — daemon converges its local cache to this:\n assignments: z.array(RouteAssign), // the route/assign set the daemon SHOULD own\n agents: z.array(AgentSpec.extend({ agentId: z.string().uuid() })).default([]), // spec set CP wants present; daemon converges\n crons: z.array(CronUpsert), // the cron set it SHOULD run\n // Platform integrations this daemon SHOULD hold — FILTERED to this daemon (never\n // org-wide), since each element carries plaintext tokens. Never log this array.\n integrations: z.array(IntegrationSpec).default([]),\n // MCP server defs this daemon SHOULD hold — FILTERED to this daemon (only providers\n // its agents enable). In the MCP-proxy model these carry a relay proxy URL + a bearer\n // grant key (not the upstream secret), but treat as sensitive — never log this array.\n // Defaulted so a pre-MCP-registry CP's snapshot still parses.\n mcpServers: z.array(McpServerSpec).default([]),\n // External-memory defs this daemon's agents reference. Relay grants and local\n // secret leases are daemon-private and must never be logged.\n memoryConnections: z.array(MemoryConnectionSpec).default([]),\n leases: z.array(SecretsGrant), // secret leases it SHOULD hold\n // Relay roster — the relays this daemon SHOULD dial (webchat ingress now;\n // shared-bot/webhook with milestone B). Hot updates ride `relay/roster`;\n // defaulted so a pre-relay CP's snapshot still parses.\n relays: z.array(RelayRosterEntry).default([]),\n // Bot-agnostic collaboration routing snapshot (agent-collaboration §2.3 / §6.5) —\n // the reconnect BASELINE for this daemon's terminal-verify of REMOTE agent callers.\n // Scoped to channels this daemon's agents participate in. Hot changes ride the\n // `collaboration/routes` EVT. Defaulted so a pre-collab CP's snapshot still parses.\n collabRoutes: CollabRoutesSnapshot.default({ generation: 0, channels: [], agents: [] }),\n drop: z.object({\n // things in localState the CP says to release\n assignments: z.array(z.string()),\n crons: z.array(z.string()),\n // A missed live move archives the replica (preserving workspace/memory); a\n // missed delete removes a replica that carries the explicit CP marker.\n agents: z.array(z.object({ agentId: z.string(), action: z.enum(['detach', 'remove']) })).default([]),\n integrations: z.array(z.string()).default([])\n })\n});\n//# sourceMappingURL=register.js.map","import { z } from 'zod'\nimport {\n DEFAULT_WORKSPACE_GIT_ALLOWED_ORIGINS,\n normalizeWorkspaceGitOrigin,\n RelayRosterEntry\n} from '@agentconnect.md/protocol'\n\n/** The `{name, value}[]` shape shared by runtime env, MCP env, and MCP headers. */\nconst NameValueList = z.array(z.object({ name: z.string(), value: z.string() })).default([])\n\nexport const RuntimeDefSchema = z.object({\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: NameValueList,\n // Operator/registry-owned read-only installation roots needed by a runtime\n // whose executable or dependencies live below a host path hidden from the\n // sandbox (most commonly HOME). Agent configuration can select a runtime but\n // cannot add entries here.\n readRoots: z.array(z.string()).optional()\n})\nexport type RuntimeDef = z.infer<typeof RuntimeDefSchema>\n\n// A daemon-configured MCP server, keyed by name in `config.mcpServers`. The name\n// is what an agent's `mcpServers` list references, and what the daemon reports\n// to the CP — definitions (command/url/headers) never leave the daemon.\n// The name \"agentconnect\" is reserved for the daemon's own injected bridge entry.\nexport const McpServerDefSchema = z\n .object({\n transport: z.enum(['stdio', 'http', 'sse']).default('stdio'),\n // stdio transport: the executable to spawn (required for stdio).\n command: z.string().optional(),\n args: z.array(z.string()).default([]),\n env: NameValueList,\n // Same trusted installation-root escape hatch as RuntimeDefSchema, for a\n // daemon-configured stdio MCP child spawned by the runtime.\n readRoots: z.array(z.string()).optional(),\n // http/sse transports: the server endpoint (required for http/sse).\n url: z.string().optional(),\n headers: NameValueList\n })\n .superRefine((def, ctx) => {\n if (def.transport === 'stdio' && !def.command)\n ctx.addIssue({ code: 'custom', path: ['command'], message: 'a stdio MCP server requires \"command\"' })\n if (def.transport !== 'stdio' && !def.url)\n ctx.addIssue({ code: 'custom', path: ['url'], message: `a ${def.transport} MCP server requires \"url\"` })\n })\nexport type McpServerDef = z.infer<typeof McpServerDefSchema>\n\nconst EnvironmentName = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, 'invalid environment variable name')\nconst MemoryPluginCommandRef = z\n .string()\n .min(1)\n .max(128)\n .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/, 'invalid memory plugin commandRef')\nconst ProcessValue = z\n .string()\n .max(16 * 1024)\n .refine((value) => !value.includes('\\0'), 'process value contains NUL')\nconst WorkspaceGitOrigin = z.string().transform((value, ctx) => {\n try {\n return normalizeWorkspaceGitOrigin(value)\n } catch {\n ctx.addIssue({\n code: 'custom',\n message: 'workspace Git origins must be exact credential-free HTTPS or SSH origins without a path'\n })\n return z.NEVER\n }\n})\n\n/** Operator-owned local memory-plugin allowlist. A tenant/CP sends only the map\n * key (`commandRef`); command, args, static env, and logical-secret→env mapping\n * never cross the control plane. */\nexport const StdioMemoryPluginDefSchema = z\n .object({\n command: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => !value.includes('\\0'), 'command contains NUL'),\n args: z.array(ProcessValue).max(128).default([]),\n env: z\n .array(z.object({ name: EnvironmentName, value: ProcessValue }).strict())\n .max(128)\n .default([]),\n secretEnv: z.record(z.string().min(1).max(128), EnvironmentName).default({})\n })\n .strict()\n .superRefine((def, ctx) => {\n const staticNames = def.env.map((entry) => entry.name)\n if (new Set(staticNames).size !== staticNames.length) {\n ctx.addIssue({ code: 'custom', path: ['env'], message: 'stdio memory plugin env names must be unique' })\n }\n const secretTargets = Object.values(def.secretEnv)\n if (new Set(secretTargets).size !== secretTargets.length) {\n ctx.addIssue({\n code: 'custom',\n path: ['secretEnv'],\n message: 'stdio memory plugin secret env targets must be unique'\n })\n }\n if (secretTargets.some((name) => staticNames.includes(name))) {\n ctx.addIssue({ code: 'custom', path: ['secretEnv'], message: 'secret env must not overwrite static env' })\n }\n })\nexport type StdioMemoryPluginDef = z.infer<typeof StdioMemoryPluginDefSchema>\n\nexport const ConfigSchema = z.object({\n version: z.literal(1),\n daemonId: z.string().optional(),\n // Base URL of the Web App console; used to build the §9.1 \"details\" deep link\n // (`<webAppUrl>/sessions/<sessionId>`). Unset ⇒ the daemon adopts the URL the CP sends\n // down on `auth/ok` (the CP is authoritative for its own console origin); only truly\n // absent when neither is set. A local config value wins over the CP-provided one.\n webAppUrl: z.string().optional(),\n controlPlane: z\n .object({\n enabled: z.boolean().default(true),\n url: z.string().optional(),\n key: z.string().optional(), // CP API key (opaque); sent as `apiKey` on the auth frame\n heartbeatMs: z.number().int().default(15000)\n })\n .default({ enabled: false, heartbeatMs: 15000 }),\n agentsDir: z.string().optional(), // resolved against root if absent\n runtimes: z.record(z.string(), RuntimeDefSchema).optional(),\n // MCP servers this daemon can attach to agent sessions (reported to the CP as\n // facts by name + transport; agents opt in by name via their `mcpServers` list).\n mcpServers: z.record(z.string(), McpServerDefSchema).optional(),\n // Local memory plugins are daemon-private, operator-installed extensions.\n // Agent/tenant configuration can reference a key but can never supply a\n // command, path, args, or secret environment target.\n memoryPlugins: z.record(MemoryPluginCommandRef, StdioMemoryPluginDefSchema).optional(),\n security: z\n .object({\n // Prevent ACP runtimes from implicitly inheriting apps/connectors attached\n // to the signed-in cloud account. Explicit local and daemon-injected MCP\n // servers remain available. Set false only to opt this daemon out.\n isolateAccountApps: z.boolean().default(true),\n // Daemon-wide sandbox policy (issue #312). When true, startup fails unless\n // Linux SRT/bwrap is available and every agent runs sandboxed; the\n // console locks the per-agent option on. false leaves it agent-selectable.\n requireSandbox: z.boolean().default(false),\n // Operator-owned remote-origin policy for daemon-managed workspace clone/pull.\n // Exact scheme + host + port only; [] disables remote Git workspaces.\n workspaceGitAllowedOrigins: z.array(WorkspaceGitOrigin).default([...DEFAULT_WORKSPACE_GIT_ALLOWED_ORIGINS])\n })\n .default({\n isolateAccountApps: true,\n requireSandbox: false,\n workspaceGitAllowedOrigins: [...DEFAULT_WORKSPACE_GIT_ALLOWED_ORIGINS]\n }),\n // Relay roster the CP last published (shared-bot-relay.md §5). Persisted whole so\n // the daemon can re-dial its relays at boot while the CP is unreachable (graceful\n // degradation); the CP's register/ok snapshot re-converges it authoritatively once\n // connected. CP-owned — overwritten on every roster converge, not hand-edited.\n relays: z.array(RelayRosterEntry).default([]),\n logging: z\n .object({ level: z.enum(['trace', 'debug', 'info', 'warn', 'error']).default('info') })\n .default({ level: 'info' }),\n limits: z\n .object({\n maxAgents: z.number().int().default(32),\n maxConcurrentSessions: z.number().int().default(32),\n // Idle window before the sweep TTL-closes a session (§7.3) AND reaps its\n // agent's ACP host back to `provisioned` (§7.2). Background work is protected\n // by the SDK-lifecycle lease (a session with live background tasks or a running\n // SDK cycle is not reclaimed regardless of this window — see\n // docs/designs/background-task-aware-reclaim.md), so this no longer has to be\n // stretched to \"long enough that background jobs finish first\". 15min: reclaim\n // genuinely-idle hosts promptly (freeing runtime child RSS); the lease, not this\n // window, is what keeps background work alive. (Was widened to 2h by bb328c01 as\n // an interim workaround before the lease existed; now dialed back.)\n agentIdleTimeoutMs: z.number().int().default(900_000),\n // Absolute host lifetime ceiling (from host start). The background-task lease\n // defers idle reclaim while work is in flight; this bounds that deferral so a\n // wedged / never-ending background task (a hung build, a long-lived dev server)\n // can't pin an otherwise-idle host forever. Past this, the sweep force-reclaims\n // even with live background work (logged at warn). Must exceed agentIdleTimeoutMs\n // to have any effect. 6h.\n agentMaxLifetimeMs: z.number().int().default(21_600_000),\n // How often the idle sweep runs: reaps idle ACP adapter children back to\n // `provisioned` (§7.2) and TTL-closes idle sessions (§7.3). Keep well below\n // agentIdleTimeoutMs so a host lingers at most one interval past its window.\n idleSweepMs: z.number().int().default(60_000),\n // Quiet window before the sweep removes an agent's materialized config-file\n // secrets (agents/config-file-env.ts) — much shorter than the host TTL: the\n // files are re-written before the next turn is dispatched, so a warm host\n // stays fully usable and this only bounds how long the secret material\n // rests on disk while no turn or background task is running.\n configFilesIdleMs: z.number().int().default(60_000),\n // SIGTERM/daemon-drain grace window: in-flight turns get this long to finish\n // before the daemon cancels stragglers and tears children down (§2.5/§5.3).\n shutdownDrainMs: z.number().int().default(25_000),\n // §7.3 force-cancel backstop: after `!stop` we send session/cancel and wait\n // this long; if the turn still hasn't yielded, we force-stop the host.\n cancelBackstopMs: z.number().int().default(30_000),\n // How many times to (re)try launching an agent's ACP host — spawn + the\n // `initialize` handshake — before giving up and surfacing the failure to the\n // session. Covers transient failures (a resource race, a slow cold start). A\n // deterministic failure (missing binary) just burns all attempts then reports.\n agentStartAttempts: z.number().int().min(1).default(3),\n // Fixed backoff between agent-start attempts.\n agentStartBackoffMs: z.number().int().min(0).default(500),\n // Cap (bytes) for inlining an inbound attachment into the ACP prompt.\n // Files larger than this are passed as a resource_link pointer, never\n // downloaded/base64'd — bounds daemon RSS and the prompt frame size.\n maxAttachmentBytes: z\n .number()\n .int()\n .default(8 * 1024 * 1024)\n })\n .default({\n maxAgents: 32,\n maxConcurrentSessions: 32,\n agentIdleTimeoutMs: 900_000,\n agentMaxLifetimeMs: 21_600_000,\n idleSweepMs: 60_000,\n configFilesIdleMs: 60_000,\n shutdownDrainMs: 25_000,\n cancelBackstopMs: 30_000,\n agentStartAttempts: 3,\n agentStartBackoffMs: 500,\n maxAttachmentBytes: 8 * 1024 * 1024\n })\n})\nexport type Config = z.infer<typeof ConfigSchema>\n","import { chmodSync, readFileSync, existsSync, writeFileSync, mkdirSync, statSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { RelayRosterEntry } from '@agentconnect.md/protocol'\nimport { ConfigSchema, type Config } from './config-schema.js'\nimport { resolveRoot, configPath, defaultAgentsDir } from '../paths.js'\n\nexport interface FlatOverrides {\n apiUrl?: string\n apiKey?: string\n noCp?: boolean\n daemonId?: string\n logLevel?: Config['logging']['level']\n agentsDir?: string\n maxAgents?: number\n requireSandbox?: boolean\n}\n\nfunction protectConfigFile(file: string, writable = false): void {\n if (!existsSync(file)) return\n try {\n const current = statSync(file).mode & 0o777\n const desired = writable ? 0o600 : current & 0o700\n if (current !== desired) chmodSync(file, desired)\n } catch (err) {\n // Windows does not provide enforceable POSIX mode semantics. On POSIX,\n // never keep using a secret-bearing config if owner-only access cannot be\n // established.\n if (process.platform !== 'win32') throw err\n }\n}\n\nfunction writeConfigFile(file: string, raw: unknown): void {\n // `mode` protects new paths; chmod also repairs a legacy file created under a\n // loose umask. Do not chmod an existing custom parent directory.\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 })\n protectConfigFile(file, true)\n writeFileSync(file, JSON.stringify(raw, null, 2) + '\\n', { encoding: 'utf8', mode: 0o600 })\n protectConfigFile(file, true)\n}\n\nexport function loadConfig(\n opts: { root?: string; configPath?: string; overrides?: FlatOverrides; optional?: boolean; autoCreate?: boolean } = {}\n): Config {\n const root = resolveRoot(opts.root)\n const file = opts.configPath ?? configPath(root)\n // `optional` (used by `chat`) lets the daemon run with zero config: a missing\n // config.json yields the schema defaults, and runtimes fall back to the ACP registry.\n // `autoCreate` (used by `run`) goes a step further and writes that empty config to\n // disk so the daemon runs fully local (control plane disabled by default) and the\n // user has a file to edit later — no `agentconnect login` required.\n let raw: unknown\n if (existsSync(file)) {\n protectConfigFile(file)\n raw = JSON.parse(readFileSync(file, 'utf8'))\n } else if (opts.autoCreate) {\n raw = { version: 1 }\n writeConfigFile(file, raw)\n } else if (opts.optional) {\n raw = { version: 1 }\n } else {\n throw new Error(`config not found: ${file} (create it, pass --config, or run \\`agentconnect login\\`)`)\n }\n const cfg = ConfigSchema.parse(raw) // throws on invalid\n\n const o = opts.overrides ?? {}\n if (o.daemonId) cfg.daemonId = o.daemonId\n if (o.logLevel) cfg.logging.level = o.logLevel\n if (o.maxAgents !== undefined) cfg.limits.maxAgents = o.maxAgents\n if (o.requireSandbox) cfg.security.requireSandbox = true\n if (o.apiUrl) cfg.controlPlane.url = o.apiUrl\n if (o.apiKey) cfg.controlPlane.key = o.apiKey\n // Passing --api-url/--api-key implies \"connect to the CP\" (it defaults off),\n // so the one-line onboarding command works without a config edit. --no-cp wins.\n if (o.apiUrl || o.apiKey) cfg.controlPlane.enabled = true\n if (o.noCp) cfg.controlPlane.enabled = false\n\n cfg.agentsDir = o.agentsDir ?? cfg.agentsDir ?? defaultAgentsDir(root)\n return cfg\n}\n\n/**\n * Persist a (freshly-minted) `daemonId` back into config.json so it is stable\n * per install. Best-effort: a write failure is swallowed (the daemon still runs\n * with the in-memory id this session).\n */\nexport function persistDaemonId(root: string | undefined, daemonId: string, customConfigPath?: string): void {\n try {\n const file = customConfigPath ?? configPath(resolveRoot(root))\n protectConfigFile(file)\n const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n raw.daemonId = daemonId\n writeConfigFile(file, raw)\n } catch {\n // ignore — non-fatal\n }\n}\n\n/**\n * Persist the CP-published relay roster back into config.json so the daemon can\n * re-dial its relays at boot while the CP is unreachable (graceful degradation).\n * Whole-set (CP-owned): overwrites any prior value, so a swept relay is cleared.\n * Best-effort — a write failure is swallowed (the in-memory roster still drives\n * this session's dials).\n */\nexport function persistRelays(root: string | undefined, relays: RelayRosterEntry[], customConfigPath?: string): void {\n try {\n const file = customConfigPath ?? configPath(resolveRoot(root))\n protectConfigFile(file)\n const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n raw.relays = relays\n writeConfigFile(file, raw)\n } catch {\n // ignore — non-fatal\n }\n}\n","import { z } from 'zod'\nimport { AgentMemoryBinding, AgentSkillEntry, FeishuRegion, ManagedSkillEntry } from '@agentconnect.md/protocol'\n\nexport const BindMatchSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('mention') }),\n z.object({ kind: z.literal('dm') }),\n z.object({ kind: z.literal('keyword'), value: z.string() }),\n z.object({ kind: z.literal('auto') })\n])\nexport type BindMatch = z.infer<typeof BindMatchSchema>\n\nexport const BindRuleConfigSchema = z.object({\n channel: z.string().optional(), // absent = any channel\n thread: z.string().optional(),\n match: BindMatchSchema\n})\nexport type BindRuleConfig = z.infer<typeof BindRuleConfigSchema>\n\nexport const SlackConfigSchema = z.object({\n // 'direct' (default, and the shape of every pre-shared-bot agent.json): the daemon\n // opens the Socket Mode connection itself. 'shared': the bot's inbound lives on a\n // relay, so the daemon holds xoxb ONLY (send path) and opens no socket — routing is\n // arbitrated in the relay and delivered pre-addressed. See shared-bot-relay.md §7.3.\n mode: z.enum(['direct', 'shared']).default('direct'),\n // Multi-agent opt-in (shared mode only): the bot backs many agents, so the status\n // bar exposes an in-thread \"Switch agent\" control. A non-shareable shared bot routes\n // through the relay the same way but has one agent, so the control is suppressed.\n shareable: z.boolean().default(false),\n botToken: z.string(),\n appToken: z.string().optional(), // direct only (Socket Mode); absent for shared\n appId: z.string().optional(), // public A… app id used for Slack permission-update links\n signingSecret: z.string().optional(),\n botUserId: z.string().optional(), // filled at connect via auth.test if absent; provided by CP for shared\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n // Channels the operator switched OFF. bindRules only ADD reach, so an ungated\n // integration — which reaches every conversation through unscoped defaults — needs\n // this subtractive fence to say \"not here\". A muted channel matches no rule of this\n // integration: no mention, no thread continuity, no control command. A gated\n // integration leaves it empty; its Off is the ABSENCE of a conversation-scoped rule.\n mutedChannels: z.array(z.string()).default([]),\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type SlackConfig = z.infer<typeof SlackConfigSchema>\n\nexport const TelegramConfigSchema = z.object({\n botToken: z.string(), // BotFather \"123456:ABC…\" (single token; no app token / signing secret)\n botUserId: z.string().optional(), // numeric bot id, filled at connect via getMe if absent\n botUsername: z.string().optional(), // @username without the '@', for mention detection; filled via getMe\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see SlackConfigSchema.mutedChannels\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type TelegramConfig = z.infer<typeof TelegramConfigSchema>\n\nexport const DiscordConfigSchema = z.object({\n botToken: z.string(), // Discord Gateway bot token (single token; no app token / signing secret)\n applicationId: z.string().optional(), // public client id for the invite URL (not used to connect)\n botUserId: z.string().optional(), // numeric bot user id, filled at connect via the ready event if absent\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see SlackConfigSchema.mutedChannels\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type DiscordConfig = z.infer<typeof DiscordConfigSchema>\n\nexport const FeishuConfigSchema = z.object({\n // Direct opens the Feishu long connection. Shared is send-only: relay HTTP\n // ingress is delivered pre-addressed while this daemon keeps provider egress.\n mode: z.enum(['direct', 'shared']).default('direct'),\n appId: z.string(), // cli_… app identifier (semi-public); needed for REST and direct WS\n appSecret: z.string(), // app secret (single secret; no app token / signing secret)\n botOpenId: z.string().optional(), // bot's own open_id for mention detection; filled at connect via bot/info if absent\n region: FeishuRegion.default('feishu'), // open-platform gateway: feishu.cn (default) vs larksuite.com\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([]),\n mutedChannels: z.array(z.string()).default([]), // Off channels — see SlackConfigSchema.mutedChannels\n // Conversation gating (resource-visibility.md §14): fail-closed ingress — the CP\n // ships only conversation-scoped bindRules; explicitly-addressed unrouted\n // messages get a one-time notice and DM conversations are reported to the CP.\n gated: z.boolean().default(false)\n})\nexport type FeishuConfig = z.infer<typeof FeishuConfigSchema>\n\nexport const IntegrationSchema = z.discriminatedUnion('platform', [\n z.object({\n id: z.string(),\n // CP-pushed integrations are tagged so a reconnect snapshot can prune a\n // missed integration/remove without touching hand-authored local entries.\n origin: z.literal('cp').optional(),\n platform: z.literal('slack'),\n slack: SlackConfigSchema\n }),\n z.object({\n id: z.string(),\n origin: z.literal('cp').optional(),\n platform: z.literal('telegram'),\n telegram: TelegramConfigSchema\n }),\n z.object({\n id: z.string(),\n origin: z.literal('cp').optional(),\n platform: z.literal('discord'),\n discord: DiscordConfigSchema\n }),\n z.object({\n id: z.string(),\n origin: z.literal('cp').optional(),\n platform: z.literal('feishu'),\n feishu: FeishuConfigSchema\n })\n])\nexport type Integration = z.infer<typeof IntegrationSchema>\n\n/** A scheduled trigger for THIS agent: every `schedule` tick, prompt the agent\n * with `trigger`. `target` is optional output routing — when present the daemon\n * posts the trigger into that channel and the session replies in its thread;\n * absent ⇒ headless fire (no platform output). `origin:\"cp\"` marks CP-pushed\n * entries (written by cron/upsert, pruned by drop.crons); hand-authored entries\n * have no origin and are never touched by the CP. */\nexport const CronDefSchema = z.object({\n id: z.string(),\n schedule: z.string(),\n // CP-owned entries always include an IANA timezone. Hand-authored local\n // entries may omit it to retain daemon-local scheduling.\n timezone: z.string().min(1).optional(),\n // integrationId picks which of the agent's integrations posts the anchor;\n // absent (legacy defs) ⇒ the agent's first integration.\n target: z\n .object({\n platform: z.enum(['slack', 'telegram', 'discord', 'feishu']),\n channel: z.string(),\n integrationId: z.string().optional()\n })\n .optional(),\n trigger: z.string(),\n enabled: z.boolean().default(true),\n origin: z.literal('cp').optional()\n})\nexport type CronDef = z.infer<typeof CronDefSchema>\n\nexport const AgentSchema = z.object({\n id: z.string(),\n // Added when a CP spec is persisted. Absence continues to mean a genuinely\n // local agent (or a legacy replica, which the CP handles conservatively).\n origin: z.literal('cp').optional(),\n name: z.string(),\n // Optional human-facing bot name. `name` remains the stable agent identifier;\n // the CP may set or clear this field independently via AgentSpec.displayName.\n displayName: z.string().optional(),\n // CP-resolved public avatar URL (its icon endpoint, or a user image URL). Used\n // as the Slack per-message `icon_url` (chat:write.customize), the sibling of\n // displayName→username. Set/cleared by the CP via AgentSpec.iconUrl.\n iconUrl: z.string().optional(),\n status: z.enum(['active', 'inactive', 'paused']).default('active'),\n // Operational message-processing toggle, orthogonal to `status` (which gates\n // whether the agent is loaded/placed at all). When true the agent still loads and\n // connects its platform bot, but the daemon skips ALL turn dispatch (platform,\n // webchat, cron) — see Daemon.dispatch. Turning it on also cancels in-flight\n // turns and drops their queued follow-ups (including their durable inbox rows, so\n // restart cannot resurrect them), without tearing down the warm host or ACP sessions.\n // Silent: skipped turns are dropped, not recorded. A flip remains\n // a soft-only reconcile change (no host/session teardown).\n pause: z.boolean().default(false),\n runtime: z.string(),\n // System-prompt seed + runtime knobs. Settable in agent.json and overlaid by\n // the CP spec (agent/upsert + register/ok roster) — see cp/cp-agent-registry.ts.\n description: z.string().optional(),\n reasoningEffort: z.string().optional(),\n executionMode: z.string().optional(),\n // Runtime fast mode (ACP `model_config` toggle, claude/codex). Absent ⇒ leave\n // the runtime's own default; the daemon only pushes an explicit on/off.\n fastMode: z.boolean().optional(),\n // Runtime permission/approval mode (ACP `mode` selector). The values are\n // runtime-owned strings: claude-acp uses default/acceptEdits/auto/dontAsk/plan,\n // codex-acp uses read-only/agent/agent-full-access.\n permissionMode: z.string().default('default'),\n // Conversation participants are not authorization principals by default.\n // Editors may explicitly opt this agent back into chat-side runtime setting\n // changes (model, effort, permission mode, fast mode) and approval controls.\n allowRuntimeChangesInChat: z.boolean().default(false),\n runtimeOverrides: z\n .object({\n model: z.string().optional(),\n env: z.array(z.object({ name: z.string(), value: z.string() })).default([]),\n // Write-only secret env vars (CP AgentSpec.secrets). Same {name,value}[] shape as\n // env; merged into the spawned child's environment (secrets win on a key clash).\n secrets: z.array(z.object({ name: z.string(), value: z.string() })).default([])\n })\n .optional(),\n // Names of daemon-configured MCP servers (daemon config `mcpServers`) to attach\n // at ACP session/new|load, after the daemon's own bridge entry. Empty ⇒ none;\n // unknown names are skipped with a warn (see mcp/resolve-servers.ts).\n mcpServers: z.array(z.string()).default([]),\n // Skill sources to install into the workspace via `npx skills` after clone and\n // before the ACP host spawns (design: docs/designs/shared-skills.md). CP-owned,\n // shipped inline on AgentSpec.skills — each entry is self-contained so the daemon\n // needs nothing but agent.json to install. Supersedes the deprecated\n // `workspace.skills` string list below (which is now an unused no-op).\n skills: z.array(AgentSkillEntry).default([]),\n // Centrally accepted immutable `.skill` revisions. Content stays in the\n // daemon-owned cache and is materialized into the workspace before session\n // creation; this metadata is the exact CP-authorized revision set.\n managedSkills: z.array(ManagedSkillEntry).default([]),\n // Agent→agent call authorization (design §2.5), replicated from the CP so the\n // daemon enforces it LOCALLY when another agent uses `messageAgent` to wake this\n // one. `all` (the default) ⇒ any org peer may call; `selected` ⇒ only agents in\n // `allowedCallerAgentIds`. Absent callPolicy ⇒ treated as `all` for backward\n // compatibility with existing agent.json files.\n callPolicy: z.enum(['all', 'selected']).default('all'),\n allowedCallerAgentIds: z.array(z.string()).default([]),\n // Caller-side half of collaboration authorization. Defaults preserve the\n // historical unrestricted behavior for existing agent.json files.\n outboundPolicy: z.enum(['all', 'selected']).default('all'),\n allowedTargetAgentIds: z.array(z.string()).default([]),\n // Opt-in (issue #536): when true, on a GENUINE new channel join the agent\n // proactively introduces itself to the other agents already there (via\n // listAgents → a sendMessage wake) so peers can record it in memory. Default\n // off — the daemon seeds each integration's channel baseline silently, so only\n // channels joined AFTER the baseline (never a restart/re-list) trigger an intro.\n introduceOnJoin: z.boolean().default(false),\n // Request an OS sandbox for this agent (issue #312). Daemon policy may force it\n // on; an unavailable optional sandbox is ineffective. New agents default off.\n restrictFileAccess: z.boolean().default(false),\n // Which memory backend this agent uses (see agents/memory-provider.ts). Absent ⇒\n // managed (the default). External keeps only connection id + bounded policy on\n // disk; endpoint/grant/config live in the daemon-private CP registry.\n memory: AgentMemoryBinding.optional(),\n workspace: z.object({\n mode: z.enum(['git-repo', 'from-scratch']),\n path: z.string(),\n gitRepo: z.string().optional(), // full cloneable address (e.g. https://github.com/acme/infra)\n gitBranch: z.string().default('main'),\n // Repository-relative ACP cwd. Kept lexically lenient here so a historical or\n // hand-authored value cannot break daemon discovery; prepareWorkspace validates it.\n agentDir: z.string().optional(),\n // Remote-git credential mode. Absent ⇒ anonymous (public repos). 'github-app' ⇒\n // clone/fetch/push authenticate via the local credential helper backed by\n // CP-minted short-lived installation tokens — nothing durable on this host.\n gitCredential: z.enum(['github-app']).optional(),\n pullOnNewSession: z.boolean().default(true),\n // DEPRECATED: superseded by the top-level `skills` field (AgentSkillEntry[]).\n // Kept so historical agent.json files still parse; nothing consumes it.\n skills: z.array(z.string()).default([])\n }),\n integrations: z.array(IntegrationSchema).default([]),\n // zod 4: nested .default({}) does not apply inner field defaults — use explicit full literal\n output: z\n .object({\n mode: z.enum(['none', 'minimal', 'low', 'medium', 'high']).default('low'),\n showFooter: z.boolean().default(true)\n })\n .default({ mode: 'low', showFooter: true }),\n permissions: z\n .object({ policy: z.enum(['ask', 'auto']).default('ask'), autoApprove: z.array(z.string()).default([]) })\n .default({ policy: 'ask', autoApprove: [] }),\n crons: z.array(CronDefSchema).default([])\n})\nexport type Agent = z.infer<typeof AgentSchema>\n","import { chmodSync, existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\nconst PRIVATE_DIR_MODE = 0o700\nconst PRIVATE_FILE_MODE = 0o600\n\nfunction chmodIfNeeded(path: string, target: number | ((current: number) => number)): void {\n try {\n const current = statSync(path).mode & 0o777\n const mode = typeof target === 'function' ? target(current) : target\n if (current !== mode) chmodSync(path, mode)\n } catch (err) {\n if (process.platform !== 'win32') throw err\n }\n}\n\nexport function ensurePrivateAgentDirectory(path: string): void {\n mkdirSync(path, { recursive: true, mode: PRIVATE_DIR_MODE })\n chmodIfNeeded(path, PRIVATE_DIR_MODE)\n}\n\n/** Tighten a hand-authored or legacy agent.json before reading its secrets. */\nexport function protectAgentJson(file: string, writable = false): void {\n if (!existsSync(file)) return\n chmodIfNeeded(file, (current) => (writable ? PRIVATE_FILE_MODE : current & 0o700))\n}\n\n/** Preserve the existing inode/symlink while enforcing owner-only access. */\nexport function writeAgentJson(file: string, contents: string): void {\n if (!existsSync(file)) ensurePrivateAgentDirectory(dirname(file))\n protectAgentJson(file, true)\n writeFileSync(file, contents, { encoding: 'utf8', mode: PRIVATE_FILE_MODE })\n protectAgentJson(file, true)\n}\n","import { readFileSync, readdirSync, existsSync } from 'node:fs'\nimport { join, resolve, isAbsolute, dirname } from 'node:path'\nimport { AgentSchema, type Agent } from './agent-schema.js'\nimport { protectAgentJson } from './agent-json-file.js'\n\nconst IGNORED_DIRS = new Set(['node_modules', '.git'])\nconst MAX_DEPTH = 4\nconst DETACHED_DIR = '.detached'\n\n// Agent plus loader-derived data: the directory containing agent.json.\nexport type LoadedAgent = Agent & { dir: string }\n\n// Parse one agent.json, then resolve workspace.path relative to the agent dir.\nfunction parseAgentFile(file: string): LoadedAgent {\n protectAgentJson(file)\n const dir = dirname(file)\n const agent = AgentSchema.parse(JSON.parse(readFileSync(file, 'utf8')))\n if (!isAbsolute(agent.workspace.path)) {\n agent.workspace.path = resolve(dir, agent.workspace.path)\n }\n return { ...agent, dir }\n}\n\n// Bounded recursive walk: collect every agent.json under `dir`. A directory that\n// contains an agent.json is treated as a leaf (we do not recurse into it), so an\n// agent's own workspace checkout can't masquerade as nested agents.\nexport function findAgentFiles(dir: string, depth = 0): string[] {\n if (depth > MAX_DEPTH || !existsSync(dir)) return []\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return []\n }\n if (entries.some((e) => e.isFile() && e.name === 'agent.json')) {\n return [join(dir, 'agent.json')]\n }\n const out: string[] = []\n for (const entry of entries) {\n if (!entry.isDirectory()) continue\n if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('.')) continue\n out.push(...findAgentFiles(join(dir, entry.name), depth + 1))\n }\n return out\n}\n\nfunction protectDetachedAgentFiles(agentsDir: string): void {\n for (const file of findAgentFiles(join(agentsDir, DETACHED_DIR))) {\n protectAgentJson(file)\n }\n}\n\n// All parsed agents under `agentsDir`, no status filter. `dir` is the directory\n// holding each agent.json.\nexport function discoverAgents(agentsDir: string): { agent: LoadedAgent; dir: string }[] {\n // Hidden cold-move archives are intentionally excluded from discovery, but\n // legacy copies may still contain runtime secrets and must converge too.\n protectDetachedAgentFiles(agentsDir)\n return findAgentFiles(agentsDir).map((file) => {\n try {\n return { agent: parseAgentFile(file), dir: dirname(file) }\n } catch (err) {\n throw new Error(`invalid agent.json at ${file}: ${(err as Error).message}`)\n }\n })\n}\n\n// Active agents only — the daemon's multi-agent path.\nexport function loadAgents(agentsDir: string): LoadedAgent[] {\n return discoverAgents(agentsDir)\n .map((d) => d.agent)\n .filter((a) => a.status === 'active')\n}\n\n// Resolve a single agent from `agentsDir`. With `name`, matches the agent `id`.\n// Without `name`: requires exactly one discovered agent. Used by `chat` and by\n// `run --agent`. Does NOT filter by status.\nexport function selectAgent(agentsDir: string, name?: string): LoadedAgent {\n const agents = discoverAgents(agentsDir).map((d) => d.agent)\n if (name) {\n const match = agents.find((a) => a.id === name)\n if (!match) {\n const available =\n agents\n .map((a) => a.id)\n .sort()\n .join(', ') || '(none)'\n throw new Error(`agent \"${name}\" not found in ${agentsDir}. Available: ${available}`)\n }\n return match\n }\n if (agents.length === 0) throw new Error(`no agent.json found in ${agentsDir}`)\n if (agents.length > 1) {\n const ids = agents\n .map((a) => a.id)\n .sort()\n .join(', ')\n throw new Error(`multiple agents found in ${agentsDir}: ${ids}; use --agent <name> to specify one`)\n }\n return agents[0]!\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,WAAWA,MAAO;CAAC;CAAS;CAAY;CAAW;CAAW;CAAU;CAAQ;AAAO,CAAC;AACrG,MAAa,aAAaC,OAAS;CAC/B,UAAU;CACV,SAASC,OAAS;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