@agentconnect.md/daemon 1.0.0-rc.220 → 1.0.0-rc.222
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{acp-host-CeJJZbtg.js → acp-host-DE2r7uCO.js} +191 -16
- package/dist/acp-host-DE2r7uCO.js.map +1 -0
- package/dist/{agent-list-CoYaBcDx.js → agent-list-BwgY3Xqv.js} +2 -2
- package/dist/{agent-list-CoYaBcDx.js.map → agent-list-BwgY3Xqv.js.map} +1 -1
- package/dist/bridge-DXIVgEzf.js +726 -0
- package/dist/bridge-DXIVgEzf.js.map +1 -0
- package/dist/{chat-Bcpnzw3h.js → chat--hmAp3lB.js} +4 -3
- package/dist/chat--hmAp3lB.js.map +1 -0
- package/dist/index.js +5 -5
- package/dist/{load-agents-nWFFmN5-.js → load-agents-hq5NXMmx.js} +34 -6
- package/dist/load-agents-hq5NXMmx.js.map +1 -0
- package/dist/{login-B99oQNXR.js → login-EVa3UJRh.js} +4 -4
- package/dist/{login-B99oQNXR.js.map → login-EVa3UJRh.js.map} +1 -1
- package/dist/{run-foreground-DLxz75b4.js → run-foreground-B05rDr1z.js} +4101 -211
- package/dist/run-foreground-B05rDr1z.js.map +1 -0
- package/dist/run-foreground-Bcg0RA3e.js +2 -0
- package/dist/{schemas-DujcoO0q.js → schemas-CQkO9hC5.js} +27 -2
- package/dist/schemas-CQkO9hC5.js.map +1 -0
- package/dist/{bridge-DoUrmBw9.js → stdio-CwrB9yrX.js} +41 -727
- package/dist/stdio-CwrB9yrX.js.map +1 -0
- package/package.json +1 -1
- package/dist/acp-host-CeJJZbtg.js.map +0 -1
- package/dist/bridge-DoUrmBw9.js.map +0 -1
- package/dist/chat-Bcpnzw3h.js.map +0 -1
- package/dist/ipc-2Xbxe7uu.js +0 -35
- package/dist/ipc-2Xbxe7uu.js.map +0 -1
- package/dist/load-agents-nWFFmN5-.js.map +0 -1
- package/dist/run-foreground-DLxz75b4.js.map +0 -1
- package/dist/run-foreground-PidBMaVD.js +0 -2
- package/dist/schemas-DujcoO0q.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bridge-DXIVgEzf.js","names":["method","process"],"sources":["../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js","../src/mcp/bridge.ts"],"sourcesContent":["/**\n * Experimental server task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CreateMessageResultSchema, ElicitResultSchema } from '../../types.js';\n/**\n * Experimental task features for low-level MCP servers.\n *\n * Access via `server.experimental.tasks`:\n * ```typescript\n * const stream = server.experimental.tasks.requestStream(request, schema, options);\n * ```\n *\n * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead.\n *\n * @experimental\n */\nexport class ExperimentalServerTasks {\n constructor(_server) {\n this._server = _server;\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._server.requestStream(request, resultSchema, options);\n }\n /**\n * Sends a sampling request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages\n * before the final result.\n *\n * @example\n * ```typescript\n * const stream = server.experimental.tasks.createMessageStream({\n * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],\n * maxTokens: 100\n * }, {\n * onprogress: (progress) => {\n * // Handle streaming tokens via progress notifications\n * console.log('Progress:', progress.message);\n * }\n * });\n *\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - The sampling request parameters\n * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n createMessageStream(params, options) {\n // Access client capabilities via the server\n const clientCapabilities = this._server.getClientCapabilities();\n // Capability check - only required when tools/toolChoice are provided\n if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {\n throw new Error('Client does not support sampling tools capability.');\n }\n // Message structure validation - always validate tool_use/tool_result pairs.\n // These may appear even without tools/toolChoice in the current request when\n // a previous sampling request returned tool_use and this is a follow-up with results.\n if (params.messages.length > 0) {\n const lastMessage = params.messages[params.messages.length - 1];\n const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;\n const previousContent = previousMessage\n ? Array.isArray(previousMessage.content)\n ? previousMessage.content\n : [previousMessage.content]\n : [];\n const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');\n if (hasToolResults) {\n if (lastContent.some(c => c.type !== 'tool_result')) {\n throw new Error('The last message must contain only tool_result content if any is present');\n }\n if (!hasPreviousToolUse) {\n throw new Error('tool_result blocks are not matching any tool_use from the previous message');\n }\n }\n if (hasPreviousToolUse) {\n // Extract tool_use IDs from previous message and tool_result IDs from current message\n const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));\n const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));\n if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');\n }\n }\n }\n return this.requestStream({\n method: 'sampling/createMessage',\n params\n }, CreateMessageResultSchema, options);\n }\n /**\n * Sends an elicitation request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'\n * and 'taskStatus' messages before the final result.\n *\n * @example\n * ```typescript\n * const stream = server.experimental.tasks.elicitInputStream({\n * mode: 'url',\n * message: 'Please authenticate',\n * elicitationId: 'auth-123',\n * url: 'https://example.com/auth'\n * }, {\n * task: { ttl: 300000 } // Task-augmented for long-running auth flow\n * });\n *\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('User action:', message.result.action);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - The elicitation request parameters\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n elicitInputStream(params, options) {\n // Access client capabilities via the server\n const clientCapabilities = this._server.getClientCapabilities();\n const mode = params.mode ?? 'form';\n // Capability check based on mode\n switch (mode) {\n case 'url': {\n if (!clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support url elicitation.');\n }\n break;\n }\n case 'form': {\n if (!clientCapabilities?.elicitation?.form) {\n throw new Error('Client does not support form elicitation.');\n }\n break;\n }\n }\n // Normalize params to ensure mode is set for form mode (defaults to 'form' per spec)\n const normalizedParams = mode === 'form' && params.mode === undefined ? { ...params, mode: 'form' } : params;\n // Cast to ServerRequest needed because TypeScript can't narrow the union type\n // based on the discriminated 'method' field when constructing the object literal\n return this.requestStream({\n method: 'elicitation/create',\n params: normalizedParams\n }, ElicitResultSchema, options);\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._server.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n return this._server.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n return this._server.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n return this._server.cancelTask({ taskId }, options);\n }\n}\n//# sourceMappingURL=server.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from './zod-compat.js';\nimport { ExperimentalServerTasks } from '../experimental/tasks/server.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * An MCP server on top of a pluggable transport.\n *\n * This server will automatically respond to the initialization flow as initiated from the client.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed server\n * const server = new Server<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomServer\",\n * version: \"1.0.0\"\n * })\n * ```\n * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.\n */\nexport class Server extends Protocol {\n /**\n * Initializes this server with the given name and version information.\n */\n constructor(_serverInfo, options) {\n super(options);\n this._serverInfo = _serverInfo;\n // Map log levels by session id\n this._loggingLevels = new Map();\n // Map LogLevelSchema to severity index\n this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));\n // Is a message with the given level ignored in the log level set for the given session id?\n this.isMessageIgnored = (level, sessionId) => {\n const currentLevel = this._loggingLevels.get(sessionId);\n return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;\n };\n this._capabilities = options?.capabilities ?? {};\n this._instructions = options?.instructions;\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request));\n this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());\n if (this._capabilities.logging) {\n this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {\n const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined;\n const { level } = request.params;\n const parseResult = LoggingLevelSchema.safeParse(level);\n if (parseResult.success) {\n this._loggingLevels.set(transportSessionId, parseResult.data);\n }\n return {};\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalServerTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce server-side validation for tools/call.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value using type-safe property access\n let methodValue;\n if (isZ4Schema(methodSchema)) {\n const v4Schema = methodSchema;\n const v4Def = v4Schema._zod?.def;\n methodValue = v4Def?.value ?? v4Schema.value;\n }\n else {\n const v3Schema = methodSchema;\n const legacyDef = v3Schema._def;\n methodValue = legacyDef?.value ?? v3Schema.value;\n }\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'tools/call') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CallToolRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against CallToolResultSchema\n const validationResult = safeParse(CallToolResultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'sampling/createMessage':\n if (!this._clientCapabilities?.sampling) {\n throw new Error(`Client does not support sampling (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._clientCapabilities?.elicitation) {\n throw new Error(`Client does not support elicitation (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._clientCapabilities?.roots) {\n throw new Error(`Client does not support listing roots (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/message':\n if (!this._capabilities.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'notifications/resources/updated':\n case 'notifications/resources/list_changed':\n if (!this._capabilities.resources) {\n throw new Error(`Server does not support notifying about resources (required for ${method})`);\n }\n break;\n case 'notifications/tools/list_changed':\n if (!this._capabilities.tools) {\n throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);\n }\n break;\n case 'notifications/prompts/list_changed':\n if (!this._capabilities.prompts) {\n throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);\n }\n break;\n case 'notifications/elicitation/complete':\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error(`Client does not support URL elicitation (required for ${method})`);\n }\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'completion/complete':\n if (!this._capabilities.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'logging/setLevel':\n if (!this._capabilities.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._capabilities.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n if (!this._capabilities.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._capabilities.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Server does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n case 'initialize':\n // No specific capability required for these methods\n break;\n }\n }\n assertTaskCapability(method) {\n assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server');\n }\n async _oninitialize(request) {\n const requestedVersion = request.params.protocolVersion;\n this._clientCapabilities = request.params.capabilities;\n this._clientVersion = request.params.clientInfo;\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;\n return {\n protocolVersion,\n capabilities: this.getCapabilities(),\n serverInfo: this._serverInfo,\n ...(this._instructions && { instructions: this._instructions })\n };\n }\n /**\n * After initialization has completed, this will be populated with the client's reported capabilities.\n */\n getClientCapabilities() {\n return this._clientCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the client's name and version.\n */\n getClientVersion() {\n return this._clientVersion;\n }\n getCapabilities() {\n return this._capabilities;\n }\n async ping() {\n return this.request({ method: 'ping' }, EmptyResultSchema);\n }\n // Implementation\n async createMessage(params, options) {\n // Capability check - only required when tools/toolChoice are provided\n if (params.tools || params.toolChoice) {\n if (!this._clientCapabilities?.sampling?.tools) {\n throw new Error('Client does not support sampling tools capability.');\n }\n }\n // Message structure validation - always validate tool_use/tool_result pairs.\n // These may appear even without tools/toolChoice in the current request when\n // a previous sampling request returned tool_use and this is a follow-up with results.\n if (params.messages.length > 0) {\n const lastMessage = params.messages[params.messages.length - 1];\n const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;\n const previousContent = previousMessage\n ? Array.isArray(previousMessage.content)\n ? previousMessage.content\n : [previousMessage.content]\n : [];\n const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');\n if (hasToolResults) {\n if (lastContent.some(c => c.type !== 'tool_result')) {\n throw new Error('The last message must contain only tool_result content if any is present');\n }\n if (!hasPreviousToolUse) {\n throw new Error('tool_result blocks are not matching any tool_use from the previous message');\n }\n }\n if (hasPreviousToolUse) {\n const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));\n const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));\n if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');\n }\n }\n }\n // Use different schemas based on whether tools are provided\n if (params.tools) {\n return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options);\n }\n return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options);\n }\n /**\n * Creates an elicitation request for the given parameters.\n * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.\n * @param params The parameters for the elicitation request.\n * @param options Optional request options.\n * @returns The result of the elicitation request.\n */\n async elicitInput(params, options) {\n const mode = (params.mode ?? 'form');\n switch (mode) {\n case 'url': {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support url elicitation.');\n }\n const urlParams = params;\n return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options);\n }\n case 'form': {\n if (!this._clientCapabilities?.elicitation?.form) {\n throw new Error('Client does not support form elicitation.');\n }\n const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' };\n const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options);\n if (result.action === 'accept' && result.content && formParams.requestedSchema) {\n try {\n const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);\n const validationResult = validator(result.content);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return result;\n }\n }\n }\n /**\n * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`\n * notification for the specified elicitation ID.\n *\n * @param elicitationId The ID of the elicitation to mark as complete.\n * @param options Optional notification options. Useful when the completion notification should be related to a prior request.\n * @returns A function that emits the completion notification when awaited.\n */\n createElicitationCompletionNotifier(elicitationId, options) {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)');\n }\n return () => this.notification({\n method: 'notifications/elicitation/complete',\n params: {\n elicitationId\n }\n }, options);\n }\n async listRoots(params, options) {\n return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options);\n }\n /**\n * Sends a logging message to the client, if connected.\n * Note: You only need to send the parameters object, not the entire JSON RPC message\n * @see LoggingMessageNotification\n * @param params\n * @param sessionId optional for stateless and backward compatibility\n */\n async sendLoggingMessage(params, sessionId) {\n if (this._capabilities.logging) {\n if (!this.isMessageIgnored(params.level, sessionId)) {\n return this.notification({ method: 'notifications/message', params });\n }\n }\n }\n async sendResourceUpdated(params) {\n return this.notification({\n method: 'notifications/resources/updated',\n params\n });\n }\n async sendResourceListChanged() {\n return this.notification({\n method: 'notifications/resources/list_changed'\n });\n }\n async sendToolListChanged() {\n return this.notification({ method: 'notifications/tools/list_changed' });\n }\n async sendPromptListChanged() {\n return this.notification({ method: 'notifications/prompts/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","import process from 'node:process';\nimport { ReadBuffer, serializeMessage } from '../shared/stdio.js';\n/**\n * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout.\n *\n * This transport is only available in Node.js environments.\n */\nexport class StdioServerTransport {\n constructor(_stdin = process.stdin, _stdout = process.stdout) {\n this._stdin = _stdin;\n this._stdout = _stdout;\n this._readBuffer = new ReadBuffer();\n this._started = false;\n // Arrow functions to bind `this` properly, while maintaining function identity.\n this._ondata = (chunk) => {\n this._readBuffer.append(chunk);\n this.processReadBuffer();\n };\n this._onerror = (error) => {\n this.onerror?.(error);\n };\n }\n /**\n * Starts listening for messages on stdin.\n */\n async start() {\n if (this._started) {\n throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.');\n }\n this._started = true;\n this._stdin.on('data', this._ondata);\n this._stdin.on('error', this._onerror);\n }\n processReadBuffer() {\n while (true) {\n try {\n const message = this._readBuffer.readMessage();\n if (message === null) {\n break;\n }\n this.onmessage?.(message);\n }\n catch (error) {\n this.onerror?.(error);\n }\n }\n }\n async close() {\n // Remove our event listeners first\n this._stdin.off('data', this._ondata);\n this._stdin.off('error', this._onerror);\n // Check if we were the only data listener\n const remainingDataListeners = this._stdin.listenerCount('data');\n if (remainingDataListeners === 0) {\n // Only pause stdin if we were the only listener\n // This prevents interfering with other parts of the application that might be using stdin\n this._stdin.pause();\n }\n // Clear the buffer and notify closure\n this._readBuffer.clear();\n this.onclose?.();\n }\n send(message) {\n return new Promise(resolve => {\n const json = serializeMessage(message);\n if (this._stdout.write(json)) {\n resolve();\n }\n else {\n this._stdout.once('drain', resolve);\n }\n });\n }\n}\n//# sourceMappingURL=stdio.js.map","import net from 'node:net'\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'\nimport { decodeFrames, encodeFrame, type IpcListToolsResult, type IpcResponse } from './ipc.js'\nimport { DAEMON_VERSION } from '../version.js'\n\ntype IpcCall = { op: 'listTools' } | { op: 'callTool'; name: string; args: Record<string, unknown> }\n\n/**\n * IPC client half of the bridge: a persistent UDS connection to the daemon's\n * control server. Requests are correlated by an incrementing id; an `ok:false`\n * response rejects with the daemon's error message.\n */\nclass IpcClient {\n private socket: net.Socket\n private nextId = 1\n private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>()\n private buf = ''\n private ready: Promise<void>\n\n constructor(\n endpoint: string,\n private token: string\n ) {\n this.socket = net.connect(endpoint)\n this.socket.setEncoding('utf8')\n this.ready = new Promise((resolve, reject) => {\n this.socket.once('connect', resolve)\n this.socket.once('error', reject)\n })\n this.socket.on('data', (chunk: string) => {\n this.buf += chunk\n const { messages, rest } = decodeFrames<IpcResponse>(this.buf)\n this.buf = rest\n for (const res of messages) {\n const p = this.pending.get(res.id)\n if (!p) continue\n this.pending.delete(res.id)\n if (res.ok) p.resolve(res.result)\n else p.reject(new Error(res.error ?? 'tool call failed'))\n }\n })\n this.socket.on('close', () => {\n for (const p of this.pending.values()) p.reject(new Error('daemon connection closed'))\n this.pending.clear()\n })\n }\n\n async request(call: IpcCall): Promise<unknown> {\n await this.ready\n const id = this.nextId++\n return new Promise<unknown>((resolve, reject) => {\n this.pending.set(id, { resolve, reject })\n this.socket.write(encodeFrame({ id, token: this.token, ...call }))\n })\n }\n}\n\n/**\n * Entry point for `agentconnect mcp-bridge`: a stdio MCP server that relays\n * `tools/list` and `tools/call` to the running daemon over its control socket.\n * The agent harness spawns this per session; the daemon does the real work.\n */\nexport async function runBridge(): Promise<void> {\n const endpoint = process.env.AC_MCP_ENDPOINT\n const token = process.env.AC_MCP_TOKEN\n if (!endpoint || !token) {\n process.stderr.write('mcp-bridge: AC_MCP_ENDPOINT and AC_MCP_TOKEN must be set\\n')\n process.exit(2)\n }\n\n const ipc = new IpcClient(endpoint, token)\n let tools: IpcListToolsResult['tools']\n try {\n const res = (await ipc.request({ op: 'listTools' })) as IpcListToolsResult\n tools = res.tools\n } catch (err) {\n process.stderr.write(`mcp-bridge: could not reach daemon: ${(err as Error).message}\\n`)\n process.exit(1)\n }\n\n const server = new Server({ name: 'agentconnect', version: DAEMON_VERSION }, { capabilities: { tools: {} } })\n server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }))\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n try {\n const result = await ipc.request({\n op: 'callTool',\n name: req.params.name,\n args: (req.params.arguments ?? {}) as Record<string, unknown>\n })\n // A tool may return native MCP content (e.g. a viewable image from\n // readSlackFile) via the `mcpContent` marker — pass it through verbatim.\n if (result && typeof result === 'object' && Array.isArray((result as { mcpContent?: unknown }).mcpContent)) {\n return { content: (result as { mcpContent: unknown[] }).mcpContent }\n }\n const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2)\n return { content: [{ type: 'text', text }] }\n } catch (err) {\n return { content: [{ type: 'text', text: (err as Error).message }], isError: true }\n }\n })\n\n await server.connect(new StdioServerTransport())\n}\n"],"x_google_ignoreList":[0,1,2],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,0BAAb,MAAqC;CACjC,YAAY,SAAS;EACjB,KAAK,UAAU;CACnB;;;;;;;;;;;;;;;CAeA,cAAc,SAAS,cAAc,SAAS;EAC1C,OAAO,KAAK,QAAQ,cAAc,SAAS,cAAc,OAAO;CACpE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4CA,oBAAoB,QAAQ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AAQ,CAAC;IAAG,SAAS;GAAK;EACpF;CACF,CAAC;CAED,MAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AACjD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as agentChildEnv, i as selectAgent, o as loadConfig } from "./load-agents-
|
|
1
|
+
import { a as agentChildEnv, i as selectAgent, o as loadConfig } from "./load-agents-hq5NXMmx.js";
|
|
2
2
|
import { l as resolveRoot } from "./paths-DEcUO8lC.js";
|
|
3
|
-
import {
|
|
3
|
+
import { i as prepareWorkspace, t as AcpHost, y as resolveRuntimes } from "./acp-host-DE2r7uCO.js";
|
|
4
4
|
import { createInterface } from "node:readline";
|
|
5
5
|
//#region src/cli/chat.ts
|
|
6
6
|
function renderUpdate(out) {
|
|
@@ -36,6 +36,7 @@ async function runChat(opts) {
|
|
|
36
36
|
env: agentChildEnv(agent),
|
|
37
37
|
configPrefs: {
|
|
38
38
|
model: agent.runtimeOverrides?.model,
|
|
39
|
+
permissionMode: agent.permissionMode,
|
|
39
40
|
reasoningEffort: agent.reasoningEffort,
|
|
40
41
|
fastMode: agent.fastMode
|
|
41
42
|
}
|
|
@@ -75,4 +76,4 @@ async function runChat(opts) {
|
|
|
75
76
|
//#endregion
|
|
76
77
|
export { renderUpdate, runChat };
|
|
77
78
|
|
|
78
|
-
//# sourceMappingURL=chat
|
|
79
|
+
//# sourceMappingURL=chat--hmAp3lB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat--hmAp3lB.js","names":[],"sources":["../src/cli/chat.ts"],"sourcesContent":["import { createInterface } from 'node:readline'\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk'\nimport { loadConfig } from '../config/load-config.js'\nimport { resolveRuntimes } from '../runtimes/registry.js'\nimport { selectAgent } from '../agents/load-agents.js'\nimport { agentChildEnv } from '../agents/agent-env.js'\nimport { prepareWorkspace } from '../workspace/workspace-manager.js'\nimport { AcpHost } from '../acp/acp-host.js'\nimport { resolveRoot } from '../paths.js'\n\nexport function renderUpdate(out: NodeJS.WritableStream) {\n return (_sessionId: string, update: SessionUpdate): void => {\n if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {\n out.write(update.content.text)\n } else if (update.sessionUpdate === 'tool_call') {\n const title = ('title' in update && update.title) || update.toolCallId || 'tool'\n out.write(`\\n[tool] ${title}\\n`)\n }\n }\n}\n\nexport interface RunChatOpts {\n agentsDir?: string\n agentName?: string\n message?: string\n configPath?: string\n root?: string\n out?: NodeJS.WritableStream\n input?: NodeJS.ReadableStream\n}\n\nexport async function runChat(opts: RunChatOpts): Promise<void> {\n const out = opts.out ?? process.stdout\n const root = resolveRoot(opts.root)\n const cfg = loadConfig({\n root: opts.root,\n configPath: opts.configPath,\n optional: true,\n overrides: { agentsDir: opts.agentsDir }\n })\n const agent = selectAgent(cfg.agentsDir!, opts.agentName)\n\n const runtimes = await resolveRuntimes(cfg, root, { neededRuntimes: [agent.runtime], mode: 'cache-first' })\n const runtime = runtimes[agent.runtime]\n if (!runtime) {\n const available = Object.keys(runtimes).sort().join(', ') || '(none)'\n throw new Error(`runtime \"${agent.runtime}\" not found. Available: ${available}`)\n }\n\n const host = new AcpHost(runtime, {\n onUpdate: renderUpdate(out),\n env: agentChildEnv(agent),\n configPrefs: {\n model: agent.runtimeOverrides?.model,\n permissionMode: agent.permissionMode,\n reasoningEffort: agent.reasoningEffort,\n fastMode: agent.fastMode\n }\n })\n await host.start()\n try {\n const cwd = await prepareWorkspace(agent)\n const sessionId = await host.newSession(cwd)\n\n const send = async (text: string) => {\n const blocks: ContentBlock[] = [{ type: 'text', text }]\n await host.prompt(sessionId, blocks)\n out.write('\\n')\n }\n\n if (typeof opts.message === 'string' && opts.message.length > 0) {\n await send(opts.message)\n return\n }\n\n const rl = createInterface({ input: opts.input ?? process.stdin })\n out.write(`Chatting with ${agent.name} (${agent.id}). Type .exit to quit.\\n> `)\n try {\n for await (const line of rl) {\n const text = line.trim()\n if (text === '.exit' || text === '.quit') break\n if (text.length > 0) await send(text)\n out.write('> ')\n }\n } finally {\n rl.close()\n }\n } finally {\n await host.stop()\n }\n}\n"],"mappings":";;;;;AAUA,SAAgB,aAAa,KAA4B;CACvD,QAAQ,YAAoB,WAAgC;EAC1D,IAAI,OAAO,kBAAkB,yBAAyB,OAAO,QAAQ,SAAS,QAC5E,IAAI,MAAM,OAAO,QAAQ,IAAI;OACxB,IAAI,OAAO,kBAAkB,aAAa;GAC/C,MAAM,QAAS,WAAW,UAAU,OAAO,SAAU,OAAO,cAAc;GAC1E,IAAI,MAAM,YAAY,MAAM,GAAG;EACjC;CACF;AACF;AAYA,eAAsB,QAAQ,MAAkC;CAC9D,MAAM,MAAM,KAAK,OAAO,QAAQ;CAChC,MAAM,OAAO,YAAY,KAAK,IAAI;CAClC,MAAM,MAAM,WAAW;EACrB,MAAM,KAAK;EACX,YAAY,KAAK;EACjB,UAAU;EACV,WAAW,EAAE,WAAW,KAAK,UAAU;CACzC,CAAC;CACD,MAAM,QAAQ,YAAY,IAAI,WAAY,KAAK,SAAS;CAExD,MAAM,WAAW,MAAM,gBAAgB,KAAK,MAAM;EAAE,gBAAgB,CAAC,MAAM,OAAO;EAAG,MAAM;CAAc,CAAC;CAC1G,MAAM,UAAU,SAAS,MAAM;CAC/B,IAAI,CAAC,SAAS;EACZ,MAAM,YAAY,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,KAAK;EAC7D,MAAM,IAAI,MAAM,YAAY,MAAM,QAAQ,0BAA0B,WAAW;CACjF;CAEA,MAAM,OAAO,IAAI,QAAQ,SAAS;EAChC,UAAU,aAAa,GAAG;EAC1B,KAAK,cAAc,KAAK;EACxB,aAAa;GACX,OAAO,MAAM,kBAAkB;GAC/B,gBAAgB,MAAM;GACtB,iBAAiB,MAAM;GACvB,UAAU,MAAM;EAClB;CACF,CAAC;CACD,MAAM,KAAK,MAAM;CACjB,IAAI;EACF,MAAM,MAAM,MAAM,iBAAiB,KAAK;EACxC,MAAM,YAAY,MAAM,KAAK,WAAW,GAAG;EAE3C,MAAM,OAAO,OAAO,SAAiB;GACnC,MAAM,SAAyB,CAAC;IAAE,MAAM;IAAQ;GAAK,CAAC;GACtD,MAAM,KAAK,OAAO,WAAW,MAAM;GACnC,IAAI,MAAM,IAAI;EAChB;EAEA,IAAI,OAAO,KAAK,YAAY,YAAY,KAAK,QAAQ,SAAS,GAAG;GAC/D,MAAM,KAAK,KAAK,OAAO;GACvB;EACF;EAEA,MAAM,KAAK,gBAAgB,EAAE,OAAO,KAAK,SAAS,QAAQ,MAAM,CAAC;EACjE,IAAI,MAAM,iBAAiB,MAAM,KAAK,IAAI,MAAM,GAAG,2BAA2B;EAC9E,IAAI;GACF,WAAW,MAAM,QAAQ,IAAI;IAC3B,MAAM,OAAO,KAAK,KAAK;IACvB,IAAI,SAAS,WAAW,SAAS,SAAS;IAC1C,IAAI,KAAK,SAAS,GAAG,MAAM,KAAK,IAAI;IACpC,IAAI,MAAM,IAAI;GAChB;EACF,UAAU;GACR,GAAG,MAAM;EACX;CACF,UAAU;EACR,MAAM,KAAK,KAAK;CAClB;AACF"}
|
package/dist/index.js
CHANGED
|
@@ -68501,9 +68501,9 @@ const telemetry = startDaemonOpenTelemetry({ serviceVersion: DAEMON_VERSION });
|
|
|
68501
68501
|
const [{ Command }, { fileURLToPath: fileURLToPath$1 }, { runChat }, { runLogin }, { runForeground }, { resolveController }, { acquireSingletonLock }, { resolveRoot }] = await Promise.all([
|
|
68502
68502
|
import("./commander-B5QVEFzH.js"),
|
|
68503
68503
|
import("node:url"),
|
|
68504
|
-
import("./chat
|
|
68505
|
-
import("./login-
|
|
68506
|
-
import("./run-foreground-
|
|
68504
|
+
import("./chat--hmAp3lB.js"),
|
|
68505
|
+
import("./login-EVa3UJRh.js"),
|
|
68506
|
+
import("./run-foreground-Bcg0RA3e.js"),
|
|
68507
68507
|
import("./service-6w0WKhdx.js"),
|
|
68508
68508
|
import("./lock-CA9Bm8_s.js"),
|
|
68509
68509
|
import("./paths-CcRUjFjy.js")
|
|
@@ -68552,7 +68552,7 @@ program.command("run").description("Run the daemon in the foreground").action(as
|
|
|
68552
68552
|
}
|
|
68553
68553
|
});
|
|
68554
68554
|
program.command("mcp-bridge", { hidden: true }).description("internal: stdio MCP bridge to the running daemon").action(async () => {
|
|
68555
|
-
const { runBridge } = await import("./bridge-
|
|
68555
|
+
const { runBridge } = await import("./bridge-DXIVgEzf.js");
|
|
68556
68556
|
await runBridge();
|
|
68557
68557
|
});
|
|
68558
68558
|
const controller = () => resolveController({ root: program.opts().root });
|
|
@@ -68661,7 +68661,7 @@ program.command("git-credential").description("Git credential helper backed by t
|
|
|
68661
68661
|
program.command("agent").description("Inspect local agent directories").command("list").description("List agents discovered under --agents-dir (id, status, runtime, name, dir)").action(async () => {
|
|
68662
68662
|
const opts = program.opts();
|
|
68663
68663
|
try {
|
|
68664
|
-
const { runAgentList } = await import("./agent-list-
|
|
68664
|
+
const { runAgentList } = await import("./agent-list-BwgY3Xqv.js");
|
|
68665
68665
|
await runAgentList({
|
|
68666
68666
|
agentsDir: opts.agentsDir,
|
|
68667
68667
|
configPath: opts.config,
|
|
@@ -1,15 +1,40 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as record, a as array, c as discriminatedUnion, d as literal, m as object, n as _enum, o as boolean, p as number, v as string } from "./schemas-CQkO9hC5.js";
|
|
2
2
|
import { l as resolveRoot, r as defaultAgentsDir, t as configPath } from "./paths-DEcUO8lC.js";
|
|
3
3
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
5
5
|
//#region src/config/config-schema.ts
|
|
6
|
+
/** The `{name, value}[]` shape shared by runtime env, MCP env, and MCP headers. */
|
|
7
|
+
const NameValueList = array(object({
|
|
8
|
+
name: string(),
|
|
9
|
+
value: string()
|
|
10
|
+
})).default([]);
|
|
6
11
|
const RuntimeDefSchema = object({
|
|
7
12
|
command: string(),
|
|
8
13
|
args: array(string()).default([]),
|
|
9
|
-
env:
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
14
|
+
env: NameValueList
|
|
15
|
+
});
|
|
16
|
+
const McpServerDefSchema = object({
|
|
17
|
+
transport: _enum([
|
|
18
|
+
"stdio",
|
|
19
|
+
"http",
|
|
20
|
+
"sse"
|
|
21
|
+
]).default("stdio"),
|
|
22
|
+
command: string().optional(),
|
|
23
|
+
args: array(string()).default([]),
|
|
24
|
+
env: NameValueList,
|
|
25
|
+
url: string().optional(),
|
|
26
|
+
headers: NameValueList
|
|
27
|
+
}).superRefine((def, ctx) => {
|
|
28
|
+
if (def.transport === "stdio" && !def.command) ctx.addIssue({
|
|
29
|
+
code: "custom",
|
|
30
|
+
path: ["command"],
|
|
31
|
+
message: "a stdio MCP server requires \"command\""
|
|
32
|
+
});
|
|
33
|
+
if (def.transport !== "stdio" && !def.url) ctx.addIssue({
|
|
34
|
+
code: "custom",
|
|
35
|
+
path: ["url"],
|
|
36
|
+
message: `a ${def.transport} MCP server requires "url"`
|
|
37
|
+
});
|
|
13
38
|
});
|
|
14
39
|
const ConfigSchema = object({
|
|
15
40
|
version: literal(1),
|
|
@@ -26,6 +51,7 @@ const ConfigSchema = object({
|
|
|
26
51
|
}),
|
|
27
52
|
agentsDir: string().optional(),
|
|
28
53
|
runtimes: record(string(), RuntimeDefSchema).optional(),
|
|
54
|
+
mcpServers: record(string(), McpServerDefSchema).optional(),
|
|
29
55
|
logging: object({ level: _enum([
|
|
30
56
|
"trace",
|
|
31
57
|
"debug",
|
|
@@ -154,6 +180,7 @@ const AgentSchema = object({
|
|
|
154
180
|
reasoningEffort: string().optional(),
|
|
155
181
|
executionMode: string().optional(),
|
|
156
182
|
fastMode: boolean().optional(),
|
|
183
|
+
permissionMode: string().default("default"),
|
|
157
184
|
runtimeOverrides: object({
|
|
158
185
|
model: string().optional(),
|
|
159
186
|
env: array(object({
|
|
@@ -161,6 +188,7 @@ const AgentSchema = object({
|
|
|
161
188
|
value: string()
|
|
162
189
|
})).default([])
|
|
163
190
|
}).optional(),
|
|
191
|
+
mcpServers: array(string()).default([]),
|
|
164
192
|
workspace: object({
|
|
165
193
|
mode: _enum(["git-repo", "from-scratch"]),
|
|
166
194
|
path: string(),
|
|
@@ -313,4 +341,4 @@ function selectAgent(agentsDir, name) {
|
|
|
313
341
|
//#endregion
|
|
314
342
|
export { agentChildEnv as a, ConfigSchema as c, selectAgent as i, findAgentFiles as n, loadConfig as o, loadAgents as r, persistDaemonId as s, discoverAgents as t };
|
|
315
343
|
|
|
316
|
-
//# sourceMappingURL=load-agents-
|
|
344
|
+
//# sourceMappingURL=load-agents-hq5NXMmx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-agents-hq5NXMmx.js","names":["z.array","z.object","z.string","z\n .object","z.enum","z.literal","z\n .object","z.boolean","z.number","z.record","z\n .number","z.discriminatedUnion","z.object","z.literal","z.string","z.array","z\n .object","z.boolean","z.enum"],"sources":["../src/config/config-schema.ts","../src/config/load-config.ts","../src/agents/agent-schema.ts","../src/agents/agent-env.ts","../src/agents/load-agents.ts"],"sourcesContent":["import { z } from 'zod'\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})\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 probe snapshot\n// reports 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 // 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\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 (health-probed + reported\n // to the CP as facts; agents opt in by name via their `mcpServers` list).\n mcpServers: z.record(z.string(), McpServerDefSchema).optional(),\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(8),\n maxConcurrentSessions: z.number().int().default(32),\n agentIdleTimeoutMs: z.number().int().default(900_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 // 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: 8,\n maxConcurrentSessions: 32,\n agentIdleTimeoutMs: 900_000,\n idleSweepMs: 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 { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { ConfigSchema, type Config } from './config-schema.js'\nimport { resolveRoot, configPath, defaultAgentsDir } from '../paths.js'\n\nexport interface FlatOverrides {\n cpUrl?: string\n cpKey?: string\n noCp?: boolean\n daemonId?: string\n logLevel?: Config['logging']['level']\n agentsDir?: string\n maxAgents?: number\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 raw = JSON.parse(readFileSync(file, 'utf8'))\n } else if (opts.autoCreate) {\n raw = { version: 1 }\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, JSON.stringify(raw, null, 2) + '\\n')\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.cpUrl) cfg.controlPlane.url = o.cpUrl\n if (o.cpKey) cfg.controlPlane.key = o.cpKey\n // Passing --cp-url/--cp-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.cpUrl || o.cpKey) 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): void {\n try {\n const file = configPath(resolveRoot(root))\n const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n raw.daemonId = daemonId\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, JSON.stringify(raw, null, 2) + '\\n')\n } catch {\n // ignore — non-fatal\n }\n}\n","import { z } from 'zod'\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 botToken: z.string(),\n appToken: z.string(),\n signingSecret: z.string().optional(),\n botUserId: z.string().optional(), // filled at connect via auth.test if absent\n allowedUserIds: z.array(z.string()).default([]),\n bindRules: z.array(BindRuleConfigSchema).default([])\n})\nexport type SlackConfig = z.infer<typeof SlackConfigSchema>\n\nexport const IntegrationSchema = z.object({\n id: z.string(),\n platform: z.literal('slack'),\n slack: SlackConfigSchema\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 // 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({ platform: z.literal('slack'), channel: z.string(), integrationId: z.string().optional() })\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 name: z.string(),\n status: z.enum(['active', 'inactive', 'paused']).default('active'),\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 runtimeOverrides: z\n .object({\n model: z.string().optional(),\n env: 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 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 // 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 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.object({ mode: z.enum(['low', 'medium', 'high']).default('low') }).default({ mode: 'low' }),\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 { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { Agent } from './agent-schema.js'\n\n// Minimal .env parser: KEY=VALUE per line, `#` comments, blank lines,\n// optional `export ` prefix, matching single/double quotes stripped.\n// No variable expansion within the file. Last duplicate key wins.\nexport function parseDotenv(text: string): Record<string, string> {\n const out: Record<string, string> = {}\n for (const rawLine of text.split('\\n')) {\n const line = rawLine.replace(/\\r$/, '').trim()\n if (!line || line.startsWith('#')) continue\n const body = line.startsWith('export ') ? line.slice(7).trim() : line\n const eq = body.indexOf('=')\n if (eq === -1) continue\n const key = body.slice(0, eq).trim()\n if (!key) continue\n let value = body.slice(eq + 1).trim()\n const q = value[0]\n if (value.length >= 2 && (q === '\"' || q === \"'\") && value.at(-1) === q) {\n value = value.slice(1, -1)\n }\n out[key] = value\n }\n return out\n}\n\n// Parse `<dir>/.env`, or {} if the file does not exist.\nexport function loadDotenv(dir: string): Record<string, string> {\n const file = join(dir, '.env')\n if (!existsSync(file)) return {}\n return parseDotenv(readFileSync(file, 'utf8'))\n}\n\nconst VAR_RE = /\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g\n\nfunction interpolateString(\n value: string,\n source: Record<string, string | undefined>,\n path: string,\n ctx: { id: string; envPath: string }\n): string {\n return value.replace(VAR_RE, (_m, name: string) => {\n const resolved = source[name]\n if (resolved === undefined) {\n throw new Error(`agent \"${ctx.id}\": unresolved \\${${name}} in ${path} (.env: ${ctx.envPath})`)\n }\n return resolved\n })\n}\n\nfunction walk(\n node: unknown,\n source: Record<string, string | undefined>,\n path: string,\n ctx: { id: string; envPath: string }\n): unknown {\n if (typeof node === 'string') return interpolateString(node, source, path, ctx)\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i++) node[i] = walk(node[i], source, `${path}[${i}]`, ctx)\n return node\n }\n if (node && typeof node === 'object') {\n const obj = node as Record<string, unknown>\n for (const key of Object.keys(obj)) {\n obj[key] = walk(obj[key], source, path ? `${path}.${key}` : key, ctx)\n }\n return node\n }\n return node\n}\n\n// Rewrite every ${VAR} in every string of `agent` (in place). Throws on the\n// first unresolved variable.\nexport function interpolateAgent(\n agent: Agent,\n source: Record<string, string | undefined>,\n ctx: { id: string; envPath: string }\n): void {\n walk(agent, source, '', ctx)\n}\n\n// Per-agent env overlay applied on top of runtime.env when spawning the ACP\n// child. .env values, then runtimeOverrides.env (which wins).\nexport function agentChildEnv(agent: {\n env: Record<string, string>\n runtimeOverrides?: { env?: { name: string; value: string }[] }\n}): Record<string, string> {\n return {\n ...agent.env,\n ...Object.fromEntries((agent.runtimeOverrides?.env ?? []).map((e) => [e.name, e.value]))\n }\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 { loadDotenv, interpolateAgent } from './agent-env.js'\n\nconst IGNORED_DIRS = new Set(['node_modules', '.git'])\nconst MAX_DEPTH = 4\n\n// Agent plus loader-derived data: its directory and parsed .env.\nexport type LoadedAgent = Agent & { dir: string; env: Record<string, string> }\n\n// Parse one agent.json, interpolate ${VAR} from the sibling .env (+ process.env),\n// then resolve workspace.path relative to the agent dir.\nfunction parseAgentFile(file: string): LoadedAgent {\n const dir = dirname(file)\n const env = loadDotenv(dir)\n const agent = AgentSchema.parse(JSON.parse(readFileSync(file, 'utf8')))\n interpolateAgent(agent, { ...process.env, ...env }, { id: agent.id, envPath: join(dir, '.env') })\n if (!isAbsolute(agent.workspace.path)) {\n agent.workspace.path = resolve(dir, agent.workspace.path)\n }\n return { ...agent, dir, env }\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\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 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":";;;;;;AAGA,MAAM,gBAAgBA,MAAQC,OAAS;CAAE,MAAMC,OAAS;CAAG,OAAOA,OAAS;AAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AAE3F,MAAa,mBAAmBD,OAAS;CACvC,SAASC,OAAS;CAClB,MAAMF,MAAQE,OAAS,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;CACpC,KAAK;AACP,CAAC;AAOD,MAAa,qBAAqBC,OACxB;CACN,WAAWC,MAAO;EAAC;EAAS;EAAQ;CAAK,CAAC,CAAC,CAAC,QAAQ,OAAO;CAE3D,SAASF,OAAS,CAAC,CAAC,SAAS;CAC7B,M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,UAAU,IAAI,IAAI,oCAAoC;CACpG;CACA,OAAO,OAAO;AAChB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as DAEMON_VERSION } from "./version-DGaRXjBK.js";
|
|
2
|
-
import {
|
|
2
|
+
import { n as ClientTransport, t as runForeground } from "./run-foreground-B05rDr1z.js";
|
|
3
|
+
import { c as ConfigSchema } from "./load-agents-hq5NXMmx.js";
|
|
3
4
|
import { l as resolveRoot, t as configPath } from "./paths-DEcUO8lC.js";
|
|
4
|
-
import { f as buildEnvelope, l as isFrame, m as encode, p as decodeEnvelope } from "./acp-host-
|
|
5
|
-
import { n as ClientTransport, t as runForeground } from "./run-foreground-DLxz75b4.js";
|
|
5
|
+
import { f as buildEnvelope, l as isFrame, m as encode, p as decodeEnvelope } from "./acp-host-DE2r7uCO.js";
|
|
6
6
|
import { n as resolveController } from "./service-BQVw7wbz.js";
|
|
7
7
|
import { dirname } from "node:path";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
@@ -226,4 +226,4 @@ async function runLogin(opts, partial = {}) {
|
|
|
226
226
|
//#endregion
|
|
227
227
|
export { buildInstallOpts, persistCredentials, runLogin };
|
|
228
228
|
|
|
229
|
-
//# sourceMappingURL=login-
|
|
229
|
+
//# sourceMappingURL=login-EVa3UJRh.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-B99oQNXR.js","names":["realRunForeground"],"sources":["../src/cp/auth-probe.ts","../src/cli/login.ts"],"sourcesContent":["/**\n * `probeAuth` — a one-shot CP auth check used by `agentconnect login`. It dials\n * the CP, sends ONLY the `auth` frame (no `register`), and resolves with the\n * authoritative daemonId from `auth/ok`, or a human-readable failure reason on\n * a `4401` close, a correlated `error`, a dial failure, or a timeout. It always\n * closes the socket and never leaves a connection open.\n */\nimport { buildEnvelope, decodeEnvelope, encode, isFrame } from '@agentconnect.md/protocol'\nimport { ClientTransport, type Transport } from './transport.js'\n\nexport interface ProbeResult {\n ok: boolean\n daemonId?: string\n reason?: string\n}\n\nexport interface ProbeOpts {\n url: string\n token: string\n daemonId?: string\n agentVersion?: string\n timeoutMs?: number\n /** Injectable for tests; defaults to dialing the real WebSocket. */\n connect?: () => Promise<Transport>\n}\n\nexport async function probeAuth(opts: ProbeOpts): Promise<ProbeResult> {\n const timeoutMs = opts.timeoutMs ?? 10_000\n const dial = opts.connect ?? (() => ClientTransport.dial(opts.url))\n\n let transport: Transport\n try {\n transport = await dial()\n } catch (err) {\n return { ok: false, reason: `cannot reach ${opts.url}: ${(err as Error).message}` }\n }\n\n const authPayload: Record<string, unknown> = {\n apiKey: opts.token,\n agentVersion: opts.agentVersion ?? 'probe'\n }\n if (opts.daemonId) authPayload.daemonId = opts.daemonId\n const frame = buildEnvelope('auth', authPayload)\n\n return await new Promise<ProbeResult>((resolve) => {\n let settled = false\n const done = (r: ProbeResult): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n try {\n transport.close(1000, 'probe done')\n } catch {\n // socket may already be closed\n }\n resolve(r)\n }\n\n const timer = setTimeout(\n () => done({ ok: false, reason: `timed out after ${timeoutMs}ms waiting for auth/ok` }),\n timeoutMs\n )\n\n transport.onMessage((text) => {\n const decoded = decodeEnvelope(text)\n if (!decoded.ok) return\n const f = decoded.frame\n if (f.corr !== frame.id) return\n if (f.type === 'error') {\n const e = f.payload as { code: string; message: string }\n done({ ok: false, reason: `${e.code}: ${e.message}` })\n return\n }\n if (isFrame('auth/ok')(f)) {\n const ok = f.payload as { daemonId: string }\n done({ ok: true, daemonId: ok.daemonId })\n }\n })\n\n transport.onClose((code) => {\n if (code === 4401) done({ ok: false, reason: 'authentication failed (4401) — check the daemon token' })\n else done({ ok: false, reason: `connection closed (${code}) before auth/ok` })\n })\n\n transport.send(encode(frame))\n })\n}\n","/**\n * `agentconnect login` — interactive onboarding. It tests the Control Plane auth\n * flow, persists credentials only on success, then offers to install the OS\n * service. If installed it starts the service (`up`) and returns; otherwise it\n * runs the daemon in the foreground (the same path as `agentconnect run`).\n *\n * `persistCredentials` is the pure config-merge half (token-only onboarding:\n * `daemonId` is omitted unless given — the first connect adopts it from the\n * token's `sub`). `runLogin` is the orchestrator, with injectable deps for tests.\n */\nimport { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { createInterface } from 'node:readline'\nimport { fileURLToPath } from 'node:url'\nimport { ConfigSchema } from '../config/config-schema.js'\nimport { resolveRoot, configPath } from '../paths.js'\nimport { DAEMON_VERSION } from '../version.js'\nimport { probeAuth, type ProbeResult } from '../cp/auth-probe.js'\nimport { resolveController, type InstallOpts } from '../service/index.js'\nimport { runForeground as realRunForeground } from './run-foreground.js'\n\nexport interface PersistCredsOpts {\n cpUrl: string\n cpKey: string\n daemonId?: string\n root?: string\n configPath?: string\n}\n\n/** Merge url/token into config.json (validated), returning the written path. */\nexport function persistCredentials(opts: PersistCredsOpts): string {\n const root = resolveRoot(opts.root)\n const file = opts.configPath ?? configPath(root)\n const raw: Record<string, unknown> = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n\n const cp = (raw.controlPlane as Record<string, unknown> | undefined) ?? {}\n raw.controlPlane = { ...cp, url: opts.cpUrl, key: opts.cpKey, enabled: true }\n if (opts.daemonId) raw.daemonId = opts.daemonId\n\n ConfigSchema.parse(raw) // fail before writing if the merge is invalid\n\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, JSON.stringify(raw, null, 2) + '\\n')\n return file\n}\n\nexport interface RunLoginOpts {\n cpUrl?: string\n cpKey?: string\n daemonId?: string\n root?: string\n configPath?: string\n /** The resolved CLI entry path. Must be supplied by the CLI entry point\n * (index.ts) so the correct bundle path is used rather than inferring it\n * from login.ts's own import.meta.url (which is the same bundle but the\n * `../` path calculation would be wrong). Falls back to import.meta.url\n * for the pure test path where login.ts is loaded standalone. */\n cliEntry?: string\n}\n\n/**\n * Build the InstallOpts for the OS service installer.\n *\n * Exported as a pure helper so it can be unit-tested independently of the\n * full `runLogin` orchestration. The caller (index.ts) passes `cliEntry` so\n * the correct bundle path always flows through; if omitted we fall back to\n * `import.meta.url` (correct only when login.ts is the entry, e.g. in tests).\n */\nexport function buildInstallOpts(opts: { root?: string; cliEntry?: string }): InstallOpts {\n return {\n execPath: process.execPath,\n cliEntry: opts.cliEntry ?? fileURLToPath(import.meta.url),\n includeRootEnv: resolveRoot(opts.root) !== resolveRoot(undefined)\n }\n}\n\nexport interface LoginDeps {\n probe: (o: { url: string; token: string }) => Promise<ProbeResult>\n installService: () => Promise<void>\n runForeground: () => Promise<void>\n out: NodeJS.WritableStream\n input: NodeJS.ReadableStream\n isTTY: boolean\n}\n\nfunction realDeps(opts: RunLoginOpts): LoginDeps {\n return {\n probe: (o) => probeAuth({ url: o.url, token: o.token, agentVersion: DAEMON_VERSION }),\n installService: async () => {\n const controller = resolveController({ root: opts.root })\n await controller.install(buildInstallOpts(opts))\n await controller.up()\n },\n runForeground: () =>\n realRunForeground({\n root: opts.root,\n overrides: { cpUrl: opts.cpUrl, cpKey: opts.cpKey, daemonId: opts.daemonId }\n }),\n out: process.stdout,\n input: process.stdin,\n isTTY: Boolean(process.stdin.isTTY)\n }\n}\n\n/** Read the next line from a readline interface via async iterator. */\nasync function nextLine(\n iter: AsyncIterableIterator<string>,\n prompt: string,\n out: NodeJS.WritableStream\n): Promise<string> {\n out.write(prompt)\n const { value, done } = await iter.next()\n if (done) throw new Error(`unexpected end of input waiting for: ${prompt}`)\n return (value as string).trim()\n}\n\nexport async function runLogin(opts: RunLoginOpts, partial: Partial<LoginDeps> = {}): Promise<void> {\n const deps: LoginDeps = { ...realDeps(opts), ...partial }\n const { out } = deps\n\n // ── Non-interactive: flags required; probe; persist. No prompts, no handoff. ──\n if (!deps.isTTY) {\n if (!opts.cpUrl) throw new Error('login requires --cp-url <url>')\n if (!opts.cpKey) throw new Error('login requires --cp-key <key>')\n const r = await deps.probe({ url: opts.cpUrl, token: opts.cpKey })\n if (!r.ok) throw new Error(`authentication failed: ${r.reason}`)\n persistCredentials({ ...opts, cpUrl: opts.cpUrl, cpKey: opts.cpKey })\n out.write(`✓ authenticated${r.daemonId ? ` (daemon ${r.daemonId})` : ''} — credentials saved\\n`)\n return\n }\n\n // Both interactive handoffs read `<root>/config.json`: the installed service\n // runs `… run` (no `--config`), and the foreground `Daemon` loads by root. A\n // custom `--config` would persist credentials the daemon never reads, so the\n // install/run branch would look successful but start without them. Reject it;\n // `--root` is the knob that keeps persist + service + foreground in sync.\n if (opts.configPath) {\n throw new Error(\n 'interactive login does not support --config — use --root <dir> so the daemon and the installed service read the same config'\n )\n }\n\n // ── Interactive ──\n const rl = createInterface({ input: deps.input, output: out })\n const iter = rl[Symbol.asyncIterator]()\n let url = opts.cpUrl\n let token = opts.cpKey\n try {\n if (!url) url = await nextLine(iter, 'Control Plane URL: ', out)\n\n for (let attempt = 0; ; attempt++) {\n if (!token) token = await nextLine(iter, 'Daemon API key: ', out)\n out.write(`Testing connection to ${url}…\\n`)\n const r = await deps.probe({ url: url!, token: token! })\n if (r.ok) {\n out.write(`✓ authenticated${r.daemonId ? ` (daemon ${r.daemonId})` : ''}\\n`)\n break\n }\n out.write(`✗ ${r.reason}\\n`)\n if (attempt >= 1) throw new Error('authentication failed')\n token = undefined // re-prompt on retry\n }\n\n persistCredentials({ ...opts, cpUrl: url!, cpKey: token! })\n\n const ans = (await nextLine(iter, 'Install AgentConnect as a background service? (y/N) ', out)).toLowerCase()\n if (ans === 'y' || ans === 'yes') {\n await deps.installService()\n out.write('Service installed and started. Manage it with `agentconnect up` / `down` / `status`.\\n')\n return\n }\n out.write('Starting in the foreground (Ctrl-C to stop)…\\n')\n } finally {\n rl.close()\n }\n\n await deps.runForeground()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,eAAsB,UAAU,MAAuC;CACrE,MAAM,YAAY,KAAK,aAAa;CACpC,MAAM,OAAO,KAAK,kBAAkB,gBAAgB,KAAK,KAAK,GAAG;CAEjE,IAAI;CACJ,IAAI;EACF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O,CAAC;GACvD,IAAI,EAAE,IAAI;IACR,IAAI,MAAM,kBAAkB,EAAE,WAAW,YAAY,EAAE,SAAS,KAAK,GAAG,GAAG;IAC3E;GACF;GACA,IAAI,MAAM,KAAK,EAAE,OAAO,GAAG;GAC3B,IAAI,WAAW,GAAG,MAAM,IAAI,MAAM,uBAAuB;GACzD,QAAQ,KAAA;EACV;EAEA,mBAAmB;GAAE,GAAG;GAAM,OAAO;GAAM,OAAO;EAAO,CAAC;EAE1D,MAAM,OAAO,MAAM,SAAS,MAAM,wDAAwD,GAAG,EAAA,CAAG,YAAY;EAC5G,IAAI,QAAQ,OAAO,QAAQ,OAAO;GAChC,MAAM,KAAK,eAAe;GAC1B,IAAI,MAAM,wFAAwF;GAClG;EACF;EACA,IAAI,MAAM,gDAAgD;CAC5D,UAAU;EACR,GAAG,MAAM;CACX;CAEA,MAAM,KAAK,cAAc;AAC3B"}
|
|
1
|
+
{"version":3,"file":"login-EVa3UJRh.js","names":["realRunForeground"],"sources":["../src/cp/auth-probe.ts","../src/cli/login.ts"],"sourcesContent":["/**\n * `probeAuth` — a one-shot CP auth check used by `agentconnect login`. It dials\n * the CP, sends ONLY the `auth` frame (no `register`), and resolves with the\n * authoritative daemonId from `auth/ok`, or a human-readable failure reason on\n * a `4401` close, a correlated `error`, a dial failure, or a timeout. It always\n * closes the socket and never leaves a connection open.\n */\nimport { buildEnvelope, decodeEnvelope, encode, isFrame } from '@agentconnect.md/protocol'\nimport { ClientTransport, type Transport } from './transport.js'\n\nexport interface ProbeResult {\n ok: boolean\n daemonId?: string\n reason?: string\n}\n\nexport interface ProbeOpts {\n url: string\n token: string\n daemonId?: string\n agentVersion?: string\n timeoutMs?: number\n /** Injectable for tests; defaults to dialing the real WebSocket. */\n connect?: () => Promise<Transport>\n}\n\nexport async function probeAuth(opts: ProbeOpts): Promise<ProbeResult> {\n const timeoutMs = opts.timeoutMs ?? 10_000\n const dial = opts.connect ?? (() => ClientTransport.dial(opts.url))\n\n let transport: Transport\n try {\n transport = await dial()\n } catch (err) {\n return { ok: false, reason: `cannot reach ${opts.url}: ${(err as Error).message}` }\n }\n\n const authPayload: Record<string, unknown> = {\n apiKey: opts.token,\n agentVersion: opts.agentVersion ?? 'probe'\n }\n if (opts.daemonId) authPayload.daemonId = opts.daemonId\n const frame = buildEnvelope('auth', authPayload)\n\n return await new Promise<ProbeResult>((resolve) => {\n let settled = false\n const done = (r: ProbeResult): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n try {\n transport.close(1000, 'probe done')\n } catch {\n // socket may already be closed\n }\n resolve(r)\n }\n\n const timer = setTimeout(\n () => done({ ok: false, reason: `timed out after ${timeoutMs}ms waiting for auth/ok` }),\n timeoutMs\n )\n\n transport.onMessage((text) => {\n const decoded = decodeEnvelope(text)\n if (!decoded.ok) return\n const f = decoded.frame\n if (f.corr !== frame.id) return\n if (f.type === 'error') {\n const e = f.payload as { code: string; message: string }\n done({ ok: false, reason: `${e.code}: ${e.message}` })\n return\n }\n if (isFrame('auth/ok')(f)) {\n const ok = f.payload as { daemonId: string }\n done({ ok: true, daemonId: ok.daemonId })\n }\n })\n\n transport.onClose((code) => {\n if (code === 4401) done({ ok: false, reason: 'authentication failed (4401) — check the daemon token' })\n else done({ ok: false, reason: `connection closed (${code}) before auth/ok` })\n })\n\n transport.send(encode(frame))\n })\n}\n","/**\n * `agentconnect login` — interactive onboarding. It tests the Control Plane auth\n * flow, persists credentials only on success, then offers to install the OS\n * service. If installed it starts the service (`up`) and returns; otherwise it\n * runs the daemon in the foreground (the same path as `agentconnect run`).\n *\n * `persistCredentials` is the pure config-merge half (token-only onboarding:\n * `daemonId` is omitted unless given — the first connect adopts it from the\n * token's `sub`). `runLogin` is the orchestrator, with injectable deps for tests.\n */\nimport { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport { createInterface } from 'node:readline'\nimport { fileURLToPath } from 'node:url'\nimport { ConfigSchema } from '../config/config-schema.js'\nimport { resolveRoot, configPath } from '../paths.js'\nimport { DAEMON_VERSION } from '../version.js'\nimport { probeAuth, type ProbeResult } from '../cp/auth-probe.js'\nimport { resolveController, type InstallOpts } from '../service/index.js'\nimport { runForeground as realRunForeground } from './run-foreground.js'\n\nexport interface PersistCredsOpts {\n cpUrl: string\n cpKey: string\n daemonId?: string\n root?: string\n configPath?: string\n}\n\n/** Merge url/token into config.json (validated), returning the written path. */\nexport function persistCredentials(opts: PersistCredsOpts): string {\n const root = resolveRoot(opts.root)\n const file = opts.configPath ?? configPath(root)\n const raw: Record<string, unknown> = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { version: 1 }\n\n const cp = (raw.controlPlane as Record<string, unknown> | undefined) ?? {}\n raw.controlPlane = { ...cp, url: opts.cpUrl, key: opts.cpKey, enabled: true }\n if (opts.daemonId) raw.daemonId = opts.daemonId\n\n ConfigSchema.parse(raw) // fail before writing if the merge is invalid\n\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, JSON.stringify(raw, null, 2) + '\\n')\n return file\n}\n\nexport interface RunLoginOpts {\n cpUrl?: string\n cpKey?: string\n daemonId?: string\n root?: string\n configPath?: string\n /** The resolved CLI entry path. Must be supplied by the CLI entry point\n * (index.ts) so the correct bundle path is used rather than inferring it\n * from login.ts's own import.meta.url (which is the same bundle but the\n * `../` path calculation would be wrong). Falls back to import.meta.url\n * for the pure test path where login.ts is loaded standalone. */\n cliEntry?: string\n}\n\n/**\n * Build the InstallOpts for the OS service installer.\n *\n * Exported as a pure helper so it can be unit-tested independently of the\n * full `runLogin` orchestration. The caller (index.ts) passes `cliEntry` so\n * the correct bundle path always flows through; if omitted we fall back to\n * `import.meta.url` (correct only when login.ts is the entry, e.g. in tests).\n */\nexport function buildInstallOpts(opts: { root?: string; cliEntry?: string }): InstallOpts {\n return {\n execPath: process.execPath,\n cliEntry: opts.cliEntry ?? fileURLToPath(import.meta.url),\n includeRootEnv: resolveRoot(opts.root) !== resolveRoot(undefined)\n }\n}\n\nexport interface LoginDeps {\n probe: (o: { url: string; token: string }) => Promise<ProbeResult>\n installService: () => Promise<void>\n runForeground: () => Promise<void>\n out: NodeJS.WritableStream\n input: NodeJS.ReadableStream\n isTTY: boolean\n}\n\nfunction realDeps(opts: RunLoginOpts): LoginDeps {\n return {\n probe: (o) => probeAuth({ url: o.url, token: o.token, agentVersion: DAEMON_VERSION }),\n installService: async () => {\n const controller = resolveController({ root: opts.root })\n await controller.install(buildInstallOpts(opts))\n await controller.up()\n },\n runForeground: () =>\n realRunForeground({\n root: opts.root,\n overrides: { cpUrl: opts.cpUrl, cpKey: opts.cpKey, daemonId: opts.daemonId }\n }),\n out: process.stdout,\n input: process.stdin,\n isTTY: Boolean(process.stdin.isTTY)\n }\n}\n\n/** Read the next line from a readline interface via async iterator. */\nasync function nextLine(\n iter: AsyncIterableIterator<string>,\n prompt: string,\n out: NodeJS.WritableStream\n): Promise<string> {\n out.write(prompt)\n const { value, done } = await iter.next()\n if (done) throw new Error(`unexpected end of input waiting for: ${prompt}`)\n return (value as string).trim()\n}\n\nexport async function runLogin(opts: RunLoginOpts, partial: Partial<LoginDeps> = {}): Promise<void> {\n const deps: LoginDeps = { ...realDeps(opts), ...partial }\n const { out } = deps\n\n // ── Non-interactive: flags required; probe; persist. No prompts, no handoff. ──\n if (!deps.isTTY) {\n if (!opts.cpUrl) throw new Error('login requires --cp-url <url>')\n if (!opts.cpKey) throw new Error('login requires --cp-key <key>')\n const r = await deps.probe({ url: opts.cpUrl, token: opts.cpKey })\n if (!r.ok) throw new Error(`authentication failed: ${r.reason}`)\n persistCredentials({ ...opts, cpUrl: opts.cpUrl, cpKey: opts.cpKey })\n out.write(`✓ authenticated${r.daemonId ? ` (daemon ${r.daemonId})` : ''} — credentials saved\\n`)\n return\n }\n\n // Both interactive handoffs read `<root>/config.json`: the installed service\n // runs `… run` (no `--config`), and the foreground `Daemon` loads by root. A\n // custom `--config` would persist credentials the daemon never reads, so the\n // install/run branch would look successful but start without them. Reject it;\n // `--root` is the knob that keeps persist + service + foreground in sync.\n if (opts.configPath) {\n throw new Error(\n 'interactive login does not support --config — use --root <dir> so the daemon and the installed service read the same config'\n )\n }\n\n // ── Interactive ──\n const rl = createInterface({ input: deps.input, output: out })\n const iter = rl[Symbol.asyncIterator]()\n let url = opts.cpUrl\n let token = opts.cpKey\n try {\n if (!url) url = await nextLine(iter, 'Control Plane URL: ', out)\n\n for (let attempt = 0; ; attempt++) {\n if (!token) token = await nextLine(iter, 'Daemon API key: ', out)\n out.write(`Testing connection to ${url}…\\n`)\n const r = await deps.probe({ url: url!, token: token! })\n if (r.ok) {\n out.write(`✓ authenticated${r.daemonId ? ` (daemon ${r.daemonId})` : ''}\\n`)\n break\n }\n out.write(`✗ ${r.reason}\\n`)\n if (attempt >= 1) throw new Error('authentication failed')\n token = undefined // re-prompt on retry\n }\n\n persistCredentials({ ...opts, cpUrl: url!, cpKey: token! })\n\n const ans = (await nextLine(iter, 'Install AgentConnect as a background service? (y/N) ', out)).toLowerCase()\n if (ans === 'y' || ans === 'yes') {\n await deps.installService()\n out.write('Service installed and started. Manage it with `agentconnect up` / `down` / `status`.\\n')\n return\n }\n out.write('Starting in the foreground (Ctrl-C to stop)…\\n')\n } finally {\n rl.close()\n }\n\n await deps.runForeground()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,eAAsB,UAAU,MAAuC;CACrE,MAAM,YAAY,KAAK,aAAa;CACpC,MAAM,OAAO,KAAK,kBAAkB,gBAAgB,KAAK,KAAK,GAAG;CAEjE,IAAI;CACJ,IAAI;EACF,YAAY,MAAM,KAAK;CACzB,SAAS,KAAK;EACZ,OAAO;GAAE,IAAI;GAAO,QAAQ,gBAAgB,KAAK,IAAI,IAAK,IAAc;EAAU;CACpF;CAEA,MAAM,cAAuC;EAC3C,QAAQ,KAAK;EACb,cAAc,KAAK,gBAAgB;CACrC;CACA,IAAI,KAAK,UAAU,YAAY,WAAW,KAAK;CAC/C,MAAM,QAAQ,cAAc,QAAQ,WAA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