@tangle-network/create-agent-app 0.60.160 → 0.60.161

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/create-agent-app",
3
- "version": "0.60.160",
3
+ "version": "0.60.161",
4
4
  "description": "Create a tested Tangle agent application with either a tool loop or a complete chat interface.",
5
5
  "keywords": [
6
6
  "tangle",
@@ -81,3 +81,9 @@ Discovery: **Does the customized agent hold its contract?**
81
81
  - [ ] `pnpm knowledge:ingest` — enumerates without error.
82
82
  - [ ] Fill `wrangler.toml` (D1 id, KV id, `MODEL_NAME`), run the preset migration,
83
83
  then `pnpm dev` to exercise `/chat` for real.
84
+
85
+ Before exposing `/chat`, pass a trusted server-side `HeadlessAuth.authenticate`
86
+ resolver to `createWorker`; the default handler refuses work. The resolver must
87
+ validate the session/key, choose the authorized workspace, and enforce budgets.
88
+ Public discovery intentionally reports this skeleton as not ready. Do not
89
+ change that claim until the configured product's client flow is proved.
@@ -39,3 +39,13 @@ Then walk the trail:
39
39
 
40
40
  Regulated proposals are human-approved and never auto-execute. Domain figures are
41
41
  grounded in real records, never fabricated. See `AGENTS.md` for the full contract.
42
+
43
+ ## External-agent readiness
44
+
45
+ Public `/agent-setup.md`, `/llms.txt` and `/.well-known/tangle-agent.json` describe
46
+ this skeleton's readiness truthfully. The default `/chat` fails closed with
47
+ 503 `auth.not_configured`. Install a trusted `HeadlessAuth.authenticate`
48
+ resolver through `createWorker` before enabling it. Never derive identity from
49
+ request-body userId/workspaceId. Update the public contract only after proving
50
+ real authentication, authorization, spending and results. Use the default chat
51
+ template for the assembled local-key operator API and browser owner setup.
@@ -0,0 +1,20 @@
1
+ import { createAgentSurfaceHandler, renderAgentSetupSkill, type AgentSurfaceConfig } from '@tangle-network/agent-app/agent-surfaces'
2
+
3
+ /** The headless skeleton must not advertise customer readiness before auth exists. */
4
+ export function agentSurfaces(origin: string) {
5
+ const product: AgentSurfaceConfig = {
6
+ id: '__PACKAGE_NAME__', name: '__PROJECT_NAME__', origin,
7
+ summary: 'A headless tool-loop development skeleton. External-agent operation is disabled until the product installs trusted authentication and workspace authorization.',
8
+ useWhen: ['Develop a domain tool-loop application; use the default chat template for a ready local-key operator API.'],
9
+ signup: { kind: 'manual', steps: ['Ask the product operator to configure authentication and authorization. This skeleton does not issue keys or accept Tangle Platform keys. Do not send account credentials or work to /chat before the operator enables a trusted identity resolver.'] },
10
+ apiKeyEnv: 'AGENT_APP_API_KEY', prerequisites: ['A product operator who has completed production authentication'], install: [], firstCall: [], verify: [],
11
+ errors: [{ symptom: '503 auth.not_configured', cause: 'No trusted server-side identity resolver is installed', fix: 'The developer must wire one; request-body userId/workspaceId never authorize access.' }],
12
+ pricing: { summary: 'Not ready for customer work. When enabled by the operator, model calls use the configured provider credentials and can incur charges.' },
13
+ next: [], manifest: { ready: false, operator_api: null, auth: { kind: 'not_configured' }, capabilities: [] },
14
+ }
15
+ const handler = createAgentSurfaceHandler(product)
16
+ return { ...handler, handle(request: Request) {
17
+ if (new URL(request.url).pathname === '/llms-full.txt' && ['GET', 'HEAD'].includes(request.method)) return new Response(request.method === 'HEAD' ? null : renderAgentSetupSkill(product), { headers: { 'content-type': 'text/plain; charset=utf-8' } })
18
+ return handler.handle(request)
19
+ } }
20
+ }
@@ -11,11 +11,11 @@
11
11
  * fail-closed to the approval queue (never auto-executed). You extend the route;
12
12
  * you do not edit `@tangle-network/agent-app`.
13
13
  *
14
- * Replace the system-prompt assembly + per-turn context recovery with your real
15
- * auth/session once you have one. Keep the human-in-the-loop invariant: regulated
14
+ * Install a trusted HeadlessAuth resolver before enabling customer work. Keep the human-in-the-loop invariant: regulated
16
15
  * proposals stay proposals.
17
16
  */
18
17
 
18
+ import { agentSurfaces } from './agent-surfaces'
19
19
  import { config } from '../agent.config'
20
20
  import { createAgentApp, type AppBindings } from './agent-app'
21
21
  import {
@@ -36,10 +36,6 @@ import {
36
36
 
37
37
  interface ChatRequest {
38
38
  message: string
39
- /** Trusted server-side in a real app; taken from the body here for the skeleton. */
40
- userId?: string
41
- workspaceId?: string
42
- threadId?: string | null
43
39
  }
44
40
 
45
41
  /**
@@ -72,13 +68,22 @@ function buildSystemPrompt(): string {
72
68
  return fragments.join('\n\n')
73
69
  }
74
70
 
75
- export default {
71
+ /** A product installs this server-side resolver; body identities are never trusted. */
72
+ export interface HeadlessAuth {
73
+ authenticate(request: Request, env: AppBindings): Promise<AppToolContext | null>
74
+ }
75
+ export function createWorker(auth?: HeadlessAuth) { return {
76
76
  async fetch(request: Request, env: AppBindings): Promise<Response> {
77
+ const surface = agentSurfaces(new URL(request.url).origin).handle(request)
78
+ if (surface) return surface
77
79
  const url = new URL(request.url)
78
80
  if (url.pathname !== '/chat' || request.method !== 'POST') {
79
81
  return new Response('Not found', { status: 404 })
80
82
  }
81
83
 
84
+ if (!auth) return Response.json({ error: 'Authentication is not configured', code: 'auth.not_configured' }, { status: 503 })
85
+ const ctx = await auth.authenticate(request, env)
86
+ if (!ctx) return Response.json({ error: 'Unauthorized' }, { status: 401 })
82
87
  const body = (await request.json()) as ChatRequest
83
88
  if (!body.message) {
84
89
  return new Response(JSON.stringify({ error: 'message is required' }), {
@@ -89,14 +94,6 @@ export default {
89
94
 
90
95
  const app = createAgentApp(env)
91
96
 
92
- // Trusted per-turn context. In production recover this from your auth/session,
93
- // NEVER from model tool args — the model must not be able to forge identity.
94
- const ctx: AppToolContext = {
95
- userId: body.userId ?? 'anonymous',
96
- workspaceId: body.workspaceId ?? 'default',
97
- threadId: body.threadId ?? null,
98
- }
99
-
100
97
  const executor = createAppToolRuntimeExecutor({
101
98
  handlers: app.handlers,
102
99
  taxonomy: app.taxonomy,
@@ -125,4 +122,6 @@ export default {
125
122
  { headers: { 'Content-Type': 'application/json' } },
126
123
  )
127
124
  },
128
- }
125
+ } }
126
+
127
+ export default createWorker()
@@ -0,0 +1,20 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import worker, { createWorker } from '../src/worker'
3
+ import type { AppBindings } from '../src/agent-app'
4
+
5
+ const env = {} as AppBindings
6
+
7
+ describe('headless external-agent boundary', () => {
8
+ it('serves discovery without credentials but never trusts request-body identity', async () => {
9
+ const manifest = await worker.fetch(new Request('https://product.example/.well-known/tangle-agent.json'), env)
10
+ expect(manifest.status).toBe(200)
11
+ expect((await manifest.json() as { ready: boolean }).ready).toBe(false)
12
+ const response = await worker.fetch(new Request('https://product.example/chat', {
13
+ method: 'POST', headers: { 'content-type': 'application/json' },
14
+ body: JSON.stringify({ message: 'run', userId: 'owner', workspaceId: 'other-owner' }),
15
+ }), env)
16
+ expect(response.status).toBe(503)
17
+ const denied = createWorker({ authenticate: async () => null })
18
+ expect((await denied.fetch(new Request('https://product.example/chat', { method: 'POST', body: '{}' }), env)).status).toBe(401)
19
+ })
20
+ })
@@ -5,6 +5,10 @@
5
5
  # The scaffolder replaces this placeholder only in the new local .dev.vars.
6
6
  BETTER_AUTH_SECRET=REPLACE_WITH_RANDOM_SECRET
7
7
 
8
+ # Required for authenticated durable turn locking. Set a separate random secret
9
+ # locally and with wrangler secret put TURN_STREAM_AUTH_SECRET in production.
10
+ TURN_STREAM_AUTH_SECRET=
11
+
8
12
  # Tangle Router key the harness bills model calls against.
9
13
  TANGLE_API_KEY=
10
14
  # Optional router override; omit for the platform default.
@@ -46,3 +46,15 @@ That proof checks real auth and thread persistence across a Worker restart, but
46
46
  For deployment, complete environment configuration, apply the required database migrations, and exercise the actual page and turn flow.
47
47
  Record hosted/model/disconnect proofs separately; do not claim them from compilation or an injected producer.
48
48
  Fix failures without weakening the protected behavior.
49
+
50
+ Customer agents discover `/agent-setup.md` and `/api/operator/v1`; this file is
51
+ only the coding-agent contract. Keep the public docs, key scopes and actual
52
+ operator capabilities aligned. Never advertise Platform signup, durable async
53
+ admission, safe artifact bytes, MCP, or A2A unless their implementations exist.
54
+ Capped keys must not bypass spending enforcement through the operator adapter.
55
+
56
+ External-agent execution is disabled by default (`OPERATOR_RUN_ENABLED="false"`).
57
+ Account signup and an account owner selecting a scope do not authorize spending
58
+ the deployment payer’s funds. Before explicitly enabling `"true"`, the deployment
59
+ payer must review signup/access controls, funding and admission policy. Read-only
60
+ keys continue to work. Previously issued run keys are denied while disabled.
@@ -19,7 +19,7 @@ Discovery: **Which real model answers, on which harness?**
19
19
  - [ ] Set `model.default` to a model your Tangle Router key can reach.
20
20
  - [ ] Set `gateway.maxProviderInputTokens` to its full input limit, including retained tool and sidecar history.
21
21
  - [ ] Choose a compatible harness. Vendor-locked harnesses must use their provider's models.
22
- - [ ] Review fallbacks and the optional `MODEL_NAME` environment override.
22
+ - [ ] Review the optional `MODEL_NAME` override. Detached automatic failover is disabled; fallback candidates require a separately verified non-admission/reconciliation policy.
23
23
  - [ ] Keep unavailable model, effort, profile, and plan-mode controls hidden. Add a display catalog and real callbacks only when your server can honor them. Resolve prompts, tools, permissions, connections, resources, and backend policy server-side. Profile authoring belongs in settings, not a new composer picker.
24
24
 
25
25
  The existing per-turn model/effort wire remains available. The template does
@@ -102,3 +102,46 @@ thread persistence in Chromium, including a process restart, without model calls
102
102
  Record local build, injected-producer, browser/D1, hosted, live-model, and live
103
103
  reconnect results separately. An unrun hosted/model proof stays unrun. Deploy
104
104
  and apply remote migrations only after the product is configured and verified.
105
+
106
+ ## External-agent onboarding
107
+
108
+ - [ ] Fetch `/agent-setup.md`, `/llms.txt`, `/llms-full.txt`, `/agent-api.md` and
109
+ `/.well-known/tangle-agent.json` without a cookie. Check the configured public origin.
110
+ - [ ] Use `/?view=api-access` as a new and existing owner. Issue a read-only
111
+ expiring key, discover its workspace, revoke it, and confirm 401.
112
+ - [ ] Grant run access deliberately; verify read-only, cross-owner and capped
113
+ requests fail before execution. Operator work uses deployment credentials.
114
+ - [ ] Submit one client-generated UUID, repeat it after an ambiguous response,
115
+ and verify one persisted turn. Read its settled state and actual output.
116
+ - [ ] Configure product-owned safe artifact adapters when needed. Verify bytes
117
+ and hashes rather than filenames; unsupported capabilities must stay absent.
118
+ - [ ] Exercise a pending owner decision; an external key cannot decide it.
119
+
120
+ External-agent execution is disabled by default (`OPERATOR_RUN_ENABLED="false"`).
121
+ Account signup and an account owner selecting a scope do not authorize spending
122
+ the deployment payer’s funds. Before explicitly enabling `"true"`, the deployment
123
+ payer must review signup/access controls, funding and admission policy. Read-only
124
+ keys continue to work. Previously issued run keys are denied while disabled.
125
+
126
+ All browser and API turns use the shared `TurnStreamDO` workspace lock. Configure
127
+ `TURN_STREAM_AUTH_SECRET` in local development and production; missing lock
128
+ configuration fails closed before model work. Apply the Wrangler Durable Object
129
+ migration when upgrading. A stuck lock needs reconciliation of the existing turn,
130
+ not an automatic retry of uncertain effects. Draft text is not terminal evidence.
131
+
132
+ Detached execution disables automatic model failover: losing observation before
133
+ visible output does not prove the previous backend refused its work. A real
134
+ backend result/done is required to release the workspace lock and interpret the
135
+ stream status as terminal. Transport loss or EOF retains unknown state and the
136
+ lock until an operator reconciles the exact backend execution.
137
+
138
+ ### Recovery after lost observation
139
+
140
+ A workspace conflict names the original backend execution and thread. The
141
+ scaffold does not automatically release an uncertain detached execution or
142
+ provide an external-agent recovery endpoint. A production recovery adapter must
143
+ query that exact backend execution (a missing box, empty transcript or elapsed
144
+ time is insufficient), then use `/turn-stream`’s `releaseDurableTurnLock` with
145
+ the held executionId and lockId. Its authorization remains deployment-owned.
146
+ This is a supported typed adapter requirement, not database surgery or automatic
147
+ resubmission. Retained operator UUIDs continue to identify their original work.
@@ -103,3 +103,52 @@ implied by a local build or no-model browser proof.
103
103
  workspace. It returns metadata or `warming`, never provisions a sandbox, and
104
104
  has no file-download behavior. Reopening saved bytes requires a product-owned,
105
105
  authorized file reader. Preserve the server access checks and storage semantics.
106
+
107
+ ## External agents
108
+
109
+ This product serves `/agent-setup.md`, `/llms.txt`, `/llms-full.txt`,
110
+ `/agent-api.md` and `/.well-known/tangle-agent.json` without login. These are
111
+ customer-facing instructions; `AGENTS.md` is for agents developing this repo.
112
+
113
+ Sign in to `/?view=api-access` to create an expiring key. Existing accounts and
114
+ keys are reused. Read-only access is available by default. Only after the deployment
115
+ payer enables execution may an account owner grant `operator:run`
116
+ when the agent may use the deployment's paid model/sandbox credentials
117
+ and modify workspace files. Keys are scoped and revocable. This template does
118
+ not automatically accept Tangle Platform keys or register a Platform product.
119
+
120
+ `/api/operator/v1` exposes the shared operator contract over the existing
121
+ personal workspace and transcript. It reports actual optional capabilities,
122
+ returns persisted terminal results, and keeps owner decisions in the browser.
123
+ The chat-backed start request normally runs until settlement; it does not
124
+ promise durable asynchronous admission. Capped keys are refused for execution,
125
+ rather than bypassing their caps through the browser path.
126
+
127
+ There is no default safe artifact-byte reader. `/api/files` is metadata only.
128
+ Products can supply the typed `files`/`assets` adapters to `buildOperatorApi`
129
+ for owned, bounded storage. Only configured capabilities are advertised.
130
+ Never implement root confinement with a separate symlink check and file read.
131
+
132
+ External-agent execution is disabled by default (`OPERATOR_RUN_ENABLED="false"`).
133
+ Account signup and an account owner selecting a scope do not authorize spending
134
+ the deployment payer’s funds. Before explicitly enabling `"true"`, the deployment
135
+ payer must review signup/access controls, funding and admission policy. Read-only
136
+ keys continue to work. Previously issued run keys are denied while disabled.
137
+
138
+ All browser and API turns use the shared `TurnStreamDO` workspace lock. Configure
139
+ `TURN_STREAM_AUTH_SECRET` in local development and production; missing lock
140
+ configuration fails closed before model work. Apply the Wrangler Durable Object
141
+ migration when upgrading. A stuck lock needs reconciliation of the existing turn,
142
+ not an automatic retry of uncertain effects. Draft text is not terminal evidence.
143
+
144
+ Historical turns without a retained stream-status identity intentionally report
145
+ `unknown`; transcript text alone cannot establish completion. Inspect/reconcile
146
+ the original execution rather than rerunning uncertain effects. Workspace locks
147
+ do not auto-expire: a crashed detached run stays blocked until cooperative release
148
+ or operator reconciliation establishes that the backend has stopped.
149
+
150
+ Detached execution disables automatic model failover: losing observation before
151
+ visible output does not prove the previous backend refused its work. A real
152
+ backend result/done is required to release the workspace lock and interpret the
153
+ stream status as terminal. Transport loss or EOF retains unknown state and the
154
+ lock until an operator reconciles the exact backend execution.
@@ -29,7 +29,16 @@ watch_dir = ["web", "vite.config.mjs", "tailwind.config.mjs"]
29
29
  # Never let an asset or HTML fallback swallow an API/gateway request.
30
30
  [assets]
31
31
  directory = "dist/client"
32
- run_worker_first = ["/api/*", "/v1/*"]
32
+ binding = "ASSETS"
33
+ run_worker_first = ["/", "/api/*", "/v1/*"]
34
+
35
+ [[durable_objects.bindings]]
36
+ name = "TURN_STREAM"
37
+ class_name = "TurnStreamDO"
38
+
39
+ [[migrations]]
40
+ tag = "v1-turn-lock"
41
+ new_sqlite_classes = ["TurnStreamDO"]
33
42
 
34
43
  # D1 holds everything durable: auth, threads/messages, the turn buffer.
35
44
  # Setup: `wrangler d1 create __PACKAGE_NAME__`, paste the database_id, then
@@ -57,5 +66,7 @@ fallthrough = true
57
66
  # BETTER_AUTH_SECRET, TANGLE_API_KEY, SANDBOX_API_KEY, SANDBOX_GATEWAY_URL.
58
67
  # See .dev.vars.example for the full list.
59
68
  [vars]
69
+ # Enable only after the deployment payer reviews signup, funding and run policy.
70
+ OPERATOR_RUN_ENABLED = "false"
60
71
  BETTER_AUTH_URL = "http://localhost:8787"
61
72
  # MODEL_NAME = "REPLACE_WITH_MODEL" # overrides config.model.default
@@ -35,14 +35,11 @@ export const config = {
35
35
  */
36
36
  default: 'REPLACE_WITH_MODEL',
37
37
  /**
38
- * Models to try, in order, when the chosen model's upstream is DEAD
39
- * (quota wall, 502, provider outage). Failover is reactive — zero cost
40
- * until the preferred model actually fails — and every fallback is
41
- * surfaced: the persisted row and billing receipt name the model that
42
- * actually served, and the transcript gets a visible notice. Keep this
43
- * list cross-provider (an outage usually takes a whole provider down)
44
- * and review it with your default: a stale ladder degrades to today's
45
- * behavior (the turn fails), never to a silent wrong-model answer.
38
+ * Candidate fallback models for a product with verified retry admission.
39
+ * The generated detached sandbox lane disables automatic failover because
40
+ * transport loss is not proof the first backend stopped doing work.
41
+ * This list is inert until the product wires a policy that proves a failed
42
+ * attempt was never admitted or has actually stopped. Review it before use.
46
43
  */
47
44
  fallbacks: ['gemini-3.7-flash', 'glm-5.3'],
48
45
  /** Default reasoning effort for turns that don't specify one. */
@@ -0,0 +1,10 @@
1
+ -- Durable duplicate suppression across Worker isolates. A lost admission is
2
+ -- never retried automatically; inspect its persisted transcript/state first.
3
+ CREATE TABLE IF NOT EXISTS operator_turn_admissions (
4
+ owner_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
5
+ turn_id TEXT NOT NULL,
6
+ thread_id TEXT NOT NULL,
7
+ created_at INTEGER NOT NULL,
8
+ refusal_json TEXT,
9
+ PRIMARY KEY (owner_id, turn_id)
10
+ );
@@ -0,0 +1,3 @@
1
+ -- Link the retained user turn to the existing authoritative stream status.
2
+ ALTER TABLE message ADD COLUMN turn_stream_id TEXT;
3
+ ALTER TABLE message ADD COLUMN backend_terminal INTEGER NOT NULL DEFAULT 0;
@@ -0,0 +1,47 @@
1
+ import { createAgentSurfaceHandler, renderAgentSetupSkill, type AgentSurfaceConfig } from '@tangle-network/agent-app/agent-surfaces'
2
+ import { operatorOpenApi } from './openapi'
3
+ import { config } from '../agent.config'
4
+
5
+ /** Public customer docs, separate from the repository's coding-agent AGENTS.md. */
6
+ export function agentSurfaces(origin: string, runEnabled = false) {
7
+ const api = `${origin}/api/operator/v1`
8
+ const product: AgentSurfaceConfig = {
9
+ id: '__PACKAGE_NAME__', name: config.name, origin,
10
+ summary: `A personal agent workspace with persisted conversations. External agents use scoped local API keys to discover the workspace and inspect results. ${runEnabled ? 'The deployment payer has enabled task submission.' : 'External-agent execution is disabled by default; account signup does not grant permission to spend deployment resources.'}`,
11
+ useWhen: [runEnabled ? 'Delegate work to this workspace while keeping its conversation and owner approval boundaries.' : 'Inspect the owner’s existing workspace and results with read-only access.'],
12
+ signup: { kind: 'manual', steps: [
13
+ `Open ${origin}/?view=api-access. Sign in to your existing account, or create an account there. Account passwords stay in the browser.`,
14
+ `Create an expiring operator:read key. ${runEnabled ? 'The deployment payer has enabled execution; starting work also needs owner-granted operator:run. Review the cost notice.' : 'Run access is unavailable until the deployment payer enables it; creating an account does not authorize spending.'} Copy the key once into your agent’s secret storage. Reuse an existing unexpired key instead of creating another account or key.`,
15
+ 'This deployment uses its own ak_ keys. Tangle Platform keys are not accepted unless the product owner separately installs and verifies that integration. Revoke access from the same API access page.',
16
+ ] },
17
+ openapi: `${origin}/openapi.json`,
18
+ apiKeyEnv: 'AGENT_APP_API_KEY', prerequisites: ['curl', 'an account and an owner-approved local API key'], install: [],
19
+ firstCall: [{ title: 'Discover your actual capabilities and scopes', language: 'bash', code: `curl --fail-with-body -H "Authorization: Bearer $AGENT_APP_API_KEY" ${api}`, expect: 'JSON containing app.capabilities and principal.scopes. Missing capabilities are unsupported, not implied.' }],
20
+ verify: [{ title: 'Resolve the workspace you are allowed to use', language: 'bash', code: `curl --fail-with-body -H "Authorization: Bearer $AGENT_APP_API_KEY" ${api}/workspaces`, expect: 'The authenticated owner’s personal workspace. Use its id, never an id guessed from another user.' }],
21
+ errors: [
22
+ { symptom: '403 operator.execution_disabled', cause: 'The deployment payer has not enabled operator execution', fix: 'Use read-only access. An account owner cannot opt the deployment into paying for automation.' },
23
+ { symptom: '401', cause: 'Missing, revoked, expired or invalid local key', fix: 'Have the owner issue an expiring key through API access; do not retry with a password or Platform key.' },
24
+ { symptom: '403 api_key.insufficient_scope', cause: 'The operation needs a scope the owner did not grant', fix: 'Ask the owner to grant only the required authority.' },
25
+ { symptom: '402 operator.capped_execution_unsupported', cause: 'The browser-backed operator lane cannot enforce a finite key spending cap', fix: 'Do not remove the cap automatically. Ask the owner to choose a supported paid gateway/backend or explicitly authorize deployment-billed operator work.' },
26
+ { symptom: 'unknown turn state', cause: 'The work was claimed but its transcript cannot establish an outcome, including process loss before dispatch', fix: 'Read the same turn again or ask the operator to reconcile it. Never automatically rerun the effects under another UUID.' },
27
+ { symptom: '404', cause: 'The workspace or thread is absent or belongs to someone else', fix: 'Use the workspace and thread ids returned to this key.' },
28
+ { symptom: '429', cause: 'Shared per-key request quota is exhausted', fix: 'Respect Retry-After and back off across all clients sharing this key.' },
29
+ { symptom: '501 operator.unsupported', cause: 'The deployment has not configured the optional capability', fix: 'Stop; do not substitute a browser/private endpoint to bypass the contract.' },
30
+ { symptom: '503 operator.approvals_unavailable', cause: 'Pending decisions could not be established', fix: 'Treat approval state as unknown. Retry later or ask the owner to open the thread.' },
31
+ ],
32
+ pricing: { summary: 'Operator turns use the deployment’s configured model and sandbox credentials, like browser turns. They may incur provider charges; this scaffold does not sell credit or promise free usage. Finite-cap keys cannot run through the operator lane. Obtain the owner’s budget approval before paid work.' },
33
+ next: [{ label: 'Task lifecycle and result verification', url: `${origin}/agent-api.md` }],
34
+ manifest: { operator_api: config.gateway.enabled ? api : null, ready: config.gateway.enabled, auth: { kind: 'local_api_key', prefix: 'ak_', owner_setup: `${origin}/?view=api-access`, scopes: runEnabled ? ['operator:read', 'operator:run'] : ['operator:read'], finite_expiry_required: true },
35
+ task_execution: runEnabled ? 'request_driven_until_settlement' : 'disabled', optional_capabilities: 'Read app.capabilities from the authenticated operator API. No default artifact-byte reader, MCP server, A2A task API or Platform signup is advertised.' },
36
+ }
37
+ const docs = `# ${config.name}: external-agent API\n\nBase: ${api}. Send Authorization: Bearer using AGENT_APP_API_KEY. Never paste a raw key into a prompt, URL, shell history or log.\n\n## Submit and verify work\n\n${runEnabled ? 'The deployment payer has enabled task submission.' : 'Execution is disabled. Only read operations are available; the lifecycle below applies after the deployment payer explicitly enables OPERATOR_RUN_ENABLED following a funding and signup-policy review.'}\n\n1. GET the base and /workspaces. Read scopes and capabilities. The scaffold has one personal workspace; it cannot create additional workspaces.\n2. Generate a UUID turnId, save it before sending, then POST /workspaces/{workspaceId}/turns with JSON {"turnId":"<UUID>","content":"<owner-authorized objective>"}. Add threadId only to continue a returned conversation. A retry MUST use the same turnId. Reusing that UUID with changed content returns the original work and never executes the changed payload; a different explicit threadId conflicts. A concurrent or interrupted admission can return unknown before its transcript exists. Do not generate another UUID automatically. Lost observation can retain the workspace lock; conflict responses name the backend execution and thread. Recovery needs a deployment-owned adapter that verifies exact backend termination and uses the shared fenced release API. This template has no external-agent recovery endpoint or automatic resume. Transport failure does not prove the work never started.\n3. Apply migrations 0004_operator_admissions.sql and 0005_turn_stream_identity.sql when upgrading an existing generated app. This chat adapter drives the existing stream and the start request normally remains open until settlement. It is not a durable asynchronous job-admission guarantee. Preserve the returned threadId and turnId.\n4. GET /workspaces/{workspaceId}/threads/{threadId}/turns/{turnId}?wait=25. Only succeeded or failed is terminal. Historical user anchors without a retained stream-status identity remain unknown until reconciled. An explicit refusal before a stream opens is retained as failed; after correcting its cause, obtain authorization before a new attempt with a new UUID. queued, working, input-required and unknown are not success. Inspect failure and reply, not HTTP 202 alone.\n5. GET /workspaces/{workspaceId}/approvals to inspect owner decisions. Open each returned url for the owner. No operator route grants human approval, publishes, or answers a held decision. An unavailable approval source is an error, not an empty success. The default adapter refuses a workspace-wide scan beyond 100 conversations rather than silently omitting older decisions; such products need a durable approval index. History beyond 999 rows requires a paginated product adapter.\n6. When files.read or assets.read is advertised, retrieve /workspaces/{workspaceId}/file?path=<encoded-relative-path> or /workspaces/{workspaceId}/assets/{id} and inspect the returned content. A reply mentioning a filename, /api/files metadata, or a successful connection is not artifact-byte proof. The default template has no safe artifact-byte reader; unsupported calls answer 501.\n\n## Other routes\n\nGET /workspaces/{workspaceId}/threads?limit=50&cursor=<opaque cursor> lists conversations. GET /workspaces/{workspaceId}/threads/{threadId} returns the latest turn and browser link. Read capability discovery before attempting optional files, assets, journal or scorecard operations. There is no MCP or A2A endpoint in this template.\n\n## Ownership and cost\n\nKeys are owner-issued, revocable, scoped and expiring. Identity and workspace authorization come from the server. Starting work requires operator:read and operator:run. A run can modify the owner’s workspace and use provider resources under the deployment’s normal policy. Capped keys fail closed for operator execution. Never remove a cap or approve spending on the owner’s behalf.\n`
38
+ const handler = createAgentSurfaceHandler(product)
39
+ return { ...handler, handle(request: Request) {
40
+ const path = new URL(request.url).pathname
41
+ if ((request.method === 'GET' || request.method === 'HEAD') && path === '/openapi.json') return new Response(request.method === 'HEAD' ? null : JSON.stringify(operatorOpenApi(origin, runEnabled)), { headers: { 'content-type': 'application/json; charset=utf-8' } })
42
+ if ((request.method === 'GET' || request.method === 'HEAD') && (path === '/agent-api.md' || path === '/llms-full.txt')) {
43
+ return new Response(request.method === 'HEAD' ? null : path === '/agent-api.md' ? docs : `${renderAgentSetupSkill(product)}\n${docs}`, { headers: { 'content-type': 'text/markdown; charset=utf-8', 'x-content-type-options': 'nosniff' } })
44
+ }
45
+ return handler.handle(request)
46
+ } }
47
+ }
@@ -22,6 +22,7 @@
22
22
  * later: `@tangle-network/agent-app/teams` + `createChatTables({ workspaceTable })`.
23
23
  */
24
24
 
25
+ import { createDurableTurnLock } from '@tangle-network/agent-app/turn-stream'
25
26
  import { config } from '../agent.config'
26
27
  import { createAppAuth, type AppAuth } from '@tangle-network/agent-app/app-auth'
27
28
  import {
@@ -61,11 +62,14 @@ export interface ChatAppOverrides {
61
62
  /** Server-trusted identity for a private gateway chat assembly. Never read
62
63
  * this value from a request body or header. */
63
64
  trustedUserId?: string
65
+ /** Test seam at the sidecar transport boundary; real route authorization remains active. */
66
+ sidecarConnection?: typeof resolveSidecarConnection
64
67
  }
65
68
 
66
69
  export interface ChatApp {
67
70
  auth: AppAuth
68
71
  store: ChatStore
72
+ turnStore: TurnEventStore
69
73
  routes: ChatTurnRoutes & {
70
74
  /** POST `{ title?, firstMessage? }` → `{ thread }`. */
71
75
  createThread(request: Request): Promise<Response>
@@ -82,6 +86,7 @@ const notFound = () => Response.json({ error: 'Thread not found' }, { status: 40
82
86
  export function buildChatApp(env: AppEnv, overrides: ChatAppOverrides = {}): ChatApp {
83
87
  const db = overrides.db ?? (drizzle(env.DB) as unknown as ChatDatabase)
84
88
  const store = createChatStore(db, { threads, messages })
89
+ const turnStore = overrides.turnStore ?? createD1TurnEventStore(env.DB)
85
90
 
86
91
  const auth = createAppAuth({
87
92
  appName: config.name,
@@ -130,12 +135,51 @@ export function buildChatApp(env: AppEnv, overrides: ChatAppOverrides = {}): Cha
130
135
  return { ok: true, tenantId: user.id, userId: user.id, context: undefined }
131
136
  }
132
137
 
138
+ const durableLock = env.TURN_STREAM && env.TURN_STREAM_AUTH_SECRET
139
+ ? createDurableTurnLock<void>({ namespace: env.TURN_STREAM, auth: { secret: env.TURN_STREAM_AUTH_SECRET }, scopeOf: () => 'workspace',
140
+ onRefused: active => Response.json({ error: { code: 'workspace_turn_in_flight', message: `Execution ${active.executionId} in thread ${active.threadId} still owns this workspace. If observation was lost, the deployment operator must verify that exact backend execution stopped and use a fenced reconciliation adapter; elapsed time or another UUID is not recovery.`, executionId: active.executionId, threadId: active.threadId } }, { status: 409 }),
141
+ })
142
+ : null
143
+ interface Admission { handle: unknown; started: boolean; producer?: ChatTurnRouteProducer; userMessageId?: string }
144
+ const admissions = new Map<string, Admission>()
145
+ const produce = overrides.produce ?? createSandboxProduce(env)
133
146
  const routes = createChatTurnRoutes<void>({
147
+ turnLock: {
148
+ acquire: async args => {
149
+ if (!durableLock) return { acquired: false, response: Response.json({ error: 'Durable turn locking is not configured', code: 'chat.lock_not_configured' }, { status: 503 }) }
150
+ const acquired = await durableLock.acquire(args)
151
+ if (!acquired.acquired) return acquired
152
+ admissions.set(args.executionId, { handle: acquired.handle, started: false })
153
+ return { acquired: true, handle: args.executionId }
154
+ },
155
+ release: async handle => {
156
+ const id = String(handle)
157
+ const admission = admissions.get(id)
158
+ admissions.delete(id)
159
+ if (!admission) return
160
+ if (admission.started && !admission.producer?.terminalObserved?.()) return
161
+ if (admission.userMessageId) await store.updateMessage(admission.userMessageId, { extras: { backendTerminal: true } })
162
+ await durableLock?.release(admission.handle)
163
+ },
164
+ },
134
165
  projectId: appSlug,
135
166
  authorize,
136
167
  store,
137
- turnStore: overrides.turnStore ?? createD1TurnEventStore(env.DB),
138
- produce: overrides.produce ?? createSandboxProduce(env),
168
+ turnStore,
169
+ beforeTurn: async args => {
170
+ const admission = admissions.get(args.executionId)
171
+ if (args.userMessageId) {
172
+ if (admission) admission.userMessageId = args.userMessageId
173
+ await store.updateMessage(args.userMessageId, { extras: { turnStreamId: args.turnStreamId, backendTerminal: false } })
174
+ }
175
+ },
176
+ produce: async args => {
177
+ const admission = admissions.get(args.executionId)
178
+ if (!admission) throw new Error('Turn admission is unavailable')
179
+ admission.started = true
180
+ admission.producer = await produce(args)
181
+ return admission.producer
182
+ },
139
183
  interactions: {
140
184
  resolveConnection: async ({ request, intent, body }) => {
141
185
  const session = await requireUser(request)
@@ -147,11 +191,11 @@ export function buildChatApp(env: AppEnv, overrides: ChatAppOverrides = {}): Cha
147
191
  : (new URL(request.url).searchParams.get('threadId') ?? '')
148
192
  const thread = await store.getThread(threadId)
149
193
  if (!thread || thread.workspaceId !== user.id) return { ok: false, response: notFound() }
150
- const connection = await resolveSidecarConnection(env, {
194
+ const connection = await (overrides.sidecarConnection ?? resolveSidecarConnection)(env, {
151
195
  workspaceId: user.id,
152
196
  userId: user.id,
153
197
  threadId,
154
- })
198
+ }, { readOnly: intent === 'list' })
155
199
  if (!connection) return { ok: false, unavailable: 'SANDBOX_UNAVAILABLE' }
156
200
  return { ok: true, connection }
157
201
  },
@@ -210,6 +254,7 @@ export function buildChatApp(env: AppEnv, overrides: ChatAppOverrides = {}): Cha
210
254
  return {
211
255
  auth,
212
256
  store,
257
+ turnStore,
213
258
  routes: { ...routes, createThread, listThreads, threadMessages },
214
259
  upload,
215
260
  }
@@ -69,4 +69,4 @@ export const verifications = sqliteTable('verifications', {
69
69
 
70
70
  // ── chat tables (shell-owned columns) ───────────────────────────────────────
71
71
 
72
- export const { threads, messages } = createChatTables()
72
+ export const { threads, messages } = createChatTables({ messageExtraColumns: { turnStreamId: text('turn_stream_id'), backendTerminal: integer('backend_terminal', { mode: 'boolean' }).notNull().default(false) } })
@@ -6,7 +6,14 @@
6
6
  * `.dev.vars.example` for the full list with comments.
7
7
  */
8
8
 
9
+ import type { TurnStreamNamespaceLike } from '@tangle-network/agent-app/turn-stream'
10
+
9
11
  export interface AppEnv {
12
+ /** Shared durable workspace single-flight lock, used by every chat entrypoint. */
13
+ TURN_STREAM?: TurnStreamNamespaceLike
14
+ TURN_STREAM_AUTH_SECRET?: string
15
+ /** Compiled same-origin browser assets. */
16
+ ASSETS?: { fetch(request: Request): Promise<Response> }
10
17
  /** D1 database — run `migrations/` against it before first boot. */
11
18
  DB: D1Database
12
19
 
@@ -15,6 +22,9 @@ export interface AppEnv {
15
22
  /** better-auth HMAC secret (secret; set in .dev.vars / `wrangler secret`). */
16
23
  BETTER_AUTH_SECRET: string
17
24
 
25
+ /** Deployment payer opt-in. Public account signup never grants this authority. */
26
+ OPERATOR_RUN_ENABLED?: 'true' | 'false'
27
+
18
28
  /** Overrides `config.model.default` without a redeploy. */
19
29
  MODEL_NAME?: string
20
30
  /** Tangle Router key the harness bills model calls against. */
@@ -5,6 +5,8 @@
5
5
  * the sandbox turn, transcript, replay buffer, and failure handling.
6
6
  */
7
7
 
8
+ import { OPERATOR_API_SCOPES, OPERATOR_SCOPE_DEPENDENCIES } from '@tangle-network/agent-app/operator'
9
+ import { buildOperatorApi, type OperatorAppOptions } from './operator'
8
10
  import { config } from '../agent.config'
9
11
  import { streamChatRouteAsSandboxEvents } from '@tangle-network/agent-app/chat-routes'
10
12
  import {
@@ -23,7 +25,7 @@ import { buildChatApp, type ChatApp } from './chat'
23
25
  import type { AppEnv } from './env'
24
26
  import { appSlug } from './sandbox'
25
27
 
26
- export interface GatewayAppOptions {
28
+ export interface GatewayAppOptions extends Pick<OperatorAppOptions, 'files' | 'assets'> {
27
29
  /** Keep the persisted chat turn alive after an API client disconnects. */
28
30
  waitUntil?: (promise: Promise<unknown>) => void
29
31
  /** Test override. Production uses the D1 adapter from agent-gateway. */
@@ -153,11 +155,28 @@ export function buildGatewayApp(
153
155
  })
154
156
 
155
157
  const app = new Hono()
158
+ app.use('/api/keys', async (c, next) => {
159
+ if (c.req.method === 'POST' && env.OPERATOR_RUN_ENABLED !== 'true') {
160
+ const body = await c.req.raw.clone().json().catch(() => null) as { scopes?: unknown } | null
161
+ if (Array.isArray(body?.scopes) && body.scopes.includes('operator:run')) return c.json({ error: 'The deployment payer has not enabled operator execution', code: 'operator.execution_disabled' }, 403)
162
+ }
163
+ await next()
164
+ })
165
+ app.get('/api/keys/access', async c => {
166
+ if (!await sessionUserId(chatApp, c.req.raw)) return c.json({ error: 'Unauthorized' }, 401)
167
+ return c.json({ operatorRunEnabled: env.OPERATOR_RUN_ENABLED === 'true' })
168
+ })
156
169
  app.route('/api/keys', createApiKeyRoutes({
157
170
  store: apiKeys,
158
171
  prefix: 'ak_',
172
+ validScopes: ['chat', ...OPERATOR_API_SCOPES.filter(scope => scope !== 'operator:run' || env.OPERATOR_RUN_ENABLED === 'true')],
173
+ scopeDependencies: env.OPERATOR_RUN_ENABLED === 'true' ? OPERATOR_SCOPE_DEPENDENCIES : {},
174
+ requireExpiryForScopes: OPERATOR_API_SCOPES.filter(scope => scope !== 'operator:run' || env.OPERATOR_RUN_ENABLED === 'true'),
159
175
  getAuthUserId: (request) => sessionUserId(chatApp, request),
160
176
  }))
161
177
  app.route('/v1/agents', gateway)
178
+ const operator = buildOperatorApi(env, chatApp, options)
179
+ app.all('/api/operator/v1', c => operator.handle(c.req.raw))
180
+ app.all('/api/operator/v1/*', c => operator.handle(c.req.raw))
162
181
  return app
163
182
  }