@conciergeprotocol/server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ # @conciergeprotocol/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run a [Concierge Agent Protocol](https://conciergeprotocol.org) front door. You write one function, `answer`. The package serves `agent.txt`, keeps the thread, hides one caller's reply from another, and enforces the daily message cap.
4
+
5
+ The protocol is at [conciergeprotocol.org](https://conciergeprotocol.org). Publishing a door is described in [Publish a door](https://conciergeprotocol.org/publish).
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @conciergeprotocol/server
11
+ ```
12
+
13
+ Node.js 22 or newer. Messages are stored in SQLite. Set `DATABASE_URL` to a Postgres connection string to use Postgres, and install `pg`.
14
+
15
+ ## Answer
16
+
17
+ `answer` receives the question and returns the reply. A string, or `{ reply }`. Keys, tools, and records stay inside this function. The caller only sees the reply.
18
+
19
+ ```js
20
+ import { createCapServer } from '@conciergeprotocol/server'
21
+
22
+ const cap = await createCapServer({
23
+ agent: { name: 'Harbor Goods', chat: 'https://harborgoods.example/chat' },
24
+ answer: async ({ message, context, history }) => {
25
+ const res = await fetch('https://support.example/api/ask', {
26
+ method: 'POST',
27
+ headers: {
28
+ 'content-type': 'application/json',
29
+ authorization: `Bearer ${process.env.SUPPORT_BOT_KEY}`,
30
+ },
31
+ body: JSON.stringify({ question: message, brief: context, history }),
32
+ })
33
+ if (!res.ok) return { error: { code: 'failed', message: 'The agent could not answer.' } }
34
+ const { text } = await res.json()
35
+ return { reply: text }
36
+ },
37
+ })
38
+
39
+ await cap.listen(8088)
40
+ ```
41
+
42
+ `history` is the earlier turns, oldest first. The caller sends `previous_message_id` and does not resend them. `context` is the optional brief from the visiting agent. `account` and `scope` are null until someone logs in.
43
+
44
+ Return `{ error: { code: 'login_required', message: '...' } }` when the question needs an account. While a message is still running, the caller gets `202` and no reply.
45
+
46
+ The server waits `waitSeconds` (default 20). A longer answer finishes in the background. `dailyLimit` caps messages per caller per UTC day. `0` turns the cap off. Finished messages stay readable for `retentionHours` (default 24).
47
+
48
+ Without `sqlitePath` or `DATABASE_URL`, messages go to `data/cap.sqlite` in the working directory. Pass `sqlitePath: ':memory:'` for a process that keeps nothing.
49
+
50
+ ## The file on the company domain
51
+
52
+ This process can run on any host. The company domain still serves `agent.txt`. Point `CAP` at this server, or rewrite `/cap/v1` to it. Set `publicUrl` when the public origin differs from the request host.
53
+
54
+ ```text
55
+ Protocol: CAP/1.0
56
+ Name: Harbor Goods
57
+ Chat: https://harborgoods.example/chat
58
+ CAP: https://cap.harborgoods.example/cap/v1
59
+ Spec: https://conciergeprotocol.org/cap.txt
60
+ ```
61
+
62
+ Check it:
63
+
64
+ ```sh
65
+ npx cap-check https://cap.harborgoods.example
66
+ ```
67
+
68
+ `cap-check` reads `agent.txt`, asks one question, and confirms a second caller cannot read the reply.
69
+
70
+ ## Next.js
71
+
72
+ `createCapHandler` returns a Fetch handler. Use a durable store (`sqlitePath` on a disk, or `databaseUrl`). A memory store loses an in-flight answer when the function instance stops.
73
+
74
+ ```js
75
+ import { createCapHandler } from '@conciergeprotocol/server'
76
+ import { answer } from './answer.js'
77
+
78
+ const door = await createCapHandler({
79
+ agent: { name: 'Harbor Goods' },
80
+ answer,
81
+ databaseUrl: process.env.DATABASE_URL,
82
+ })
83
+
84
+ export const GET = (request) => door.handle(request)
85
+ export const POST = (request) => door.handle(request)
86
+ export const OPTIONS = (request) => door.handle(request)
87
+ ```
88
+
89
+ Serve `agent.txt` from the company domain. The handler above also serves it at `/agent.txt` on this app.
90
+
91
+ ## Log in
92
+
93
+ Pass `login` to turn on the built-in OAuth server. It adds the `OAuth` line to `agent.txt`. `login` checks the company's own user store and returns an account id, or null.
94
+
95
+ ```js
96
+ const cap = await createCapServer({
97
+ agent: { name: 'Harbor Goods' },
98
+ answer,
99
+ login: async ({ username, password }) => verifyUser(username, password),
100
+ })
101
+ ```
102
+
103
+ With a token, `answer` receives `account` and `scope` (`read` or `write`). A token sent by a different agent is `403`.
104
+
105
+ To hold a change for the person's approval, return `{ confirm: { summary, authorization_details }, reply }` instead of running it. After they approve, the server calls `act` once.
106
+
107
+ ## cap.json
108
+
109
+ `cap-server` reads `cap.json` from the working directory, or `CAP_CONFIG`. The same file the reference server uses:
110
+
111
+ ```json
112
+ {
113
+ "agent": { "name": "Harbor Goods", "chat": "https://harborgoods.example/chat" },
114
+ "handler": { "type": "http", "url": "https://support.example/cap-hook" },
115
+ "daily_limit": 500
116
+ }
117
+ ```
118
+
119
+ `static` returns fixed text. `echo` returns the message. `http` POSTs `{ message, context, history, account, scope }` to a URL and expects `{ "reply": "..." }`. Set `handler.secret_env` to send that environment variable as `X-Cap-Secret`.
120
+
121
+ ```sh
122
+ npx cap-server
123
+ ```
124
+
125
+ The HTTP, storage, and OAuth modules match the reference server in the protocol repository. A spec change belongs in both places.
126
+
127
+ ## License
128
+
129
+ Apache 2.0
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@conciergeprotocol/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Run a Concierge Agent Protocol front door. You write the answer.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "import": "./src/index.js"
10
+ }
11
+ },
12
+ "bin": {
13
+ "cap-server": "./src/cli.js",
14
+ "cap-check": "./src/check.js"
15
+ },
16
+ "files": [
17
+ "src"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "homepage": "https://conciergeprotocol.org",
24
+ "keywords": [
25
+ "concierge",
26
+ "cap",
27
+ "agents",
28
+ "protocol",
29
+ "server"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/conciergeprotocol/js.git",
34
+ "directory": "packages/server"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "optionalDependencies": {
40
+ "pg": "^8.16.0"
41
+ }
42
+ }
package/src/check.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { checkDoor } from './check.mjs'
3
+
4
+ const origin = process.argv[2]
5
+ if (!origin) {
6
+ console.error('Usage: cap-check <origin>')
7
+ process.exit(1)
8
+ }
9
+
10
+ const result = await checkDoor(origin)
11
+ if (result.ok) {
12
+ console.log(`${origin} passes.`)
13
+ } else {
14
+ for (const failure of result.failures) console.error(failure)
15
+ process.exit(1)
16
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,91 @@
1
+ const FROM = 'agent:cap-check'
2
+ const OTHER = 'agent:cap-check-other'
3
+
4
+ /**
5
+ * Four checks a door has to pass: agent.txt, one answered question,
6
+ * and a second caller who cannot read that reply.
7
+ */
8
+ export async function checkDoor(origin, options = {}) {
9
+ const fetchImpl = options.fetch || fetch
10
+ const root = String(origin || '').replace(/\/$/, '')
11
+ const failures = []
12
+ const fail = (message) => failures.push(message)
13
+ if (!root) return { ok: false, failures: ['Pass the door origin, such as http://127.0.0.1:8088.'] }
14
+
15
+ let card = ''
16
+ try {
17
+ const cardRes = await fetchImpl(`${root}/agent.txt`)
18
+ card = await cardRes.text()
19
+ if (cardRes.status !== 200) fail(`agent.txt returned ${cardRes.status}.`)
20
+ } catch (err) {
21
+ fail(`agent.txt could not be fetched: ${err.message}`)
22
+ }
23
+ if (card && !card.startsWith('Protocol: CAP/1.0')) fail('agent.txt must start with Protocol: CAP/1.0.')
24
+ const capLine = card.split('\n').find((line) => line.startsWith('CAP: '))
25
+ const capUrl = capLine ? capLine.slice(5).trim() : ''
26
+ if (capLine && !/^https?:\/\//.test(capUrl)) fail('agent.txt needs an http or https CAP URL.')
27
+ if (card && !capLine) fail('agent.txt needs a CAP line.')
28
+
29
+ const headers = {
30
+ 'content-type': 'application/json',
31
+ 'cap-version': '1.0',
32
+ 'cap-from': FROM,
33
+ }
34
+ const timeoutMs = options.timeoutMs ?? 25_000
35
+ let id = ''
36
+ try {
37
+ const done = await ask(fetchImpl, root, headers, options.message || 'What can you help with?', timeoutMs)
38
+ if (done.body?.status !== 'done' || typeof done.body.reply !== 'string') {
39
+ fail('The question did not finish with a reply.')
40
+ }
41
+ id = done.body?.id || ''
42
+ } catch (err) {
43
+ fail(err.message)
44
+ }
45
+
46
+ if (id) {
47
+ try {
48
+ const other = await fetchImpl(`${root}/cap/v1/messages/${encodeURIComponent(id)}`, {
49
+ headers: { ...headers, 'cap-from': OTHER },
50
+ })
51
+ if (other.status !== 404) fail('A second caller could read the reply.')
52
+ } catch (err) {
53
+ fail(`The second caller check failed: ${err.message}`)
54
+ }
55
+ }
56
+
57
+ return { ok: failures.length === 0, failures }
58
+ }
59
+
60
+ async function ask(fetchImpl, root, headers, message, timeoutMs) {
61
+ let res = await fetchImpl(`${root}/cap/v1/messages`, {
62
+ method: 'POST',
63
+ headers,
64
+ body: JSON.stringify({ message }),
65
+ })
66
+ let body = await readJson(res)
67
+ const deadline = Date.now() + timeoutMs
68
+ while (res.status === 202 || body?.status === 'working') {
69
+ if (Date.now() > deadline) throw new Error('The question was not answered in time.')
70
+ const loc = res.headers.get('location')
71
+ const url = loc
72
+ ? (loc.startsWith('http') ? loc : `${root}${loc.startsWith('/') ? '' : '/'}${loc}`)
73
+ : `${root}/cap/v1/messages/${encodeURIComponent(body?.id || '')}`
74
+ const retryAfter = Number(res.headers.get('retry-after') || 1)
75
+ const wait = Math.min((Number.isFinite(retryAfter) ? retryAfter : 1) * 1000, 2000)
76
+ await new Promise((resolve) => setTimeout(resolve, wait))
77
+ res = await fetchImpl(url, { headers })
78
+ body = await readJson(res)
79
+ }
80
+ return { res, body }
81
+ }
82
+
83
+ async function readJson(res) {
84
+ const text = await res.text()
85
+ if (!text) return null
86
+ try {
87
+ return JSON.parse(text)
88
+ } catch {
89
+ return null
90
+ }
91
+ }
package/src/cli.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { boot } from './config.mjs'
3
+
4
+ const { server } = await boot()
5
+ const port = Number(process.env.PORT || 8088)
6
+ const host = process.env.HOST || '0.0.0.0'
7
+ server.listen(port, host, () => {
8
+ console.log(`CAP server on http://${host}:${port}`)
9
+ })
package/src/config.mjs ADDED
@@ -0,0 +1,111 @@
1
+ import { timingSafeEqual } from 'node:crypto'
2
+ import { readFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { createOAuth } from './oauth.mjs'
5
+ import { createCapServer } from './node-server.mjs'
6
+ import { createStore } from './store.mjs'
7
+
8
+ const HANDLERS = ['static', 'echo', 'http']
9
+
10
+ export function loadConfig(path) {
11
+ const config = JSON.parse(readFileSync(path, 'utf8'))
12
+ if (!config.agent?.name) throw new Error('cap.json needs agent.name.')
13
+ config.agent.status = config.agent.status || 'active'
14
+ const type = config.handler?.type || 'echo'
15
+ if (!HANDLERS.includes(type)) throw new Error(`Unknown handler type: ${type}.`)
16
+ return config
17
+ }
18
+
19
+ async function postHook(handler, payload) {
20
+ const url = handler.url || process.env[handler.url_env || 'HOOK_URL']
21
+ if (!url) return { error: { code: 'failed', message: 'The agent could not answer.' } }
22
+ const secret = process.env[handler.secret_env || 'HOOK_SECRET'] || ''
23
+ const headers = { 'content-type': 'application/json' }
24
+ if (secret) headers['x-cap-secret'] = secret
25
+ const res = await fetch(url, { method: 'POST', headers, body: JSON.stringify(payload) })
26
+ const body = await res.json().catch(() => ({}))
27
+ if (!res.ok || body.error) return { error: body.error || { code: 'failed', message: 'The agent could not answer.' } }
28
+ return body
29
+ }
30
+
31
+ export function handlerAnswer(handler = { type: 'echo' }) {
32
+ const login = { error: { code: 'login_required', message: 'Log in to your account to ask about it.' } }
33
+ return async ({ message, context, history, account, scope }) => {
34
+ if (handler.account && !account) return login
35
+ if (handler.type === 'static') return { reply: String(handler.reply ?? '') }
36
+ if (handler.type === 'echo') return { reply: message }
37
+ const body = await postHook(handler, { message, context, history, account, scope })
38
+ if (body.error) return body
39
+ if (body.confirm) return { confirm: body.confirm, reply: typeof body.reply === 'string' ? body.reply : '' }
40
+ return { reply: typeof body.reply === 'string' ? body.reply : '' }
41
+ }
42
+ }
43
+
44
+ /** With `http`, an approved action goes back to the same hook as `{ confirmed }`. */
45
+ export function handlerAct(handler = { type: 'echo' }) {
46
+ if (handler.type !== 'http') return null
47
+ return async ({ account, authorization_details, caller }) => {
48
+ const body = await postHook(handler, { confirmed: { account, authorization_details, caller } })
49
+ if (body.error) return { error: { message: body.error.message } }
50
+ return { message: typeof body.message === 'string' ? body.message : '' }
51
+ }
52
+ }
53
+
54
+ const sameText = (a, b) => {
55
+ const left = Buffer.from(String(a))
56
+ const right = Buffer.from(String(b))
57
+ return left.length === right.length && timingSafeEqual(left, right)
58
+ }
59
+
60
+ /** Demo logins from cap.json. A real owner passes `boot({ login })` and checks its own user store. */
61
+ export function accountsLogin(accounts = []) {
62
+ return async ({ username, password }) => {
63
+ const match = accounts.find((entry) => entry.account === username)
64
+ const expected = match ? (match.password_env ? process.env[match.password_env] : match.password) : ''
65
+ return match && expected && sameText(password, expected) ? match.account : null
66
+ }
67
+ }
68
+
69
+ export async function boot(options = {}) {
70
+ const configPath = options.configPath || process.env.CAP_CONFIG || join(process.cwd(), 'cap.json')
71
+ const config = options.config || loadConfig(configPath)
72
+ const store = await createStore({
73
+ databaseUrl: options.databaseUrl ?? process.env.DATABASE_URL,
74
+ sqlitePath: options.sqlitePath ?? process.env.SQLITE_PATH ?? join(process.cwd(), 'data', 'cap.sqlite'),
75
+ })
76
+ for (const grant of config.grants || []) {
77
+ if (grant.token && grant.account && grant.client) {
78
+ await store.upsertGrant({ token: grant.token, account: grant.account, clientId: grant.client, scope: grant.scope === 'write' ? 'write' : 'read' })
79
+ }
80
+ }
81
+ const oauthConfig = config.oauth
82
+ const oauth = oauthConfig || options.login
83
+ ? createOAuth({
84
+ store,
85
+ agentName: config.agent.name,
86
+ login: options.login || accountsLogin(oauthConfig?.accounts),
87
+ write: Boolean(oauthConfig?.write),
88
+ act: options.act || handlerAct(config.handler),
89
+ accessTokenSeconds: oauthConfig?.access_token_seconds ?? 3600,
90
+ writeAccessTokenSeconds: oauthConfig?.write_access_token_seconds ?? 900,
91
+ allowHttpClients: Boolean(oauthConfig?.allow_http_clients),
92
+ hint: oauthConfig?.hint || '',
93
+ fetchImpl: options.fetch,
94
+ deviceInterval: oauthConfig?.device_interval ?? 5,
95
+ })
96
+ : null
97
+ const cap = createCapServer({
98
+ store,
99
+ agent: config.agent,
100
+ answer: options.answer || handlerAnswer(config.handler),
101
+ waitMs: options.waitMs ?? (config.wait_seconds ?? 20) * 1000,
102
+ retryAfter: config.retry_after ?? 5,
103
+ retentionHours: config.retention_hours ?? 24,
104
+ dailyLimit: config.daily_limit ?? 0,
105
+ maxTurns: config.max_turns ?? 20,
106
+ oauth,
107
+ publicUrl: options.publicUrl ?? process.env.PUBLIC_URL ?? '',
108
+ extraRoutes: options.extraRoutes,
109
+ })
110
+ return { store, config, ...cap }
111
+ }
package/src/http.mjs ADDED
@@ -0,0 +1,43 @@
1
+ const MAX_BODY = 1_000_000
2
+
3
+ export function send(res, status, body, extra = {}) {
4
+ res.writeHead(status, {
5
+ 'content-type': extra.type || 'application/json; charset=utf-8',
6
+ 'access-control-allow-origin': '*',
7
+ 'access-control-allow-headers': 'authorization, content-type, cap-version, cap-from, idempotency-key',
8
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
9
+ 'access-control-expose-headers': 'location, retry-after',
10
+ 'cache-control': 'no-store',
11
+ ...(extra.headers || {}),
12
+ })
13
+ res.end(extra.raw ?? JSON.stringify(body))
14
+ }
15
+
16
+ export function fail(res, status, code, message, headers) {
17
+ send(res, status, { error: { code, message } }, { headers })
18
+ }
19
+
20
+ export function readBody(req) {
21
+ return new Promise((resolve, reject) => {
22
+ const chunks = []
23
+ let size = 0
24
+ req.on('data', (chunk) => {
25
+ size += chunk.length
26
+ if (size > MAX_BODY) {
27
+ reject(Object.assign(new Error('Body is too large.'), { status: 400 }))
28
+ req.destroy()
29
+ return
30
+ }
31
+ chunks.push(chunk)
32
+ })
33
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
34
+ req.on('error', reject)
35
+ })
36
+ }
37
+
38
+ export function requestOrigin(req, publicUrl = '') {
39
+ if (publicUrl) return publicUrl.replace(/\/$/, '')
40
+ const host = req.headers['x-forwarded-host'] || req.headers.host || '127.0.0.1'
41
+ const proto = req.headers['x-forwarded-proto'] || 'http'
42
+ return `${proto}://${host}`
43
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http'
2
+
3
+ export type AgentCard = {
4
+ name: string
5
+ chat?: string
6
+ status?: 'active' | 'paused' | 'draft' | 'archived' | string
7
+ spec?: string
8
+ oauth?: string
9
+ }
10
+
11
+ export type Turn = {
12
+ message: string
13
+ context: Record<string, unknown>
14
+ reply: string | null
15
+ }
16
+
17
+ export type AnswerInput = {
18
+ message: string
19
+ context: Record<string, unknown>
20
+ history: Turn[]
21
+ account: string | null
22
+ scope: 'read' | 'write' | null
23
+ caller: string
24
+ }
25
+
26
+ export type AnswerError = { error: { code: string; message: string } }
27
+
28
+ export type AnswerResult =
29
+ | string
30
+ | { reply: string }
31
+ | AnswerError
32
+ | { confirm: { summary: string; authorization_details?: unknown[] }; reply?: string }
33
+
34
+ export type Answer = (input: AnswerInput) => AnswerResult | Promise<AnswerResult>
35
+
36
+ export type CapServerOptions = {
37
+ agent: AgentCard
38
+ answer: Answer
39
+ /** Checks the company's own user store. Returning an account id turns on OAuth. */
40
+ login?: (input: { username: string; password: string }) => string | null | Promise<string | null>
41
+ /** Runs once after a person approves a held action. */
42
+ act?: (input: { account: string; authorization_details: unknown; caller: string }) => { message: string } | { error: { message: string } } | Promise<{ message: string } | { error: { message: string } }>
43
+ write?: boolean
44
+ allowHttpClients?: boolean
45
+ grants?: { token: string; account: string; client: string; scope?: 'read' | 'write' }[]
46
+ waitSeconds?: number
47
+ waitMs?: number
48
+ retryAfter?: number
49
+ retentionHours?: number
50
+ dailyLimit?: number
51
+ maxTurns?: number
52
+ publicUrl?: string
53
+ databaseUrl?: string
54
+ /** SQLite file, or `:memory:`. Ignored when databaseUrl is a Postgres URL. */
55
+ sqlitePath?: string
56
+ accessTokenSeconds?: number
57
+ writeAccessTokenSeconds?: number
58
+ deviceInterval?: number
59
+ hint?: string
60
+ fetch?: typeof fetch
61
+ extraRoutes?: (req: IncomingMessage, res: ServerResponse, url: URL) => boolean | Promise<boolean>
62
+ }
63
+
64
+ export type ListenAddress = {
65
+ port: number
66
+ address: string
67
+ family: string
68
+ }
69
+
70
+ export type CapServer = {
71
+ listen(port?: number, host?: string): Promise<ListenAddress | string | null>
72
+ close(): Promise<void>
73
+ fetch(request: Request): Promise<Response>
74
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>
75
+ }
76
+
77
+ export function createCapServer(options: CapServerOptions): Promise<CapServer>
78
+
79
+ export function createCapHandler(options: CapServerOptions): Promise<{
80
+ handle(request: Request): Promise<Response>
81
+ close(): Promise<void>
82
+ }>
83
+
84
+ export function checkDoor(origin: string, options?: {
85
+ message?: string
86
+ timeoutMs?: number
87
+ fetch?: typeof fetch
88
+ }): Promise<{ ok: boolean; failures: string[] }>
package/src/index.js ADDED
@@ -0,0 +1,115 @@
1
+ import { join } from 'node:path'
2
+ import { createOAuth } from './oauth.mjs'
3
+ import { createCapServer as createNodeServer } from './node-server.mjs'
4
+ import { createStore } from './store.mjs'
5
+ import { handleWeb } from './web.mjs'
6
+
7
+ export { checkDoor } from './check.mjs'
8
+
9
+ /**
10
+ * Run a CAP front door. `answer` is the only part that belongs to the company.
11
+ * It receives `{ message, context, history, account, scope, caller }` and
12
+ * returns a reply string, `{ reply }`, or `{ error: { code, message } }`.
13
+ */
14
+ export async function createCapServer(options = {}) {
15
+ const agent = normalizeAgent(options.agent)
16
+ if (typeof options.answer !== 'function') throw new Error('createCapServer needs an answer function.')
17
+
18
+ const sqlitePath = options.sqlitePath ?? process.env.SQLITE_PATH ?? join(process.cwd(), 'data', 'cap.sqlite')
19
+ const databaseUrl = options.databaseUrl != null
20
+ ? options.databaseUrl
21
+ : (options.sqlitePath ? '' : (process.env.DATABASE_URL || ''))
22
+ const store = await createStore({
23
+ databaseUrl,
24
+ sqlitePath: databaseUrl ? undefined : sqlitePath,
25
+ })
26
+
27
+ for (const grant of options.grants || []) {
28
+ if (grant.token && grant.account && grant.client) {
29
+ await store.upsertGrant({
30
+ token: grant.token,
31
+ account: grant.account,
32
+ clientId: grant.client,
33
+ scope: grant.scope === 'write' ? 'write' : 'read',
34
+ })
35
+ }
36
+ }
37
+
38
+ const oauth = options.login
39
+ ? createOAuth({
40
+ store,
41
+ agentName: agent.name,
42
+ login: options.login,
43
+ write: Boolean(options.write),
44
+ act: options.act || null,
45
+ accessTokenSeconds: options.accessTokenSeconds ?? 3600,
46
+ writeAccessTokenSeconds: options.writeAccessTokenSeconds ?? 900,
47
+ allowHttpClients: Boolean(options.allowHttpClients),
48
+ hint: options.hint || '',
49
+ fetchImpl: options.fetch,
50
+ deviceInterval: options.deviceInterval ?? 5,
51
+ })
52
+ : null
53
+
54
+ const node = createNodeServer({
55
+ store,
56
+ agent,
57
+ answer: normalizeAnswer(options.answer),
58
+ waitMs: options.waitMs ?? (options.waitSeconds ?? 20) * 1000,
59
+ retryAfter: options.retryAfter ?? 5,
60
+ retentionHours: options.retentionHours ?? 24,
61
+ dailyLimit: options.dailyLimit ?? 0,
62
+ maxTurns: options.maxTurns ?? 20,
63
+ oauth,
64
+ publicUrl: options.publicUrl ?? process.env.PUBLIC_URL ?? '',
65
+ extraRoutes: options.extraRoutes,
66
+ })
67
+
68
+ return {
69
+ handle: node.handle,
70
+ fetch(request) {
71
+ return handleWeb(node.handle, request)
72
+ },
73
+ listen(port = Number(process.env.PORT || 8088), host = process.env.HOST || '0.0.0.0') {
74
+ return new Promise((resolve, reject) => {
75
+ node.server.once('error', reject)
76
+ node.server.listen(port, host, () => {
77
+ const address = node.server.address()
78
+ resolve(address)
79
+ })
80
+ })
81
+ },
82
+ async close() {
83
+ await new Promise((resolve) => node.server.close(resolve))
84
+ await store.close()
85
+ },
86
+ }
87
+ }
88
+
89
+ /** Same server, as a Fetch handler for Next.js and other Web servers. */
90
+ export async function createCapHandler(options) {
91
+ const cap = await createCapServer(options)
92
+ return {
93
+ handle: (request) => cap.fetch(request),
94
+ close: () => cap.close(),
95
+ }
96
+ }
97
+
98
+ function normalizeAgent(agent) {
99
+ if (!agent?.name || typeof agent.name !== 'string') throw new Error('createCapServer needs agent.name.')
100
+ return {
101
+ name: agent.name,
102
+ status: agent.status || 'active',
103
+ chat: agent.chat || '',
104
+ spec: agent.spec || '',
105
+ oauth: agent.oauth || '',
106
+ }
107
+ }
108
+
109
+ function normalizeAnswer(answer) {
110
+ return async (input) => {
111
+ const value = await answer(input)
112
+ if (typeof value === 'string') return { reply: value }
113
+ return value
114
+ }
115
+ }