@cerebro-labs/agentnava-sdk 0.47.1 → 0.50.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 +11 -0
- package/agent.d.ts +15 -1
- package/agent.js +6 -3
- package/agent.js.map +1 -1
- package/conversation.d.ts +3 -1
- package/conversation.js +6 -1
- package/conversation.js.map +1 -1
- package/index.d.ts +1 -1
- package/index.js.map +1 -1
- package/load-agent-dir.js +2 -21
- package/load-agent-dir.js.map +1 -1
- package/package.json +1 -1
- package/project.js +10 -3
- package/project.js.map +1 -1
- package/turn.d.ts +6 -2
- package/turn.js +85 -19
- package/turn.js.map +1 -1
- package/types.d.ts +66 -14
- package/types.js +1 -1
- package/types.js.map +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.js.map +1 -1
package/load-agent-dir.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-agent-dir.js","sourceRoot":"","sources":["../src/load-agent-dir.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wDAAwD;AACxD,EAAE;AACF,YAAY;AACZ,6FAA6F;AAC7F,kFAAkF;AAClF,wEAAwE;AACxE,6DAA6D;AAC7D,oFAAoF;AACpF,gFAAgF;AAChF,wFAAwF;AACxF,EAAE;AACF,+EAA+E;AAC/E,kFAAkF;AAClF,iFAAiF;AACjF,6EAA6E;AAC7E,gCAAgC;AAChC,uEAAuE;AACvE,+EAA+E;AAC/E,EAAE;AACF,2EAA2E;AAC3E,8EAA8E;AAC9E,wEAAwE;AACxE,EAAE;AACF,iFAAiF;AACjF,gFAAgF;AAChF,iFAAiF;AACjF,8EAA8E;AAC9E,EAAE;AACF,gFAAgF;AAChF,wDAAwD;AAExD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OA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AAC;IACF,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC;AAED,6DAA6D;AAC7D,SAAS,aAAa,CAAC,GAAW;IACjC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE;QAAE,OAAO,EAAE,CAAC;IAChE,MAAM,GAAG,GAAe,EAAE,CAAC;IAC3B,KAAK,MAAM,IAAI,IAAI,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC5C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,SAAS;QAC5D,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACjC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE;YAAE,SAAS;QAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACvC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["// `loadAgentDir` reads a Claude-Code-style folder and returns a SpecInput\n// suitable for `an.specs.push(...)`. Layout it expects:\n//\n// <path>/\n// ├── AGENT.md # required: core instructions (CLAUDE.md equivalent)\n// ├── skills/<name>/SKILL.md # optional, repeated: loaded as workflows\n// ├── subagents/<name>.md # optional, repeated (advanced)\n// ├── workflows/<name>.md # optional, repeated\n// ├── commands/<name>.md # IGNORED (warned): specs carry no commands\n// ├── http-tools.json # optional, declarative HTTP tool array\n// └── agent.json # optional, capabilities (tools, sandbox, role)\n//\n// Files inside `skills/` use the Claude Code convention: one folder per skill,\n// containing `SKILL.md` with YAML frontmatter. The folder name is the skill name.\n// Each one loads as a WORKFLOW: a spec is instructions plus workflows and has no\n// skills collection (PR #873). `skills/` is read only so a Claude Code agent\n// directory drops in unchanged.\n// `subagents/` and `workflows/` are flat directories of `<name>.md`. A\n// `commands/` directory is ignored with a warning: specs no longer carry them.\n//\n// Every workflow, from either folder, is read with `parseWorkflow`, so its\n// frontmatter `when:` (or a SKILL.md's `description:`) becomes the `when` the\n// platform requires. The file or folder name stays the workflow's name.\n//\n// `agent.json` is what makes a folder self-describing: it carries the spec-level\n// capabilities (`tools`, `sandbox`, `role`) alongside the markdown, so an agent\n// directory can be copied between workspaces and still be the same agent. Values\n// passed in `opts` win over the file, so a caller can still override in code.\n//\n// Knowledge base files are NOT loaded by this helper. Use `an.knowledge.upload`\n// for those. Everything else in the bundle is markdown.\n\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Filesystem, HttpTool, McpServer, SpecFile, SpecInput } from './types.ts';\nimport { parseWorkflow, workflowSlug } from './workflows.ts';\n\n// Local aliases, so the body of this file reads the way it was written against\n// the retired package's names. Nothing outside this module uses them.\ntype HttpToolDef = HttpTool;\ntype McpServerSpec = McpServer;\ntype AgentRole = string;\ntype SpecSandbox = Filesystem;\ntype SpecToolGroup = string;\ntype WidgetDef = { name: string; [k: string]: unknown };\n\nexport interface LoadAgentDirOptions {\n\t/** Dev-chosen, stable key, required. Used by the backend to upsert this spec. */\n\tkey: string;\n\t/** The role this agent plays. Default `'freelancer'` is applied server-side\n\t * when omitted. See {@link AgentRole} for the full vocabulary. */\n\trole?: AgentRole;\n\t/** Platform tool groups to grant. Overrides `agent.json`. */\n\ttools?: SpecToolGroup[];\n\t/** Filesystem for this agent's turns. Overrides `agent.json`. */\n\tsandbox?: SpecSandbox;\n}\n\n/** The optional `agent.json` manifest, spec-level capabilities that belong with\n * the markdown rather than in whatever script happens to push it. */\ninterface AgentManifest {\n\ttools?: SpecToolGroup[];\n\tsandbox?: SpecSandbox;\n\trole?: AgentRole;\n}\n\nexport function loadAgentDir(path: string, opts: LoadAgentDirOptions): SpecInput {\n\tif (!opts.key) {\n\t\tthrow new Error('[loadAgentDir] opts.key is required');\n\t}\n\tif (!existsSync(path) || !statSync(path).isDirectory()) {\n\t\tthrow new Error(`[loadAgentDir] not a directory: ${path}`);\n\t}\n\n\tconst agentMdPath = join(path, 'AGENT.md');\n\tif (!existsSync(agentMdPath)) {\n\t\tthrow new Error(\n\t\t\t`[loadAgentDir] missing required file: ${agentMdPath}. ` +\n\t\t\t\t`Every spec needs an AGENT.md (the CLAUDE.md equivalent: core instructions).`,\n\t\t);\n\t}\n\tconst instructions = readFileSync(agentMdPath, 'utf8');\n\n\tconst subagents = loadFlatMdDir(join(path, 'subagents'));\n\t// A workflows/<name>.md wins over a skills/<name>/SKILL.md of the same name,\n\t// \"same\" as the platform compares them (workflowSlug): it refuses two\n\t// workflows that reduce to one identifier, so both would fail at publish.\n\t// Warned rather than hidden in silence, like commands/.\n\tconst asWorkflow = (f: SpecFile): SpecFile => ({ ...parseWorkflow(f.content, f.name), name: f.name });\n\tconst workflows = loadFlatMdDir(join(path, 'workflows')).map(asWorkflow);\n\tconst key = (name: string) => workflowSlug(name) || name;\n\t// slug -> the file that claimed it, so the warning names the right folder.\n\tconst claimed = new Map<string, string>(workflows.map((w) => [key(w.name), `workflows/${w.name}.md`]));\n\tfor (const skill of loadSkillsDir(join(path, 'skills'))) {\n\t\tconst file = `skills/${skill.name}/SKILL.md`;\n\t\tconst shadow = claimed.get(key(skill.name));\n\t\tif (shadow !== undefined) {\n\t\t\tconsole.warn(`[loadAgentDir] ignoring ${file}: ${shadow} has the same name. Rename one of them to keep both.`);\n\t\t\tcontinue;\n\t\t}\n\t\tclaimed.set(key(skill.name), file);\n\t\tworkflows.push(asWorkflow(skill));\n\t}\n\t// `commands/` is read only to WARN about it. A spec has no commands field any\n\t// more: slash commands had one writer (the dedicated-vm translator) and no\n\t// reader on the default runtime.\n\t//\n\t// Deliberately not folded into workflows, which would be the tempting\n\t// one-liner. A Claude Code slash command is invoked BY A PERSON; a workflow is\n\t// invoked by the model whenever it looks relevant. Folding them would make\n\t// every /command fire unbidden, which is a behaviour change disguised as a\n\t// migration. Warned rather than dropped in silence, and rather than thrown,\n\t// so an existing agent directory still loads.\n\tconst commands = loadFlatMdDir(join(path, 'commands'));\n\tif (commands.length > 0) {\n\t\tconsole.warn(\n\t\t\t`[loadAgentDir] ignoring ${commands.length} file(s) in commands/: agent specs no longer ` +\n\t\t\t\t'carry slash commands. Move any that should run automatically into workflows/.',\n\t\t);\n\t}\n\n\tconst out: SpecInput = { key: opts.key, instructions };\n\tif (subagents.length > 0) out.subagents = subagents;\n\tif (workflows.length > 0) out.workflows = workflows;\n\tconst httpTools = loadHttpTools(join(path, 'http-tools.json'));\n\tif (httpTools && httpTools.length > 0) out.httpTools = httpTools;\n\tconst widgets = loadWidgets(join(path, 'widgets.json'));\n\tif (widgets && widgets.length > 0) out.widgets = widgets;\n\tconst mcpServers = loadMcpServers(join(path, 'mcp-servers.json'));\n\tif (mcpServers && mcpServers.length > 0) out.mcpServers = mcpServers;\n\n\tconst manifest = loadManifest(join(path, 'agent.json'));\n\tconst tools = opts.tools ?? manifest.tools;\n\tif (tools && tools.length > 0) out.tools = tools;\n\tconst sandbox = opts.sandbox ?? manifest.sandbox;\n\tif (sandbox) out.sandbox = sandbox;\n\tconst role = opts.role ?? manifest.role;\n\tif (role) out.role = role;\n\treturn out;\n}\n\n/** agent.json, optional. Absent is the common case and means \"all defaults\". */\nfunction loadManifest(filePath: string): AgentManifest {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return {};\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] agent.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] agent.json: must be an object');\n\t}\n\tconst m = parsed as Record<string, unknown>;\n\tif (m.tools !== undefined && !Array.isArray(m.tools)) {\n\t\tthrow new Error('[loadAgentDir] agent.json: \"tools\" must be an array');\n\t}\n\tif (m.sandbox !== undefined && m.sandbox !== 'drive' && m.sandbox !== 'none') {\n\t\tthrow new Error(`[loadAgentDir] agent.json: \"sandbox\" must be 'drive' or 'none'`);\n\t}\n\t// Group names are NOT validated here on purpose: the platform is the\n\t// authority on which groups exist and rejects unknown ones at push time with\n\t// the current list, so the SDK never goes stale against a newer platform.\n\treturn m as AgentManifest;\n}\n\nfunction loadHttpTools(filePath: string): HttpToolDef[] | undefined {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return undefined;\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] http-tools.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] http-tools.json: must be an array of tool defs');\n\t}\n\treturn parsed as HttpToolDef[];\n}\n\nfunction loadWidgets(filePath: string): WidgetDef[] | undefined {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return undefined;\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] widgets.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] widgets.json: must be an array of widget defs');\n\t}\n\treturn parsed as WidgetDef[];\n}\n\nfunction loadMcpServers(filePath: string): McpServerSpec[] | undefined {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return undefined;\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] mcp-servers.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] mcp-servers.json: must be an array of MCP server defs');\n\t}\n\treturn parsed as McpServerSpec[];\n}\n\n/** skills/<name>/SKILL.md: name comes from the directory. */\nfunction loadSkillsDir(dir: string): SpecFile[] {\n\tif (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n\tconst out: SpecFile[] = [];\n\tfor (const name of readdirSync(dir).sort()) {\n\t\tif (name.startsWith('.')) continue;\n\t\tconst skillPath = join(dir, name, 'SKILL.md');\n\t\tif (existsSync(skillPath) && statSync(skillPath).isFile()) {\n\t\t\tout.push({ name, content: readFileSync(skillPath, 'utf8') });\n\t\t}\n\t}\n\treturn out;\n}\n\n/** subagents/, workflows/: flat directories of <name>.md. */\nfunction loadFlatMdDir(dir: string): SpecFile[] {\n\tif (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n\tconst out: SpecFile[] = [];\n\tfor (const file of readdirSync(dir).sort()) {\n\t\tif (!file.endsWith('.md') || file.startsWith('.')) continue;\n\t\tconst filePath = join(dir, file);\n\t\tif (!statSync(filePath).isFile()) continue;\n\t\tconst name = file.replace(/\\.md$/, '');\n\t\tout.push({ name, content: readFileSync(filePath, 'utf8') });\n\t}\n\treturn out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"load-agent-dir.js","sourceRoot":"","sources":["../src/load-agent-dir.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wDAAwD;AACxD,EAAE;AACF,YAAY;AACZ,6FAA6F;AAC7F,kFAAkF;AAClF,wEAAwE;AACxE,6DAA6D;AAC7D,oFAAoF;AACpF,gFAAgF;AAChF,wFAAwF;AACxF,EAAE;AACF,+EAA+E;AAC/E,kFAAkF;AAClF,iFAAiF;AACjF,6EAA6E;AAC7E,gCAAgC;AAChC,uEAAuE;AACvE,+EAA+E;AAC/E,EAAE;AACF,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C,CAAC;QACjC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE;YAAE,SAAS;QAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACvC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["// `loadAgentDir` reads a Claude-Code-style folder and returns a SpecInput\n// suitable for `an.specs.push(...)`. Layout it expects:\n//\n// <path>/\n// ├── AGENT.md # required: core instructions (CLAUDE.md equivalent)\n// ├── skills/<name>/SKILL.md # optional, repeated: loaded as workflows\n// ├── subagents/<name>.md # optional, repeated (advanced)\n// ├── workflows/<name>.md # optional, repeated\n// ├── commands/<name>.md # IGNORED (warned): specs carry no commands\n// ├── http-tools.json # optional, declarative HTTP tool array\n// └── agent.json # optional, capabilities (tools, sandbox, role)\n//\n// Files inside `skills/` use the Claude Code convention: one folder per skill,\n// containing `SKILL.md` with YAML frontmatter. The folder name is the skill name.\n// Each one loads as a WORKFLOW: a spec is instructions plus workflows and has no\n// skills collection (PR #873). `skills/` is read only so a Claude Code agent\n// directory drops in unchanged.\n// `subagents/` and `workflows/` are flat directories of `<name>.md`. A\n// `commands/` directory is ignored with a warning: specs no longer carry them.\n//\n// Every workflow, from either folder, is read with `parseWorkflow`, so its\n// frontmatter `when:` (or a SKILL.md's `description:`) becomes the `when` the\n// platform requires. The file or folder name stays the workflow's name.\n//\n// `agent.json` is what makes a folder self-describing: it carries the spec-level\n// capabilities (`tools`, `sandbox`, `role`) alongside the markdown, so an agent\n// directory can be copied between workspaces and still be the same agent. Values\n// passed in `opts` win over the file, so a caller can still override in code.\n//\n// Knowledge base files are NOT loaded by this helper. Use `an.knowledge.upload`\n// for those. Everything else in the bundle is markdown.\n\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Filesystem, HttpTool, McpServer, SpecFile, SpecInput } from './types.ts';\nimport { parseWorkflow, workflowSlug } from './workflows.ts';\n\n// Local aliases, so the body of this file reads the way it was written against\n// the retired package's names. Nothing outside this module uses them.\ntype HttpToolDef = HttpTool;\ntype McpServerSpec = McpServer;\ntype AgentRole = string;\ntype SpecSandbox = Filesystem;\ntype SpecToolGroup = string;\n\nexport interface LoadAgentDirOptions {\n\t/** Dev-chosen, stable key, required. Used by the backend to upsert this spec. */\n\tkey: string;\n\t/** The role this agent plays. Default `'freelancer'` is applied server-side\n\t * when omitted. See {@link AgentRole} for the full vocabulary. */\n\trole?: AgentRole;\n\t/** Platform tool groups to grant. Overrides `agent.json`. */\n\ttools?: SpecToolGroup[];\n\t/** Filesystem for this agent's turns. Overrides `agent.json`. */\n\tsandbox?: SpecSandbox;\n}\n\n/** The optional `agent.json` manifest, spec-level capabilities that belong with\n * the markdown rather than in whatever script happens to push it. */\ninterface AgentManifest {\n\ttools?: SpecToolGroup[];\n\tsandbox?: SpecSandbox;\n\trole?: AgentRole;\n}\n\nexport function loadAgentDir(path: string, opts: LoadAgentDirOptions): SpecInput {\n\tif (!opts.key) {\n\t\tthrow new Error('[loadAgentDir] opts.key is required');\n\t}\n\tif (!existsSync(path) || !statSync(path).isDirectory()) {\n\t\tthrow new Error(`[loadAgentDir] not a directory: ${path}`);\n\t}\n\n\tconst agentMdPath = join(path, 'AGENT.md');\n\tif (!existsSync(agentMdPath)) {\n\t\tthrow new Error(\n\t\t\t`[loadAgentDir] missing required file: ${agentMdPath}. ` +\n\t\t\t\t`Every spec needs an AGENT.md (the CLAUDE.md equivalent: core instructions).`,\n\t\t);\n\t}\n\tconst instructions = readFileSync(agentMdPath, 'utf8');\n\n\tconst subagents = loadFlatMdDir(join(path, 'subagents'));\n\t// A workflows/<name>.md wins over a skills/<name>/SKILL.md of the same name,\n\t// \"same\" as the platform compares them (workflowSlug): it refuses two\n\t// workflows that reduce to one identifier, so both would fail at publish.\n\t// Warned rather than hidden in silence, like commands/.\n\tconst asWorkflow = (f: SpecFile): SpecFile => ({ ...parseWorkflow(f.content, f.name), name: f.name });\n\tconst workflows = loadFlatMdDir(join(path, 'workflows')).map(asWorkflow);\n\tconst key = (name: string) => workflowSlug(name) || name;\n\t// slug -> the file that claimed it, so the warning names the right folder.\n\tconst claimed = new Map<string, string>(workflows.map((w) => [key(w.name), `workflows/${w.name}.md`]));\n\tfor (const skill of loadSkillsDir(join(path, 'skills'))) {\n\t\tconst file = `skills/${skill.name}/SKILL.md`;\n\t\tconst shadow = claimed.get(key(skill.name));\n\t\tif (shadow !== undefined) {\n\t\t\tconsole.warn(`[loadAgentDir] ignoring ${file}: ${shadow} has the same name. Rename one of them to keep both.`);\n\t\t\tcontinue;\n\t\t}\n\t\tclaimed.set(key(skill.name), file);\n\t\tworkflows.push(asWorkflow(skill));\n\t}\n\t// `commands/` is read only to WARN about it. A spec has no commands field any\n\t// more: no runtime reads slash commands, and none ever had a way to author\n\t// them in a UI.\n\t//\n\t// Deliberately not folded into workflows, which would be the tempting\n\t// one-liner. A Claude Code slash command is invoked BY A PERSON; a workflow is\n\t// invoked by the model whenever it looks relevant. Folding them would make\n\t// every /command fire unbidden, which is a behaviour change disguised as a\n\t// migration. Warned rather than dropped in silence, and rather than thrown,\n\t// so an existing agent directory still loads.\n\tconst commands = loadFlatMdDir(join(path, 'commands'));\n\tif (commands.length > 0) {\n\t\tconsole.warn(\n\t\t\t`[loadAgentDir] ignoring ${commands.length} file(s) in commands/: agent specs no longer ` +\n\t\t\t\t'carry slash commands. Move any that should run automatically into workflows/.',\n\t\t);\n\t}\n\n\tconst out: SpecInput = { key: opts.key, instructions };\n\tif (subagents.length > 0) out.subagents = subagents;\n\tif (workflows.length > 0) out.workflows = workflows;\n\tconst httpTools = loadHttpTools(join(path, 'http-tools.json'));\n\tif (httpTools && httpTools.length > 0) out.httpTools = httpTools;\n\tconst mcpServers = loadMcpServers(join(path, 'mcp-servers.json'));\n\tif (mcpServers && mcpServers.length > 0) out.mcpServers = mcpServers;\n\n\tconst manifest = loadManifest(join(path, 'agent.json'));\n\tconst tools = opts.tools ?? manifest.tools;\n\tif (tools && tools.length > 0) out.tools = tools;\n\tconst sandbox = opts.sandbox ?? manifest.sandbox;\n\tif (sandbox) out.sandbox = sandbox;\n\tconst role = opts.role ?? manifest.role;\n\tif (role) out.role = role;\n\treturn out;\n}\n\n/** agent.json, optional. Absent is the common case and means \"all defaults\". */\nfunction loadManifest(filePath: string): AgentManifest {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return {};\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] agent.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] agent.json: must be an object');\n\t}\n\tconst m = parsed as Record<string, unknown>;\n\tif (m.tools !== undefined && !Array.isArray(m.tools)) {\n\t\tthrow new Error('[loadAgentDir] agent.json: \"tools\" must be an array');\n\t}\n\tif (m.sandbox !== undefined && m.sandbox !== 'drive' && m.sandbox !== 'none') {\n\t\tthrow new Error(`[loadAgentDir] agent.json: \"sandbox\" must be 'drive' or 'none'`);\n\t}\n\t// Group names are NOT validated here on purpose: the platform is the\n\t// authority on which groups exist and rejects unknown ones at push time with\n\t// the current list, so the SDK never goes stale against a newer platform.\n\treturn m as AgentManifest;\n}\n\nfunction loadHttpTools(filePath: string): HttpToolDef[] | undefined {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return undefined;\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] http-tools.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] http-tools.json: must be an array of tool defs');\n\t}\n\treturn parsed as HttpToolDef[];\n}\n\nfunction loadMcpServers(filePath: string): McpServerSpec[] | undefined {\n\tif (!existsSync(filePath) || !statSync(filePath).isFile()) return undefined;\n\tconst raw = readFileSync(filePath, 'utf8');\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch (e) {\n\t\tthrow new Error(`[loadAgentDir] mcp-servers.json: invalid JSON (${(e as Error).message})`);\n\t}\n\tif (!Array.isArray(parsed)) {\n\t\tthrow new Error('[loadAgentDir] mcp-servers.json: must be an array of MCP server defs');\n\t}\n\treturn parsed as McpServerSpec[];\n}\n\n/** skills/<name>/SKILL.md: name comes from the directory. */\nfunction loadSkillsDir(dir: string): SpecFile[] {\n\tif (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n\tconst out: SpecFile[] = [];\n\tfor (const name of readdirSync(dir).sort()) {\n\t\tif (name.startsWith('.')) continue;\n\t\tconst skillPath = join(dir, name, 'SKILL.md');\n\t\tif (existsSync(skillPath) && statSync(skillPath).isFile()) {\n\t\t\tout.push({ name, content: readFileSync(skillPath, 'utf8') });\n\t\t}\n\t}\n\treturn out;\n}\n\n/** subagents/, workflows/: flat directories of <name>.md. */\nfunction loadFlatMdDir(dir: string): SpecFile[] {\n\tif (!existsSync(dir) || !statSync(dir).isDirectory()) return [];\n\tconst out: SpecFile[] = [];\n\tfor (const file of readdirSync(dir).sort()) {\n\t\tif (!file.endsWith('.md') || file.startsWith('.')) continue;\n\t\tconst filePath = join(dir, file);\n\t\tif (!statSync(filePath).isFile()) continue;\n\t\tconst name = file.replace(/\\.md$/, '');\n\t\tout.push({ name, content: readFileSync(filePath, 'utf8') });\n\t}\n\treturn out;\n}\n"]}
|
package/package.json
CHANGED
package/project.js
CHANGED
|
@@ -129,6 +129,12 @@ export class Project {
|
|
|
129
129
|
return res.url;
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
|
+
/** A grade as the server reported it, in this SDK's vocabulary. */
|
|
133
|
+
function readGrade(value) {
|
|
134
|
+
if (value === 'fast')
|
|
135
|
+
return 'standard';
|
|
136
|
+
return GRADE_NAMES.includes(value ?? '') ? value : 'lite';
|
|
137
|
+
}
|
|
132
138
|
/** The `{ project, agents }` envelope as one flat ProjectData.
|
|
133
139
|
*
|
|
134
140
|
* The envelope and the snake_case are what apps/console reads, so the wire
|
|
@@ -142,9 +148,10 @@ export function toProjectData(body) {
|
|
|
142
148
|
name: p?.name ?? '',
|
|
143
149
|
goal: p?.goal ?? null,
|
|
144
150
|
managerInstructions: p?.manager_instructions ?? null,
|
|
145
|
-
// Any real grade passes through
|
|
146
|
-
//
|
|
147
|
-
|
|
151
|
+
// Any real grade passes through, and the old name `fast` reads as what it
|
|
152
|
+
// means now (`standard`). Anything else is the cheapest, `lite`: guessing
|
|
153
|
+
// upward would tell a caller they pay more than they do.
|
|
154
|
+
grade: readGrade(p?.grade),
|
|
148
155
|
status: p?.status === 'archived' ? 'archived' : 'active',
|
|
149
156
|
agents: members.map((m) => ({
|
|
150
157
|
agentId: m.agent_id,
|
package/project.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"project.js","sourceRoot":"","sources":["../src/project.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,WAAW,EAAkG,MAAM,YAAY,CAAC;AAWzI;;;;;;;GAOG;AACH,MAAM,OAAO,OAAO;IACV,EAAE,CAAS;IACX,KAAK,CAAO;IACb,QAAQ,CAAe;IAE/B,YAAY,IAAU,EAAE,EAAU,EAAE,QAAsB;QACzD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,QAAQ;YAAE,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;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,SAAS,EAAE,CAAC,EAAE,UAAU,IAAI,EAAE;KAC9B,CAAC;AACH,CAAC","sourcesContent":["// A project: several agents, one goal, one shared folder.\n\nimport { Conversation } from './conversation.ts';\nimport type { Http } from './http.ts';\nimport { GRADE_NAMES, type FileEntry, type Grade, type ProjectConversationData, type ProjectData, type ProjectFields } from './types.ts';\n\nexport interface ProjectStartOptions {\n\tparameters?: Record<string, string | number>;\n}\n\nexport interface FileUrlOptions {\n\tdownload?: boolean;\n\tttl?: number;\n}\n\n/**\n * A project you can work with. Holding one makes no request.\n *\n * The difference from an agent is the shared folder: every agent on a project\n * reads and writes the SAME files, which is what lets one pick up where another\n * left off. Two conversations with the same agent share nothing; two agents on\n * the same project share everything in that folder.\n */\nexport class Project {\n\treadonly id: string;\n\treadonly #http: Http;\n\tprivate snapshot?: ProjectData;\n\n\tconstructor(http: Http, id: string, snapshot?: ProjectData) {\n\t\tthis.#http = http;\n\t\tthis.id = id;\n\t\tif (snapshot) this.snapshot = snapshot;\n\t}\n\n\tprivate get base(): string {\n\t\treturn `/v1/projects/${encodeURIComponent(this.id)}`;\n\t}\n\n\tget data(): ProjectData | undefined {\n\t\treturn this.snapshot;\n\t}\n\n\tasync get(): Promise<ProjectData> {\n\t\tconst data = toProjectData(await this.#http.get(this.base));\n\t\tthis.snapshot = data;\n\t\treturn data;\n\t}\n\n\tasync update(fields: ProjectFields): Promise<Project> {\n\t\tawait this.#http.patch(this.base, fields);\n\t\t// PATCH answers the row it wrote; re-read so the object carries the roster\n\t\t// too, which the caller will ask for next.\n\t\treturn new Project(this.#http, this.id, await this.get());\n\t}\n\n\tasync addAgent(agentId: string): Promise<Project> {\n\t\tconst data = toProjectData(await this.#http.post(`${this.base}/agents`, { agentId }));\n\t\tthis.snapshot = data;\n\t\treturn new Project(this.#http, this.id, data);\n\t}\n\n\tasync removeAgent(agentId: string): Promise<Project> {\n\t\tconst data = toProjectData(\n\t\t\tawait this.#http.delete(`${this.base}/agents/${encodeURIComponent(agentId)}`),\n\t\t);\n\t\tthis.snapshot = data;\n\t\treturn new Project(this.#http, this.id, data);\n\t}\n\n\t/** Stop it without destroying it. The folder and the history stay readable. */\n\tasync archive(): Promise<Project> {\n\t\tconst data = toProjectData(await this.#http.post(`${this.base}/archive`));\n\t\tthis.snapshot = data;\n\t\treturn new Project(this.#http, this.id, data);\n\t}\n\n\t/** Delete it, and the shared folder with it. Archive is usually what you\n\t * wanted. */\n\tasync delete(): Promise<void> {\n\t\tawait this.#http.delete(this.base);\n\t}\n\n\tasync start(options: ProjectStartOptions = {}): Promise<Conversation> {\n\t\tconst data = await this.#http.post<ProjectConversationData>(`${this.base}/conversations`, {\n\t\t\t...(options.parameters && { parameters: options.parameters }),\n\t\t});\n\t\t// A project conversation and an agent conversation differ in what STARTED\n\t\t// them, not in what you can do with one, so they share the class. The\n\t\t// distinction that matters (which id it carries) is in the data.\n\t\treturn new Conversation(this.#http, data.id);\n\t}\n\n\t/**\n\t * Address one of this project's conversations by id. No request.\n\t *\n\t * The sibling of `agent.conversation(id)`: the thing that owns it is the\n\t * thing you ask.\n\t *\n\t * A PROJECT HAS ONE CONVERSATION PER AGENT, NOT ONE IN TOTAL. Starting a\n\t * project opens the manager's conversation and one for every agent on the\n\t * roster, so `conversations()` on a two-agent project returns three.\n\t *\n\t * This comment used to say a project had exactly one, which was true when it\n\t * was written and had stopped being true by the time anyone read it.\n\t * Observed on deployed staging on 2026-09-18: starting a project with Sal and\n\t * Otis returned three, the manager's being the one with no `agent_id`.\n\t *\n\t * Tell them apart by `agent_id` on the wire row: absent means the manager,\n\t * which is derived from the project rather than configured as an agent, and\n\t * whose `conversation.agentId` reads `manager-<projectId>`.\n\t *\n\t * It resolves because `getSession` reads both session tables: an id does\n\t * not say which one it came from, so the route answers for either.\n\t */\n\tconversation(conversationId: string): Conversation {\n\t\treturn new Conversation(this.#http, conversationId);\n\t}\n\n\tasync conversations(): Promise<Conversation[]> {\n\t\t// `sessions`, which is what the route actually answers with. This read\n\t\t// `res.conversations`, which is always undefined, so `?? []` turned a SHAPE\n\t\t// MISMATCH into a plausible empty list and every project reported having no\n\t\t// conversations however many it had.\n\t\t//\n\t\t// The URL was never the problem: /conversations is a real alias for\n\t\t// /sessions and both return `{ sessions: [...] }`. Only the key was wrong,\n\t\t// which is why nothing 404'd and nothing looked broken.\n\t\t//\n\t\t// Same shape as the bugs this SDK's own end-to-end suite found on the\n\t\t// server today: an absence read as an emptiness. `?? []` is the line that\n\t\t// does the hiding, and it is load-bearing for a genuinely empty project, so\n\t\t// the fix is to read the right key rather than to remove the fallback.\n\t\tconst res = await this.#http.get<{ sessions: ProjectConversationData[] }>(\n\t\t\t`${this.base}/conversations`,\n\t\t);\n\t\treturn (res.sessions ?? []).map((c) => new Conversation(this.#http, c.id));\n\t}\n\n\t// --------------------------------------------------------- the shared folder\n\n\t/** List one directory of the shared folder. Same `path` parameter as\n\t * everywhere else on this API. */\n\tasync files(path = '/'): Promise<FileEntry[]> {\n\t\tconst res = await this.#http.get<{ files: unknown[] }>(`${this.base}/files`, { path });\n\t\treturn (res.files ?? []) as FileEntry[];\n\t}\n\n\tasync readFile(path: string): Promise<string> {\n\t\t// JSON `{path, content}`, not bare text. See Conversation.readFile.\n\t\tconst res = await this.#http.get<{ path: string; content: string }>(\n\t\t\t`${this.base}/files/content`,\n\t\t\t{ path },\n\t\t);\n\t\treturn res.content ?? '';\n\t}\n\n\tasync fileUrl(path: string, options: FileUrlOptions = {}): Promise<string> {\n\t\tconst res = await this.#http.post<{ url: string }>(`${this.base}/files/url`, {\n\t\t\tpath,\n\t\t\t...(options.download !== undefined && { download: options.download }),\n\t\t\t...(options.ttl !== undefined && { ttl: options.ttl }),\n\t\t});\n\t\treturn res.url;\n\t}\n}\n\n/** A project row as `/v1/projects` returns it: snake_case, nested. */\ninterface WireProject {\n\tid: string;\n\tworkspace_id: string;\n\tname: string;\n\tstatus: string;\n\tgoal: string | null;\n\tmanager_instructions: string | null;\n\tgrade: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\ninterface WireMember {\n\tproject_id: string;\n\tagent_id: string;\n\tagent_version: number | null;\n\tagent_name: string | null;\n\tadded_at: string;\n}\n\n/** The `{ project, agents }` envelope as one flat ProjectData.\n *\n * The envelope and the snake_case are what apps/console reads, so the wire\n * stays and the SDK translates. A caller wants `project.agents`, not\n * `response.agents` alongside `response.project`. */\nexport function toProjectData(\n\tbody: { project?: WireProject; agents?: WireMember[] } | WireProject,\n): ProjectData {\n\tconst p = ('project' in body ? body.project : body) as WireProject;\n\tconst members = ('agents' in body ? (body.agents ?? []) : []) as WireMember[];\n\treturn {\n\t\tid: p?.id ?? '',\n\t\tname: p?.name ?? '',\n\t\tgoal: p?.goal ?? null,\n\t\tmanagerInstructions: p?.manager_instructions ?? null,\n\t\t// Any real grade passes through. This used to keep only 'premium', so a\n\t\t// fast or best project read back as 'standard'.\n\t\tgrade: (GRADE_NAMES as readonly string[]).includes(p?.grade ?? '') ? (p!.grade as Grade) : 'standard',\n\t\tstatus: p?.status === 'archived' ? 'archived' : 'active',\n\t\tagents: members.map((m) => ({\n\t\t\tagentId: m.agent_id,\n\t\t\tname: m.agent_name ?? '',\n\t\t\taddedAt: m.added_at,\n\t\t})),\n\t\tcreatedAt: p?.created_at ?? '',\n\t\tupdatedAt: p?.updated_at ?? '',\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"project.js","sourceRoot":"","sources":["../src/project.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,WAAW,EAAkG,MAAM,YAAY,CAAC;AAWzI;;;;;;;GAOG;AACH,MAAM,OAAO,OAAO;IACV,EAAE,CAAS;IACX,KAAK,CAAO;IACb,QAAQ,CAAe;IAE/B,YAAY,IAAU,EAAE,EAAU,EAAE,QAAsB;QACzD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,EAAE,GAAG,EAAE,CAA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,CAAC,EAAE,EAAE,CAAC,CAAC;YAC3B,OAAO,EAAE,CAAC,CAAC,QAAQ;YACnB,IAAI,EAAE,CAAC,CAAC,UAAU,IAAI,EAAE;YACxB,OAAO,EAAE,CAAC,CAAC,QAAQ;SACnB,CAAC,CAAC;QACH,SAAS,EAAE,CAAC,EAAE,UAAU,IAAI,EAAE;QAC9B,SAAS,EAAE,CAAC,EAAE,UAAU,IAAI,EAAE;KAC9B,CAAC;AACH,CAAC","sourcesContent":["// A project: several agents, one goal, one shared folder.\n\nimport { Conversation } from './conversation.ts';\nimport type { Http } from './http.ts';\nimport { GRADE_NAMES, type FileEntry, type Grade, type ProjectConversationData, type ProjectData, type ProjectFields } from './types.ts';\n\nexport interface ProjectStartOptions {\n\tparameters?: Record<string, string | number>;\n}\n\nexport interface FileUrlOptions {\n\tdownload?: boolean;\n\tttl?: number;\n}\n\n/**\n * A project you can work with. Holding one makes no request.\n *\n * The difference from an agent is the shared folder: every agent on a project\n * reads and writes the SAME files, which is what lets one pick up where another\n * left off. Two conversations with the same agent share nothing; two agents on\n * the same project share everything in that folder.\n */\nexport class Project {\n\treadonly id: string;\n\treadonly #http: Http;\n\tprivate snapshot?: ProjectData;\n\n\tconstructor(http: Http, id: string, snapshot?: ProjectData) {\n\t\tthis.#http = http;\n\t\tthis.id = id;\n\t\tif (snapshot) this.snapshot = snapshot;\n\t}\n\n\tprivate get base(): string {\n\t\treturn `/v1/projects/${encodeURIComponent(this.id)}`;\n\t}\n\n\tget data(): ProjectData | undefined {\n\t\treturn this.snapshot;\n\t}\n\n\tasync get(): Promise<ProjectData> {\n\t\tconst data = toProjectData(await this.#http.get(this.base));\n\t\tthis.snapshot = data;\n\t\treturn data;\n\t}\n\n\tasync update(fields: ProjectFields): Promise<Project> {\n\t\tawait this.#http.patch(this.base, fields);\n\t\t// PATCH answers the row it wrote; re-read so the object carries the roster\n\t\t// too, which the caller will ask for next.\n\t\treturn new Project(this.#http, this.id, await this.get());\n\t}\n\n\tasync addAgent(agentId: string): Promise<Project> {\n\t\tconst data = toProjectData(await this.#http.post(`${this.base}/agents`, { agentId }));\n\t\tthis.snapshot = data;\n\t\treturn new Project(this.#http, this.id, data);\n\t}\n\n\tasync removeAgent(agentId: string): Promise<Project> {\n\t\tconst data = toProjectData(\n\t\t\tawait this.#http.delete(`${this.base}/agents/${encodeURIComponent(agentId)}`),\n\t\t);\n\t\tthis.snapshot = data;\n\t\treturn new Project(this.#http, this.id, data);\n\t}\n\n\t/** Stop it without destroying it. The folder and the history stay readable. */\n\tasync archive(): Promise<Project> {\n\t\tconst data = toProjectData(await this.#http.post(`${this.base}/archive`));\n\t\tthis.snapshot = data;\n\t\treturn new Project(this.#http, this.id, data);\n\t}\n\n\t/** Delete it, and the shared folder with it. Archive is usually what you\n\t * wanted. */\n\tasync delete(): Promise<void> {\n\t\tawait this.#http.delete(this.base);\n\t}\n\n\tasync start(options: ProjectStartOptions = {}): Promise<Conversation> {\n\t\tconst data = await this.#http.post<ProjectConversationData>(`${this.base}/conversations`, {\n\t\t\t...(options.parameters && { parameters: options.parameters }),\n\t\t});\n\t\t// A project conversation and an agent conversation differ in what STARTED\n\t\t// them, not in what you can do with one, so they share the class. The\n\t\t// distinction that matters (which id it carries) is in the data.\n\t\treturn new Conversation(this.#http, data.id);\n\t}\n\n\t/**\n\t * Address one of this project's conversations by id. No request.\n\t *\n\t * The sibling of `agent.conversation(id)`: the thing that owns it is the\n\t * thing you ask.\n\t *\n\t * A PROJECT HAS ONE CONVERSATION PER AGENT, NOT ONE IN TOTAL. Starting a\n\t * project opens the manager's conversation and one for every agent on the\n\t * roster, so `conversations()` on a two-agent project returns three.\n\t *\n\t * This comment used to say a project had exactly one, which was true when it\n\t * was written and had stopped being true by the time anyone read it.\n\t * Observed on deployed staging on 2026-09-18: starting a project with Sal and\n\t * Otis returned three, the manager's being the one with no `agent_id`.\n\t *\n\t * Tell them apart by `agent_id` on the wire row: absent means the manager,\n\t * which is derived from the project rather than configured as an agent, and\n\t * whose `conversation.agentId` reads `manager-<projectId>`.\n\t *\n\t * It resolves because `getSession` reads both session tables: an id does\n\t * not say which one it came from, so the route answers for either.\n\t */\n\tconversation(conversationId: string): Conversation {\n\t\treturn new Conversation(this.#http, conversationId);\n\t}\n\n\tasync conversations(): Promise<Conversation[]> {\n\t\t// `sessions`, which is what the route actually answers with. This read\n\t\t// `res.conversations`, which is always undefined, so `?? []` turned a SHAPE\n\t\t// MISMATCH into a plausible empty list and every project reported having no\n\t\t// conversations however many it had.\n\t\t//\n\t\t// The URL was never the problem: /conversations is a real alias for\n\t\t// /sessions and both return `{ sessions: [...] }`. Only the key was wrong,\n\t\t// which is why nothing 404'd and nothing looked broken.\n\t\t//\n\t\t// Same shape as the bugs this SDK's own end-to-end suite found on the\n\t\t// server today: an absence read as an emptiness. `?? []` is the line that\n\t\t// does the hiding, and it is load-bearing for a genuinely empty project, so\n\t\t// the fix is to read the right key rather than to remove the fallback.\n\t\tconst res = await this.#http.get<{ sessions: ProjectConversationData[] }>(\n\t\t\t`${this.base}/conversations`,\n\t\t);\n\t\treturn (res.sessions ?? []).map((c) => new Conversation(this.#http, c.id));\n\t}\n\n\t// --------------------------------------------------------- the shared folder\n\n\t/** List one directory of the shared folder. Same `path` parameter as\n\t * everywhere else on this API. */\n\tasync files(path = '/'): Promise<FileEntry[]> {\n\t\tconst res = await this.#http.get<{ files: unknown[] }>(`${this.base}/files`, { path });\n\t\treturn (res.files ?? []) as FileEntry[];\n\t}\n\n\tasync readFile(path: string): Promise<string> {\n\t\t// JSON `{path, content}`, not bare text. See Conversation.readFile.\n\t\tconst res = await this.#http.get<{ path: string; content: string }>(\n\t\t\t`${this.base}/files/content`,\n\t\t\t{ path },\n\t\t);\n\t\treturn res.content ?? '';\n\t}\n\n\tasync fileUrl(path: string, options: FileUrlOptions = {}): Promise<string> {\n\t\tconst res = await this.#http.post<{ url: string }>(`${this.base}/files/url`, {\n\t\t\tpath,\n\t\t\t...(options.download !== undefined && { download: options.download }),\n\t\t\t...(options.ttl !== undefined && { ttl: options.ttl }),\n\t\t});\n\t\treturn res.url;\n\t}\n}\n\n/** A project row as `/v1/projects` returns it: snake_case, nested. */\ninterface WireProject {\n\tid: string;\n\tworkspace_id: string;\n\tname: string;\n\tstatus: string;\n\tgoal: string | null;\n\tmanager_instructions: string | null;\n\tgrade: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n}\n\ninterface WireMember {\n\tproject_id: string;\n\tagent_id: string;\n\tagent_version: number | null;\n\tagent_name: string | null;\n\tadded_at: string;\n}\n\n/** A grade as the server reported it, in this SDK's vocabulary. */\nfunction readGrade(value: string | null | undefined): Grade {\n\tif (value === 'fast') return 'standard';\n\treturn (GRADE_NAMES as readonly string[]).includes(value ?? '') ? (value as Grade) : 'lite';\n}\n\n/** The `{ project, agents }` envelope as one flat ProjectData.\n *\n * The envelope and the snake_case are what apps/console reads, so the wire\n * stays and the SDK translates. A caller wants `project.agents`, not\n * `response.agents` alongside `response.project`. */\nexport function toProjectData(\n\tbody: { project?: WireProject; agents?: WireMember[] } | WireProject,\n): ProjectData {\n\tconst p = ('project' in body ? body.project : body) as WireProject;\n\tconst members = ('agents' in body ? (body.agents ?? []) : []) as WireMember[];\n\treturn {\n\t\tid: p?.id ?? '',\n\t\tname: p?.name ?? '',\n\t\tgoal: p?.goal ?? null,\n\t\tmanagerInstructions: p?.manager_instructions ?? null,\n\t\t// Any real grade passes through, and the old name `fast` reads as what it\n\t\t// means now (`standard`). Anything else is the cheapest, `lite`: guessing\n\t\t// upward would tell a caller they pay more than they do.\n\t\tgrade: readGrade(p?.grade),\n\t\tstatus: p?.status === 'archived' ? 'archived' : 'active',\n\t\tagents: members.map((m) => ({\n\t\t\tagentId: m.agent_id,\n\t\t\tname: m.agent_name ?? '',\n\t\t\taddedAt: m.added_at,\n\t\t})),\n\t\tcreatedAt: p?.created_at ?? '',\n\t\tupdatedAt: p?.updated_at ?? '',\n\t};\n}\n"]}
|
package/turn.d.ts
CHANGED
|
@@ -6,6 +6,10 @@ export type Turn = Promise<string> & AsyncIterable<TurnEvent>;
|
|
|
6
6
|
* Frames are `data: {json}` separated by blank lines. Anything else on the wire
|
|
7
7
|
* (comments, retry directives, a stray blank) is ignored rather than treated as
|
|
8
8
|
* an error: a proxy is allowed to insert keep-alive comments and a stream that
|
|
9
|
-
* died because of one would be maddening to debug.
|
|
10
|
-
|
|
9
|
+
* died because of one would be maddening to debug.
|
|
10
|
+
*
|
|
11
|
+
* `turnId` is the turn the API named in its X-Turn-ID header. It becomes the
|
|
12
|
+
* first event, `start`, yielded inside the same cleanup as the rest, so a caller
|
|
13
|
+
* who stops right there still releases the connection. */
|
|
14
|
+
export declare function parseSSE(body: ReadableStream<Uint8Array>, turnId?: string | null): AsyncGenerator<TurnEvent>;
|
|
11
15
|
export declare function makeTurn(response: Promise<Response>, recoveryMessage?: string): Turn;
|
package/turn.js
CHANGED
|
@@ -20,37 +20,50 @@ import { AgentNavaError } from "./errors.js";
|
|
|
20
20
|
* Frames are `data: {json}` separated by blank lines. Anything else on the wire
|
|
21
21
|
* (comments, retry directives, a stray blank) is ignored rather than treated as
|
|
22
22
|
* an error: a proxy is allowed to insert keep-alive comments and a stream that
|
|
23
|
-
* died because of one would be maddening to debug.
|
|
24
|
-
|
|
23
|
+
* died because of one would be maddening to debug.
|
|
24
|
+
*
|
|
25
|
+
* `turnId` is the turn the API named in its X-Turn-ID header. It becomes the
|
|
26
|
+
* first event, `start`, yielded inside the same cleanup as the rest, so a caller
|
|
27
|
+
* who stops right there still releases the connection. */
|
|
28
|
+
export async function* parseSSE(body, turnId) {
|
|
25
29
|
const reader = body.getReader();
|
|
26
30
|
const decoder = new TextDecoder();
|
|
27
31
|
let buffer = '';
|
|
28
32
|
let completed = false;
|
|
29
33
|
let assembled = '';
|
|
30
34
|
let finalReply;
|
|
35
|
+
let finalWidgets;
|
|
31
36
|
let terminal = false;
|
|
32
|
-
const
|
|
37
|
+
const steps = new Map();
|
|
38
|
+
const eventsForLine = (line) => {
|
|
33
39
|
const wire = parseLine(line);
|
|
34
40
|
if (!wire)
|
|
35
|
-
return
|
|
41
|
+
return [];
|
|
36
42
|
// Text being final does not prove the turn completed. Persistence or the
|
|
37
43
|
// observer can still fail before the runtime's terminal done marker.
|
|
38
44
|
if (wire.type === 'message-end') {
|
|
39
45
|
finalReply = typeof wire.final === 'string' ? wire.final : '';
|
|
40
|
-
|
|
46
|
+
const widgets = Array.isArray(wire.widgets) ? wire.widgets.flatMap((w) => widgetOf(w) ?? []) : [];
|
|
47
|
+
finalWidgets = widgets.length > 0 ? widgets : undefined;
|
|
48
|
+
return [];
|
|
41
49
|
}
|
|
42
50
|
if (wire.type === 'done') {
|
|
43
51
|
terminal = true;
|
|
44
|
-
return { type: 'done', reply: finalReply ?? assembled };
|
|
52
|
+
return [{ type: 'done', reply: finalReply ?? assembled, ...(finalWidgets && { widgets: finalWidgets }) }];
|
|
45
53
|
}
|
|
46
54
|
const event = translate(wire);
|
|
47
|
-
if (event
|
|
55
|
+
if (!event)
|
|
56
|
+
return [];
|
|
57
|
+
if (event.type === 'text')
|
|
48
58
|
assembled += event.text;
|
|
49
|
-
if (event
|
|
59
|
+
if (event.type === 'error')
|
|
50
60
|
terminal = true;
|
|
51
|
-
|
|
61
|
+
const progress = event.type === 'tool' ? trackStep(steps, wire) : undefined;
|
|
62
|
+
return progress ? [event, progress] : [event];
|
|
52
63
|
};
|
|
53
64
|
try {
|
|
65
|
+
if (turnId)
|
|
66
|
+
yield { type: 'start', turnId };
|
|
54
67
|
while (true) {
|
|
55
68
|
const { done, value } = await reader.read();
|
|
56
69
|
if (done) {
|
|
@@ -64,8 +77,7 @@ export async function* parseSSE(body) {
|
|
|
64
77
|
while (nl !== -1) {
|
|
65
78
|
const line = buffer.slice(0, nl).replace(/\r$/, '');
|
|
66
79
|
buffer = buffer.slice(nl + 1);
|
|
67
|
-
const event
|
|
68
|
-
if (event)
|
|
80
|
+
for (const event of eventsForLine(line))
|
|
69
81
|
yield event;
|
|
70
82
|
if (terminal)
|
|
71
83
|
return;
|
|
@@ -73,9 +85,8 @@ export async function* parseSSE(body) {
|
|
|
73
85
|
}
|
|
74
86
|
}
|
|
75
87
|
// A final frame with no trailing newline still counts.
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
yield last;
|
|
88
|
+
for (const event of eventsForLine(buffer.replace(/\r$/, '')))
|
|
89
|
+
yield event;
|
|
79
90
|
if (!terminal)
|
|
80
91
|
yield { type: 'error', message: 'The response stream ended before the turn finished.', retryable: false };
|
|
81
92
|
}
|
|
@@ -104,6 +115,50 @@ export async function* parseSSE(body) {
|
|
|
104
115
|
}
|
|
105
116
|
}
|
|
106
117
|
}
|
|
118
|
+
/** A widget off the wire, or undefined for anything that is not one. */
|
|
119
|
+
function widgetOf(raw) {
|
|
120
|
+
const w = raw;
|
|
121
|
+
if (!w || typeof w.surfaceId !== 'string' || !Array.isArray(w.components))
|
|
122
|
+
return undefined;
|
|
123
|
+
return {
|
|
124
|
+
surfaceId: w.surfaceId,
|
|
125
|
+
at: typeof w.at === 'number' && w.at >= 0 ? w.at : 0,
|
|
126
|
+
components: w.components,
|
|
127
|
+
closed: w.closed !== false,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const STEP_KINDS = new Set(['read', 'write', 'edit', 'search', 'shell', 'web', 'data', 'task', 'plan', 'other']);
|
|
131
|
+
/**
|
|
132
|
+
* Update the turn's steps from one tool event, and return the whole list when
|
|
133
|
+
* it changed.
|
|
134
|
+
*
|
|
135
|
+
* The steps are the ones the portal's Working card shows: one per tool call a
|
|
136
|
+
* person should see, in the order they started, in the words the API put on
|
|
137
|
+
* the call. The API's labels come from the same mapping the portal uses
|
|
138
|
+
* (packages/backend-contract/src/tool-steps.ts), so a developer's own app and
|
|
139
|
+
* the portal list the same steps in the same words.
|
|
140
|
+
*
|
|
141
|
+
* Built from tool events on every runtime. The runtime's own `progress`
|
|
142
|
+
* snapshot, which only some runtimes send, is not used, so a turn never
|
|
143
|
+
* reports two different lists.
|
|
144
|
+
*
|
|
145
|
+
* An API from before labels sends none. A tool's identifier is not something
|
|
146
|
+
* to show a person, so such a turn has no steps rather than raw names.
|
|
147
|
+
*/
|
|
148
|
+
function trackStep(steps, wire) {
|
|
149
|
+
if (wire.step === false || !wire.label || !wire.toolId)
|
|
150
|
+
return undefined;
|
|
151
|
+
const id = wire.toolId;
|
|
152
|
+
const known = steps.get(id);
|
|
153
|
+
if (wire.type === 'tool-start' && known)
|
|
154
|
+
return undefined;
|
|
155
|
+
// A kind this version does not know yet still gets a step, as 'other'.
|
|
156
|
+
const kind = STEP_KINDS.has(wire.kind) ? wire.kind : 'other';
|
|
157
|
+
const status = wire.type === 'tool-start' ? 'active' : wire.ok === false ? 'error' : 'done';
|
|
158
|
+
steps.set(id, known ? { ...known, status } : { id, label: wire.label, kind, status });
|
|
159
|
+
// Copies, so a caller who keeps one list and edits it cannot change the next.
|
|
160
|
+
return { type: 'progress', steps: [...steps.values()].map((step) => ({ ...step })) };
|
|
161
|
+
}
|
|
107
162
|
/**
|
|
108
163
|
* The API's event vocabulary, as the SDK's.
|
|
109
164
|
*
|
|
@@ -119,6 +174,7 @@ export async function* parseSSE(body) {
|
|
|
119
174
|
*
|
|
120
175
|
* Returns undefined for a frame with nothing to report, including an event type
|
|
121
176
|
* this version does not know. A new event must never break an old client.
|
|
177
|
+
* Steps (`progress`) are built beside this, from the tool events (trackStep).
|
|
122
178
|
*/
|
|
123
179
|
function translate(wire) {
|
|
124
180
|
switch (wire.type) {
|
|
@@ -128,14 +184,23 @@ function translate(wire) {
|
|
|
128
184
|
? { type: 'text', text: wire.delta }
|
|
129
185
|
: undefined;
|
|
130
186
|
case 'tool-start':
|
|
131
|
-
return { type: 'tool', name: wire.name ?? 'tool', state: 'start' };
|
|
187
|
+
return { type: 'tool', name: wire.name ?? 'tool', state: 'start', ...(wire.label && { label: wire.label }) };
|
|
132
188
|
case 'tool-end':
|
|
133
189
|
return {
|
|
134
190
|
type: 'tool',
|
|
135
191
|
name: wire.name ?? 'tool',
|
|
136
192
|
state: 'end',
|
|
193
|
+
...(wire.label && { label: wire.label }),
|
|
137
194
|
...(wire.ok !== undefined && { ok: wire.ok }),
|
|
138
195
|
};
|
|
196
|
+
case 'widget': {
|
|
197
|
+
const widget = widgetOf(wire.widget);
|
|
198
|
+
return widget ? { type: 'widget', widget } : undefined;
|
|
199
|
+
}
|
|
200
|
+
case 'file':
|
|
201
|
+
// A file the agent wrote in the conversation's drive. Its path is what
|
|
202
|
+
// conversation.readFile() takes.
|
|
203
|
+
return typeof wire.path === 'string' && wire.path ? { type: 'file', path: wire.path } : undefined;
|
|
139
204
|
case 'error':
|
|
140
205
|
return {
|
|
141
206
|
type: 'error',
|
|
@@ -217,7 +282,7 @@ class TurnImpl {
|
|
|
217
282
|
}
|
|
218
283
|
this.consumed = how;
|
|
219
284
|
}
|
|
220
|
-
async
|
|
285
|
+
async open() {
|
|
221
286
|
const res = await this.response;
|
|
222
287
|
if (!res.body) {
|
|
223
288
|
throw new AgentNavaError({
|
|
@@ -226,13 +291,13 @@ class TurnImpl {
|
|
|
226
291
|
status: res.status,
|
|
227
292
|
});
|
|
228
293
|
}
|
|
229
|
-
return res.body;
|
|
294
|
+
return { body: res.body, turnId: res.headers.get('x-turn-id') };
|
|
230
295
|
}
|
|
231
296
|
/** Drain the stream and resolve to the final reply. */
|
|
232
297
|
async settle() {
|
|
233
298
|
// parseSSE withholds the final answer until wire done confirms completion.
|
|
234
299
|
// EOF is an interruption even if some or all of the reply already arrived.
|
|
235
|
-
for await (const event of parseSSE(await this.
|
|
300
|
+
for await (const event of parseSSE((await this.open()).body)) {
|
|
236
301
|
if (event.type === 'done')
|
|
237
302
|
return event.reply;
|
|
238
303
|
if (event.type === 'error') {
|
|
@@ -279,7 +344,8 @@ class TurnImpl {
|
|
|
279
344
|
}
|
|
280
345
|
async *[Symbol.asyncIterator]() {
|
|
281
346
|
this.claim('iterated');
|
|
282
|
-
|
|
347
|
+
const { body, turnId } = await this.open();
|
|
348
|
+
for await (const event of parseSSE(body, turnId)) {
|
|
283
349
|
yield event.type === 'error' && this.recoveryMessage
|
|
284
350
|
? { ...event, message: `${event.message} ${this.recoveryMessage}` }
|
|
285
351
|
: event;
|
package/turn.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"turn.js","sourceRoot":"","sources":["../src/turn.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,+EAA+E;AAC/E,+EAA+E;AAC/E,qBAAqB;AACrB,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,iFAAiF;AACjF,wDAAwD;AACxD,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,qEAAqE;AAErE,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAM7C;;;;;uDAKuD;AACvD,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC;IAC/D,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAChC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,SAAS,GAAG,EAAE,CAAC;IACnB,IAAI,UAA8B,CAAC;IACnC,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,MAAM,YAAY,GAAG,CAAC,IAAY,EAAyB,EAAE;QAC5D,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI;YAAE,OAAO,SAAS,CAAC;QAC5B,yEAAyE;QACzE,qEAAqE;QACrE,IAAI,IAAI,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;YACjC,UAAU,GAAG,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAA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C,GAAG,CAAC,CAAC;QAC5B,CAAC;QACD,2EAA2E;QAC3E,oEAAoE;QACpE,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;QAC/B,OAAO,IAAI,CAAC,OAAO,CAAC;IACrB,CAAC;IAED,IAAI,CACH,IAAqD,EACrD,KAAwD;QAExD,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACvC,CAAC;IAED,KAAK,CAAY,KAAwD;QACxE,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,OAAO,CAAC,MAA4B;QACnC,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC;QAC5B,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACvB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YACvD,MAAM,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,IAAI,CAAC,eAAe;gBACnD,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;gBACnE,CAAC,CAAC,KAAK,CAAC;QACV,CAAC;IACF,CAAC;CACD;AAED,MAAM,UAAU,QAAQ,CAAC,QAA2B,EAAE,eAAe,GAAG,EAAE;IACzE,OAAO,IAAI,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAoB,CAAC;AACnE,CAAC","sourcesContent":["// One turn: `Promise<string> & AsyncIterable<TurnEvent>`.\n//\n// A caller who wants the answer writes `await conversation.ask('...')`. A caller\n// who wants to render it as it arrives writes `for await (const e of\n// conversation.ask('...'))`. One method, two shapes, because making the caller\n// choose `ask` or `askStream` up front means changing the call site later just\n// to show a spinner.\n//\n// THE MESSAGE IS SENT WHEN ask() IS CALLED, not when the result is awaited or\n// iterated. A lazy promise would mean `const t = ask(...)` did nothing and\n// `await t` twice asked twice; sending eagerly makes `ask` the verb it reads as,\n// and calling it twice is then obviously two questions.\n//\n// Awaiting AND iterating the same turn throws rather than replaying. The events\n// are a live stream over a socket, not a stored list, so a second consumer would\n// silently receive nothing at all, which is far worse than an error.\n\nimport { AgentNavaError } from './errors.ts';\nimport type { TurnEvent } from './types.ts';\n\n/** What `conversation.ask()` returns. */\nexport type Turn = Promise<string> & AsyncIterable<TurnEvent>;\n\n/** Parse an SSE body into the events the API sends.\n *\n * Frames are `data: {json}` separated by blank lines. Anything else on the wire\n * (comments, retry directives, a stray blank) is ignored rather than treated as\n * an error: a proxy is allowed to insert keep-alive comments and a stream that\n * died because of one would be maddening to debug. */\nexport async function* parseSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<TurnEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = '';\n\tlet completed = false;\n\tlet assembled = '';\n\tlet finalReply: string | undefined;\n\tlet terminal = false;\n\tconst eventForLine = (line: string): TurnEvent | undefined => {\n\t\tconst wire = parseLine(line);\n\t\tif (!wire) return undefined;\n\t\t// Text being final does not prove the turn completed. Persistence or the\n\t\t// observer can still fail before the runtime's terminal done marker.\n\t\tif (wire.type === 'message-end') {\n\t\t\tfinalReply = typeof wire.final === 'string' ? wire.final : '';\n\t\t\treturn undefined;\n\t\t}\n\t\tif (wire.type === 'done') {\n\t\t\tterminal = true;\n\t\t\treturn { type: 'done', reply: finalReply ?? assembled };\n\t\t}\n\t\tconst event = translate(wire);\n\t\tif (event?.type === 'text') assembled += event.text;\n\t\tif (event?.type === 'error') terminal = true;\n\t\treturn event;\n\t};\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tcompleted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t// Split on newlines, keeping the last partial line in the buffer. A\n\t\t\t// frame can be split across two network reads at any byte.\n\t\t\tlet nl = buffer.indexOf('\\n');\n\t\t\twhile (nl !== -1) {\n\t\t\t\tconst line = buffer.slice(0, nl).replace(/\\r$/, '');\n\t\t\t\tbuffer = buffer.slice(nl + 1);\n\t\t\t\tconst event = eventForLine(line);\n\t\t\t\tif (event) yield event;\n\t\t\t\tif (terminal) return;\n\t\t\t\tnl = buffer.indexOf('\\n');\n\t\t\t}\n\t\t}\n\t\t// A final frame with no trailing newline still counts.\n\t\tconst last = eventForLine(buffer.replace(/\\r$/, ''));\n\t\tif (last) yield last;\n\t\tif (!terminal) yield { type: 'error', message: 'The response stream ended before the turn finished.', retryable: false };\n\t} catch (error) {\n\t\t// Explicit cancellation keeps its AbortError identity. A lost transport\n\t\t// is an interrupted observer, never evidence that asking again is safe.\n\t\tif (error instanceof Error && error.name === 'AbortError') throw error;\n\t\tyield { type: 'error', message: `The response stream was interrupted: ${error instanceof Error ? error.message : String(error)}`, retryable: false };\n\t} finally {\n\t\t// A final reply, a wire error, or a caller's early break can stop before\n\t\t// EOF. Releasing the lock alone leaves the HTTP body and abort listener\n\t\t// alive; cancel unread data before releasing ownership of the reader.\n\t\ttry {\n\t\t\t// Cleanup can be slow or never settle. Initiate it before releasing\n\t\t\t// ownership, but do not delay the reply/error or iterator return.\n\t\t\tif (!completed) void reader.cancel().catch(() => {});\n\t\t} catch {\n\t\t\t// Cleanup must not replace the reply or the original stream/wire error.\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n}\n\n/** One frame as it arrives on the wire, before translation. */\ninterface WireEvent {\n\ttype: string;\n\tdelta?: string;\n\tfinal?: string;\n\tname?: string;\n\tok?: boolean;\n\tmessage?: string;\n\tretryable?: boolean;\n\tpath?: string;\n}\n\n/**\n * The API's event vocabulary, as the SDK's.\n *\n * The wire says `message-delta` / `message-end` / `tool-start` / `tool-end`, and\n * design/sdk-design.md says `text` / `done` / `tool`. Both are right for their\n * own audience: the wire shape is what apps/web's chat renders and has rendered\n * for a long time, and the SDK shape is what reads well at a call site\n * (`if (e.type === 'text')`).\n *\n * So this translates, which is the same job the SDK already does for drive\n * entries and connection rows. It is NOT a rename waiting to happen: changing\n * the wire would break a working chat UI to save a switch statement.\n *\n * Returns undefined for a frame with nothing to report, including an event type\n * this version does not know. A new event must never break an old client.\n */\nfunction translate(wire: WireEvent): TurnEvent | undefined {\n\tswitch (wire.type) {\n\t\tcase 'message-delta':\n\t\t\t// A FRAGMENT. Append, do not assemble.\n\t\t\treturn typeof wire.delta === 'string' && wire.delta.length > 0\n\t\t\t\t? { type: 'text', text: wire.delta }\n\t\t\t\t: undefined;\n\t\tcase 'tool-start':\n\t\t\treturn { type: 'tool', name: wire.name ?? 'tool', state: 'start' };\n\t\tcase 'tool-end':\n\t\t\treturn {\n\t\t\t\ttype: 'tool',\n\t\t\t\tname: wire.name ?? 'tool',\n\t\t\t\tstate: 'end',\n\t\t\t\t...(wire.ok !== undefined && { ok: wire.ok }),\n\t\t\t};\n\t\tcase 'error':\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: wire.message ?? 'the turn failed',\n\t\t\t\tretryable: wire.retryable === true,\n\t\t\t};\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction parseLine(line: string): WireEvent | undefined {\n\tif (!line.startsWith('data:')) return undefined;\n\tconst payload = line.slice(5).trim();\n\tif (!payload || payload === '[DONE]') return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(payload) as WireEvent | null;\n\t\treturn parsed && typeof parsed.type === 'string' ? parsed : undefined;\n\t} catch {\n\t\t// A frame we cannot parse is dropped rather than thrown. A malformed frame\n\t\t// must not break a stream that is otherwise fine.\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Build the dual-shaped result.\n *\n * `response` is already in flight when this is called: the caller passes the\n * running request, so the turn is sent whether or not anyone ever consumes it.\n *\n * A THENABLE, not a Promise subclass, and that was measured rather than assumed.\n * A subclass whose base promise never settles deadlocks, because `await` can\n * settle against the base's own state instead of the overridden `then`. A\n * subclass whose base resolves immediately fixes the deadlock and passes\n * `instanceof Promise`, but then anything reading the promise's INTERNAL state\n * sees \"resolved\" for a turn whose `then` rejects, which is a lie that tooling\n * believes. A thenable is honest: `await`, `Promise.all` and `.then/.catch/\n * .finally` are all defined in terms of `then` and all work, and anything that\n * demands a real Promise says so out loud instead of reporting a wrong answer.\n */\nclass TurnImpl implements AsyncIterable<TurnEvent> {\n\tprivate consumed?: 'awaited' | 'iterated';\n\tprivate settled?: Promise<string>;\n\n\tconstructor(private readonly response: Promise<Response>, private readonly recoveryMessage = '') {\n\t\t// ask() starts eagerly, while consuming its thenable may happen later.\n\t\t// Observe early rejection now; keep the ORIGINAL promise so a later\n\t\t// await/iteration still receives that same error.\n\t\tvoid response.catch(() => {});\n\t}\n\n\t/**\n\t * Record how this turn is being consumed, and refuse a second, different way.\n\t *\n\t * AWAITING TWICE IS ALLOWED, deliberately. A promise handing the same value to\n\t * two awaits is exactly what a promise is, and `drain()` memoises so the second\n\t * await costs nothing. Refusing it would break `Promise.all([turn, turn])` and\n\t * every library that attaches a `.catch()` and then awaits the same value.\n\t *\n\t * ITERATING TWICE IS NOT, and neither is mixing the two. The events are a live\n\t * stream over a socket, not a stored list: a second iterator would receive\n\t * nothing at all and report an empty turn, which is worse than an error.\n\t */\n\tprivate claim(how: 'awaited' | 'iterated'): void {\n\t\tif (how === 'awaited' && this.consumed === 'awaited') return;\n\t\tif (this.consumed) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage:\n\t\t\t\t\tthis.consumed === how\n\t\t\t\t\t\t? `This turn was already ${how}. Call ask() again to ask again; a turn is a live stream, not a replayable list.`\n\t\t\t\t\t\t: `This turn was already ${this.consumed} and cannot also be ${how}. Pick one: await it for the reply, or iterate it for the events. Call ask() again to ask again.`,\n\t\t\t\tcode: 'turn_already_consumed',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t\tthis.consumed = how;\n\t}\n\n\tprivate async body(): Promise<ReadableStream<Uint8Array>> {\n\t\tconst res = await this.response;\n\t\tif (!res.body) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: `The turn response had no body to stream. ${this.recoveryMessage}`.trim(),\n\t\t\t\tcode: 'bad_response',\n\t\t\t\tstatus: res.status,\n\t\t\t});\n\t\t}\n\t\treturn res.body;\n\t}\n\n\t/** Drain the stream and resolve to the final reply. */\n\tprivate async settle(): Promise<string> {\n\t\t// parseSSE withholds the final answer until wire done confirms completion.\n\t\t// EOF is an interruption even if some or all of the reply already arrived.\n\t\tfor await (const event of parseSSE(await this.body())) {\n\t\t\tif (event.type === 'done') return event.reply;\n\t\t\tif (event.type === 'error') {\n\t\t\t\t// Awaiting is the shape that throws. Iterating gets the error as an\n\t\t\t\t// event and the loop ends, because a for-await that throws mid-render\n\t\t\t\t// leaves the UI half-painted.\n\t\t\t\tthrow new AgentNavaError({\n\t\t\t\t\tmessage: `${event.message} ${this.recoveryMessage}`.trim(),\n\t\t\t\t\tcode: 'turn_failed',\n\t\t\t\t\tstatus: event.retryable ? 503 : 400,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthrow new AgentNavaError({ message: `The response stream ended before the turn finished. ${this.recoveryMessage}`.trim(), code: 'turn_failed', status: 400 });\n\t}\n\n\tprivate drain(): Promise<string> {\n\t\t// claim() runs HERE rather than inside settle(), because settle() runs only\n\t\t// once: a second await would skip the check entirely, and awaiting a turn\n\t\t// that was already iterated would quietly return an empty string instead of\n\t\t// saying what went wrong.\n\t\t//\n\t\t// REJECT, never throw. `then` must return a promise; a synchronous throw out\n\t\t// of it escapes the promise chain, so a caller writing\n\t\t// `turn.then(a, b).catch(c)` would get an exception past their own .catch.\n\t\ttry {\n\t\t\tthis.claim('awaited');\n\t\t} catch (err) {\n\t\t\treturn Promise.reject(err);\n\t\t}\n\t\t// Started once. `await` calls `then`, and so does Promise.all, and so does\n\t\t// anything that duck-types a thenable; all of them share one drain.\n\t\tthis.settled ??= this.settle();\n\t\treturn this.settled;\n\t}\n\n\tthen<A = string, B = never>(\n\t\tonOk?: ((value: string) => A | PromiseLike<A>) | null,\n\t\tonErr?: ((reason: unknown) => B | PromiseLike<B>) | null,\n\t): Promise<A | B> {\n\t\treturn this.drain().then(onOk, onErr);\n\t}\n\n\tcatch<B = never>(onErr?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<string | B> {\n\t\treturn this.drain().catch(onErr);\n\t}\n\n\tfinally(onDone?: (() => void) | null): Promise<string> {\n\t\treturn this.drain().finally(onDone);\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncGenerator<TurnEvent> {\n\t\tthis.claim('iterated');\n\t\tfor await (const event of parseSSE(await this.body())) {\n\t\t\tyield event.type === 'error' && this.recoveryMessage\n\t\t\t\t? { ...event, message: `${event.message} ${this.recoveryMessage}` }\n\t\t\t\t: event;\n\t\t}\n\t}\n}\n\nexport function makeTurn(response: Promise<Response>, recoveryMessage = ''): Turn {\n\treturn new TurnImpl(response, recoveryMessage) as unknown as Turn;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"turn.js","sourceRoot":"","sources":["../src/turn.ts"],"names":[],"mappings":"AAAA,0DAA0D;AAC1D,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,+EAA+E;AAC/E,+EAA+E;AAC/E,qBAAqB;AACrB,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,iFAAiF;AACjF,wDAAwD;AACxD,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,qEAAqE;AAErE,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAM7C;;;;;;;;;2DAS2D;AAC3D,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,IAAgC,EAAE,MAAsB;IACvF,MAAM,MAAM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AAC,eAAe;gBACnD,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;gBACnE,CAAC,CAAC,KAAK,CAAC;QACV,CAAC;IACF,CAAC;CACD;AAED,MAAM,UAAU,QAAQ,CAAC,QAA2B,EAAE,eAAe,GAAG,EAAE;IACzE,OAAO,IAAI,QAAQ,CAAC,QAAQ,EAAE,eAAe,CAAoB,CAAC;AACnE,CAAC","sourcesContent":["// One turn: `Promise<string> & AsyncIterable<TurnEvent>`.\n//\n// A caller who wants the answer writes `await conversation.ask('...')`. A caller\n// who wants to render it as it arrives writes `for await (const e of\n// conversation.ask('...'))`. One method, two shapes, because making the caller\n// choose `ask` or `askStream` up front means changing the call site later just\n// to show a spinner.\n//\n// THE MESSAGE IS SENT WHEN ask() IS CALLED, not when the result is awaited or\n// iterated. A lazy promise would mean `const t = ask(...)` did nothing and\n// `await t` twice asked twice; sending eagerly makes `ask` the verb it reads as,\n// and calling it twice is then obviously two questions.\n//\n// Awaiting AND iterating the same turn throws rather than replaying. The events\n// are a live stream over a socket, not a stored list, so a second consumer would\n// silently receive nothing at all, which is far worse than an error.\n\nimport { AgentNavaError } from './errors.ts';\nimport type { Step, TurnEvent, Widget } from './types.ts';\n\n/** What `conversation.ask()` returns. */\nexport type Turn = Promise<string> & AsyncIterable<TurnEvent>;\n\n/** Parse an SSE body into the events the API sends.\n *\n * Frames are `data: {json}` separated by blank lines. Anything else on the wire\n * (comments, retry directives, a stray blank) is ignored rather than treated as\n * an error: a proxy is allowed to insert keep-alive comments and a stream that\n * died because of one would be maddening to debug.\n *\n * `turnId` is the turn the API named in its X-Turn-ID header. It becomes the\n * first event, `start`, yielded inside the same cleanup as the rest, so a caller\n * who stops right there still releases the connection. */\nexport async function* parseSSE(body: ReadableStream<Uint8Array>, turnId?: string | null): AsyncGenerator<TurnEvent> {\n\tconst reader = body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = '';\n\tlet completed = false;\n\tlet assembled = '';\n\tlet finalReply: string | undefined;\n\tlet finalWidgets: Widget[] | undefined;\n\tlet terminal = false;\n\tconst steps = new Map<string, Step>();\n\tconst eventsForLine = (line: string): TurnEvent[] => {\n\t\tconst wire = parseLine(line);\n\t\tif (!wire) return [];\n\t\t// Text being final does not prove the turn completed. Persistence or the\n\t\t// observer can still fail before the runtime's terminal done marker.\n\t\tif (wire.type === 'message-end') {\n\t\t\tfinalReply = typeof wire.final === 'string' ? wire.final : '';\n\t\t\tconst widgets = Array.isArray(wire.widgets) ? wire.widgets.flatMap((w) => widgetOf(w) ?? []) : [];\n\t\t\tfinalWidgets = widgets.length > 0 ? widgets : undefined;\n\t\t\treturn [];\n\t\t}\n\t\tif (wire.type === 'done') {\n\t\t\tterminal = true;\n\t\t\treturn [{ type: 'done', reply: finalReply ?? assembled, ...(finalWidgets && { widgets: finalWidgets }) }];\n\t\t}\n\t\tconst event = translate(wire);\n\t\tif (!event) return [];\n\t\tif (event.type === 'text') assembled += event.text;\n\t\tif (event.type === 'error') terminal = true;\n\t\tconst progress = event.type === 'tool' ? trackStep(steps, wire) : undefined;\n\t\treturn progress ? [event, progress] : [event];\n\t};\n\ttry {\n\t\tif (turnId) yield { type: 'start', turnId };\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tcompleted = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t// Split on newlines, keeping the last partial line in the buffer. A\n\t\t\t// frame can be split across two network reads at any byte.\n\t\t\tlet nl = buffer.indexOf('\\n');\n\t\t\twhile (nl !== -1) {\n\t\t\t\tconst line = buffer.slice(0, nl).replace(/\\r$/, '');\n\t\t\t\tbuffer = buffer.slice(nl + 1);\n\t\t\t\tfor (const event of eventsForLine(line)) yield event;\n\t\t\t\tif (terminal) return;\n\t\t\t\tnl = buffer.indexOf('\\n');\n\t\t\t}\n\t\t}\n\t\t// A final frame with no trailing newline still counts.\n\t\tfor (const event of eventsForLine(buffer.replace(/\\r$/, ''))) yield event;\n\t\tif (!terminal) yield { type: 'error', message: 'The response stream ended before the turn finished.', retryable: false };\n\t} catch (error) {\n\t\t// Explicit cancellation keeps its AbortError identity. A lost transport\n\t\t// is an interrupted observer, never evidence that asking again is safe.\n\t\tif (error instanceof Error && error.name === 'AbortError') throw error;\n\t\tyield { type: 'error', message: `The response stream was interrupted: ${error instanceof Error ? error.message : String(error)}`, retryable: false };\n\t} finally {\n\t\t// A final reply, a wire error, or a caller's early break can stop before\n\t\t// EOF. Releasing the lock alone leaves the HTTP body and abort listener\n\t\t// alive; cancel unread data before releasing ownership of the reader.\n\t\ttry {\n\t\t\t// Cleanup can be slow or never settle. Initiate it before releasing\n\t\t\t// ownership, but do not delay the reply/error or iterator return.\n\t\t\tif (!completed) void reader.cancel().catch(() => {});\n\t\t} catch {\n\t\t\t// Cleanup must not replace the reply or the original stream/wire error.\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n}\n\n/** One frame as it arrives on the wire, before translation. */\ninterface WireEvent {\n\ttype: string;\n\tdelta?: string;\n\tfinal?: string;\n\ttoolId?: string;\n\tname?: string;\n\t/** What a person sees for the tool call (\"Searching the web: <query>\"). */\n\tlabel?: string;\n\tkind?: string;\n\t/** False for a call that is not a step a person should see. */\n\tstep?: boolean;\n\tok?: boolean;\n\tmessage?: string;\n\tretryable?: boolean;\n\tpath?: string;\n\t/** A widget drawn inside the reply (`widget`), or the final list (`message-end`). */\n\twidget?: unknown;\n\twidgets?: unknown[];\n}\n\n/** A widget off the wire, or undefined for anything that is not one. */\nfunction widgetOf(raw: unknown): Widget | undefined {\n\tconst w = raw as Partial<Widget> | null;\n\tif (!w || typeof w.surfaceId !== 'string' || !Array.isArray(w.components)) return undefined;\n\treturn {\n\t\tsurfaceId: w.surfaceId,\n\t\tat: typeof w.at === 'number' && w.at >= 0 ? w.at : 0,\n\t\tcomponents: w.components,\n\t\tclosed: w.closed !== false,\n\t};\n}\n\nconst STEP_KINDS = new Set<Step['kind']>(['read', 'write', 'edit', 'search', 'shell', 'web', 'data', 'task', 'plan', 'other']);\n\n/**\n * Update the turn's steps from one tool event, and return the whole list when\n * it changed.\n *\n * The steps are the ones the portal's Working card shows: one per tool call a\n * person should see, in the order they started, in the words the API put on\n * the call. The API's labels come from the same mapping the portal uses\n * (packages/backend-contract/src/tool-steps.ts), so a developer's own app and\n * the portal list the same steps in the same words.\n *\n * Built from tool events on every runtime. The runtime's own `progress`\n * snapshot, which only some runtimes send, is not used, so a turn never\n * reports two different lists.\n *\n * An API from before labels sends none. A tool's identifier is not something\n * to show a person, so such a turn has no steps rather than raw names.\n */\nfunction trackStep(steps: Map<string, Step>, wire: WireEvent): TurnEvent | undefined {\n\tif (wire.step === false || !wire.label || !wire.toolId) return undefined;\n\tconst id = wire.toolId;\n\tconst known = steps.get(id);\n\tif (wire.type === 'tool-start' && known) return undefined;\n\t// A kind this version does not know yet still gets a step, as 'other'.\n\tconst kind = STEP_KINDS.has(wire.kind as Step['kind']) ? (wire.kind as Step['kind']) : 'other';\n\tconst status: Step['status'] = wire.type === 'tool-start' ? 'active' : wire.ok === false ? 'error' : 'done';\n\tsteps.set(id, known ? { ...known, status } : { id, label: wire.label, kind, status });\n\t// Copies, so a caller who keeps one list and edits it cannot change the next.\n\treturn { type: 'progress', steps: [...steps.values()].map((step) => ({ ...step })) };\n}\n\n/**\n * The API's event vocabulary, as the SDK's.\n *\n * The wire says `message-delta` / `message-end` / `tool-start` / `tool-end`, and\n * design/sdk-design.md says `text` / `done` / `tool`. Both are right for their\n * own audience: the wire shape is what apps/web's chat renders and has rendered\n * for a long time, and the SDK shape is what reads well at a call site\n * (`if (e.type === 'text')`).\n *\n * So this translates, which is the same job the SDK already does for drive\n * entries and connection rows. It is NOT a rename waiting to happen: changing\n * the wire would break a working chat UI to save a switch statement.\n *\n * Returns undefined for a frame with nothing to report, including an event type\n * this version does not know. A new event must never break an old client.\n * Steps (`progress`) are built beside this, from the tool events (trackStep).\n */\nfunction translate(wire: WireEvent): TurnEvent | undefined {\n\tswitch (wire.type) {\n\t\tcase 'message-delta':\n\t\t\t// A FRAGMENT. Append, do not assemble.\n\t\t\treturn typeof wire.delta === 'string' && wire.delta.length > 0\n\t\t\t\t? { type: 'text', text: wire.delta }\n\t\t\t\t: undefined;\n\t\tcase 'tool-start':\n\t\t\treturn { type: 'tool', name: wire.name ?? 'tool', state: 'start', ...(wire.label && { label: wire.label }) };\n\t\tcase 'tool-end':\n\t\t\treturn {\n\t\t\t\ttype: 'tool',\n\t\t\t\tname: wire.name ?? 'tool',\n\t\t\t\tstate: 'end',\n\t\t\t\t...(wire.label && { label: wire.label }),\n\t\t\t\t...(wire.ok !== undefined && { ok: wire.ok }),\n\t\t\t};\n\t\tcase 'widget': {\n\t\t\tconst widget = widgetOf(wire.widget);\n\t\t\treturn widget ? { type: 'widget', widget } : undefined;\n\t\t}\n\t\tcase 'file':\n\t\t\t// A file the agent wrote in the conversation's drive. Its path is what\n\t\t\t// conversation.readFile() takes.\n\t\t\treturn typeof wire.path === 'string' && wire.path ? { type: 'file', path: wire.path } : undefined;\n\t\tcase 'error':\n\t\t\treturn {\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: wire.message ?? 'the turn failed',\n\t\t\t\tretryable: wire.retryable === true,\n\t\t\t};\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction parseLine(line: string): WireEvent | undefined {\n\tif (!line.startsWith('data:')) return undefined;\n\tconst payload = line.slice(5).trim();\n\tif (!payload || payload === '[DONE]') return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(payload) as WireEvent | null;\n\t\treturn parsed && typeof parsed.type === 'string' ? parsed : undefined;\n\t} catch {\n\t\t// A frame we cannot parse is dropped rather than thrown. A malformed frame\n\t\t// must not break a stream that is otherwise fine.\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Build the dual-shaped result.\n *\n * `response` is already in flight when this is called: the caller passes the\n * running request, so the turn is sent whether or not anyone ever consumes it.\n *\n * A THENABLE, not a Promise subclass, and that was measured rather than assumed.\n * A subclass whose base promise never settles deadlocks, because `await` can\n * settle against the base's own state instead of the overridden `then`. A\n * subclass whose base resolves immediately fixes the deadlock and passes\n * `instanceof Promise`, but then anything reading the promise's INTERNAL state\n * sees \"resolved\" for a turn whose `then` rejects, which is a lie that tooling\n * believes. A thenable is honest: `await`, `Promise.all` and `.then/.catch/\n * .finally` are all defined in terms of `then` and all work, and anything that\n * demands a real Promise says so out loud instead of reporting a wrong answer.\n */\nclass TurnImpl implements AsyncIterable<TurnEvent> {\n\tprivate consumed?: 'awaited' | 'iterated';\n\tprivate settled?: Promise<string>;\n\n\tconstructor(private readonly response: Promise<Response>, private readonly recoveryMessage = '') {\n\t\t// ask() starts eagerly, while consuming its thenable may happen later.\n\t\t// Observe early rejection now; keep the ORIGINAL promise so a later\n\t\t// await/iteration still receives that same error.\n\t\tvoid response.catch(() => {});\n\t}\n\n\t/**\n\t * Record how this turn is being consumed, and refuse a second, different way.\n\t *\n\t * AWAITING TWICE IS ALLOWED, deliberately. A promise handing the same value to\n\t * two awaits is exactly what a promise is, and `drain()` memoises so the second\n\t * await costs nothing. Refusing it would break `Promise.all([turn, turn])` and\n\t * every library that attaches a `.catch()` and then awaits the same value.\n\t *\n\t * ITERATING TWICE IS NOT, and neither is mixing the two. The events are a live\n\t * stream over a socket, not a stored list: a second iterator would receive\n\t * nothing at all and report an empty turn, which is worse than an error.\n\t */\n\tprivate claim(how: 'awaited' | 'iterated'): void {\n\t\tif (how === 'awaited' && this.consumed === 'awaited') return;\n\t\tif (this.consumed) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage:\n\t\t\t\t\tthis.consumed === how\n\t\t\t\t\t\t? `This turn was already ${how}. Call ask() again to ask again; a turn is a live stream, not a replayable list.`\n\t\t\t\t\t\t: `This turn was already ${this.consumed} and cannot also be ${how}. Pick one: await it for the reply, or iterate it for the events. Call ask() again to ask again.`,\n\t\t\t\tcode: 'turn_already_consumed',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t\tthis.consumed = how;\n\t}\n\n\tprivate async open(): Promise<{ body: ReadableStream<Uint8Array>; turnId: string | null }> {\n\t\tconst res = await this.response;\n\t\tif (!res.body) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: `The turn response had no body to stream. ${this.recoveryMessage}`.trim(),\n\t\t\t\tcode: 'bad_response',\n\t\t\t\tstatus: res.status,\n\t\t\t});\n\t\t}\n\t\treturn { body: res.body, turnId: res.headers.get('x-turn-id') };\n\t}\n\n\t/** Drain the stream and resolve to the final reply. */\n\tprivate async settle(): Promise<string> {\n\t\t// parseSSE withholds the final answer until wire done confirms completion.\n\t\t// EOF is an interruption even if some or all of the reply already arrived.\n\t\tfor await (const event of parseSSE((await this.open()).body)) {\n\t\t\tif (event.type === 'done') return event.reply;\n\t\t\tif (event.type === 'error') {\n\t\t\t\t// Awaiting is the shape that throws. Iterating gets the error as an\n\t\t\t\t// event and the loop ends, because a for-await that throws mid-render\n\t\t\t\t// leaves the UI half-painted.\n\t\t\t\tthrow new AgentNavaError({\n\t\t\t\t\tmessage: `${event.message} ${this.recoveryMessage}`.trim(),\n\t\t\t\t\tcode: 'turn_failed',\n\t\t\t\t\tstatus: event.retryable ? 503 : 400,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthrow new AgentNavaError({ message: `The response stream ended before the turn finished. ${this.recoveryMessage}`.trim(), code: 'turn_failed', status: 400 });\n\t}\n\n\tprivate drain(): Promise<string> {\n\t\t// claim() runs HERE rather than inside settle(), because settle() runs only\n\t\t// once: a second await would skip the check entirely, and awaiting a turn\n\t\t// that was already iterated would quietly return an empty string instead of\n\t\t// saying what went wrong.\n\t\t//\n\t\t// REJECT, never throw. `then` must return a promise; a synchronous throw out\n\t\t// of it escapes the promise chain, so a caller writing\n\t\t// `turn.then(a, b).catch(c)` would get an exception past their own .catch.\n\t\ttry {\n\t\t\tthis.claim('awaited');\n\t\t} catch (err) {\n\t\t\treturn Promise.reject(err);\n\t\t}\n\t\t// Started once. `await` calls `then`, and so does Promise.all, and so does\n\t\t// anything that duck-types a thenable; all of them share one drain.\n\t\tthis.settled ??= this.settle();\n\t\treturn this.settled;\n\t}\n\n\tthen<A = string, B = never>(\n\t\tonOk?: ((value: string) => A | PromiseLike<A>) | null,\n\t\tonErr?: ((reason: unknown) => B | PromiseLike<B>) | null,\n\t): Promise<A | B> {\n\t\treturn this.drain().then(onOk, onErr);\n\t}\n\n\tcatch<B = never>(onErr?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<string | B> {\n\t\treturn this.drain().catch(onErr);\n\t}\n\n\tfinally(onDone?: (() => void) | null): Promise<string> {\n\t\treturn this.drain().finally(onDone);\n\t}\n\n\tasync *[Symbol.asyncIterator](): AsyncGenerator<TurnEvent> {\n\t\tthis.claim('iterated');\n\t\tconst { body, turnId } = await this.open();\n\t\tfor await (const event of parseSSE(body, turnId)) {\n\t\t\tyield event.type === 'error' && this.recoveryMessage\n\t\t\t\t? { ...event, message: `${event.message} ${this.recoveryMessage}` }\n\t\t\t\t: event;\n\t\t}\n\t}\n}\n\nexport function makeTurn(response: Promise<Response>, recoveryMessage = ''): Turn {\n\treturn new TurnImpl(response, recoveryMessage) as unknown as Turn;\n}\n"]}
|