@owlmeans/viable-sdk 0.1.18-rc.2 → 0.1.18-rc.21

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.
Files changed (51) hide show
  1. package/README.md +2 -28
  2. package/agent-meta/manifest.json +16 -0
  3. package/agent-meta/skills/viable-sdk/SKILL.md +463 -0
  4. package/build/api/remote.d.ts +5 -0
  5. package/build/api/remote.d.ts.map +1 -1
  6. package/build/api/remote.js +7 -17
  7. package/build/api/remote.js.map +1 -1
  8. package/build/consts.d.ts +23 -0
  9. package/build/consts.d.ts.map +1 -1
  10. package/build/consts.js +27 -0
  11. package/build/consts.js.map +1 -1
  12. package/build/context/index.d.ts +10 -1
  13. package/build/context/index.d.ts.map +1 -1
  14. package/build/context/index.js +70 -24
  15. package/build/context/index.js.map +1 -1
  16. package/build/executor/shell.d.ts.map +1 -1
  17. package/build/executor/shell.js +17 -5
  18. package/build/executor/shell.js.map +1 -1
  19. package/build/harness/templates.d.ts.map +1 -1
  20. package/build/harness/templates.js +30 -11
  21. package/build/harness/templates.js.map +1 -1
  22. package/build/task/envelope.d.ts.map +1 -1
  23. package/build/task/envelope.js +5 -1
  24. package/build/task/envelope.js.map +1 -1
  25. package/build/tools/catalogue.d.ts.map +1 -1
  26. package/build/tools/catalogue.js +121 -30
  27. package/build/tools/catalogue.js.map +1 -1
  28. package/build/tools/index.d.ts +1 -0
  29. package/build/tools/index.d.ts.map +1 -1
  30. package/build/tools/index.js +1 -0
  31. package/build/tools/index.js.map +1 -1
  32. package/build/tools/mcp.d.ts +2 -10
  33. package/build/tools/mcp.d.ts.map +1 -1
  34. package/build/tools/mcp.js +29 -27
  35. package/build/tools/mcp.js.map +1 -1
  36. package/build/tools/platform.d.ts.map +1 -1
  37. package/build/tools/platform.js +3 -1
  38. package/build/tools/platform.js.map +1 -1
  39. package/build/tools/refusal.d.ts.map +1 -1
  40. package/build/tools/refusal.js +71 -0
  41. package/build/tools/refusal.js.map +1 -1
  42. package/build/tools/stories.d.ts +39 -0
  43. package/build/tools/stories.d.ts.map +1 -0
  44. package/build/tools/stories.js +81 -0
  45. package/build/tools/stories.js.map +1 -0
  46. package/build/tools/types.d.ts +8 -0
  47. package/build/tools/types.d.ts.map +1 -1
  48. package/build/tools/types.js.map +1 -1
  49. package/build/types.d.ts +12 -16
  50. package/build/types.d.ts.map +1 -1
  51. package/package.json +20 -17
package/README.md CHANGED
@@ -12,9 +12,7 @@ needs and the platform cannot supply:
12
12
  both over HTTP and in-process;
13
13
  - **a session runtime** that answers the operations the platform sends: file writes, shell
14
14
  commands and git against a project on the user's own machine;
15
- - **the tool catalogue and the model-task protocol** a parent agent reads — including the
16
- questions the platform puts to a person, and the tools for converting an application that
17
- already exists.
15
+ - **the tool catalogue and the model-task protocol** a parent agent reads.
18
16
 
19
17
  ## The two axes
20
18
 
@@ -74,35 +72,11 @@ throughput problem, it is a corrupted tree.
74
72
  outstanding, including what it had already answered when the connection dropped. Re-running a build
75
73
  because an acknowledgement was lost is exactly the cost that cache avoids.
76
74
 
77
- **A question is the user's, and the connector answers none of it.** An inquiry arrives on the
78
- same operation loop as everything else and is executed by nobody: `next_question` hands it to the
79
- parent to put to a person, and `answer_question` sends the answer back. The two queues stay
80
- separate from the task queue, because draining one list would sooner or later hand a decision
81
- about somebody's project to a subagent. Declining is an answer — a parent whose user is away says
82
- so rather than waiting out the deadline or inventing one.
83
-
84
- **A model task is handed over once.** The platform redelivers every unanswered operation on each
85
- poll, which is free for a slot command the result cache answers and expensive for a task a
86
- subagent is already working on. The shared queue remembers every id it has handed over and ignores
87
- a second delivery of one, while still refreshing the operation the answer must route to.
88
-
89
75
  **A malformed model-task answer is refused locally.** `parseTaskResult` checks the answer against
90
76
  the task before the platform ever sees it — with the subagent's context still open, so the parent
91
77
  can retry immediately. A malformed answer that reached the platform would cost a whole new task, a
92
78
  new subagent and another wait.
93
79
 
94
- **A refusal is phrased from its marker.** The platform's refusal classes live in packages this one
95
- does not depend on, so an error crossing the wire arrives as a marshalled `type|||marker|||stack`
96
- wrapped in a local stack trace. `REFUSALS` maps the marker to one sentence a parent agent can act
97
- on; an unknown marker keeps the marker and names the tool to call next, and no stack ever reaches
98
- the model — including the one shape with no separator in it, where `ResilientError.ensure` swaps a
99
- plain-text response body into `type` and its stack into `message`.
100
-
101
- **A refusal reads the same wherever it is rendered.** The same marker arrives thrown from a call
102
- and stored as text — `job.error`, `slot.lastError`, a conversion's `lastError`, a pipeline row's
103
- `error` — so every one of those goes through `refusalPhrase` too. Anything that is not a refusal,
104
- a build warning above all, is rendered exactly as it stands.
105
-
106
80
  **The harness installer never writes the token.** Each configuration references the environment
107
81
  variable in its own syntax, so what it writes is safe to commit. `tests/harness.spec.ts` greps
108
82
  every written file for a token shape.
@@ -119,7 +93,7 @@ This package ships embedded agent skills under `agent-meta/`. After installing y
119
93
  your project's skill store (`.agents/skills/`):
120
94
 
121
95
  ```sh
122
- npx @owlmeans/agent-skills@^0.1.18-rc.14
96
+ npx @owlmeans/agent-skills@^0.1.18-rc.28
123
97
  ```
124
98
 
125
99
  The embedded files are version-matched to this package release. Do not edit them
@@ -0,0 +1,16 @@
1
+ {
2
+ "schemaVersion": 2,
3
+ "package": "@owlmeans/viable-sdk",
4
+ "version": "0.1.18-rc.21",
5
+ "generatedAt": "2026-09-18T18:24:55.973Z",
6
+ "canonicalRepo": "https://github.com/owlmeans/common",
7
+ "entries": [
8
+ {
9
+ "kind": "skill",
10
+ "name": "viable-sdk",
11
+ "category": "package-specific",
12
+ "file": "skills/viable-sdk/SKILL.md",
13
+ "canonicalPath": ".agents/skills/viable-sdk/SKILL.md"
14
+ }
15
+ ]
16
+ }
@@ -0,0 +1,463 @@
1
+ ---
2
+ name: viable-sdk
3
+ description: How to use @owlmeans/viable-sdk — the connector SDK an external coding agent drives the OwlMeans Viable platform with — the token-authenticated client context, the two host kinds and their tool catalogue, the session operation loop, the local slot executor and local run, the model-task envelope, and the harness installer. Auto-invoked when building or changing a connector, an MCP host, a connector tool, the task envelope, or anything that executes platform slot commands on a developer's machine.
4
+ user-invocable: false
5
+ ---
6
+ <!-- AUTO-GENERATED — do not edit. Regenerate via sync-agent-meta. -->
7
+
8
+ # @owlmeans/viable-sdk
9
+
10
+ **Layer:** Tooling (Node/Bun; not a browser or React package)
11
+ **Install:** `"@owlmeans/viable-sdk": "^0.1.18-rc.21"` in `dependencies`
12
+ **Subpaths:** `.` · `./executor` · `./run` · `./tools` · `./task` · `./harness`
13
+ **Contracts:** `@owlmeans/viable-common` (`./connect`, `./slot`, `./integrity`, and the planning
14
+ vocabulary — story type, story flow, `jobIdOf`) and `@owlmeans/planning` (the planning protocol tree
15
+ and facade) — every name on the wire is declared there, so the SDK and the platform cannot spell one
16
+ differently.
17
+
18
+ Everything a coding agent needs in order to drive the platform: authenticate with one access token,
19
+ attach a session to a project, execute the platform's slot commands against a directory on this
20
+ machine, deliver its model calls to the parent agent, and run the generated application locally.
21
+ `@owlmeans/viable-mcp` is one host built on it.
22
+
23
+ ## Key Exports
24
+
25
+ | Export | Description |
26
+ |--------|-------------|
27
+ | `makeSdkContext({ apiUrl, token, service?, onRejected? })` | A client context authenticated by one token — a literal or a thunk — with the connector protocols and the planning tree bound and the planning client registered |
28
+ | `makeRemoteConnectorApi(context)` | `ConnectorApi` over HTTP; its `planning` is the context's planning client facade |
29
+ | `openSession(opts)` → `SessionRuntime` | One attached session: the operation loop, the task queue, `stats` |
30
+ | `renderTaskEnvelope(task, { harness })` · `parseTaskResult(task, raw)` | What the parent agent is told; what its answer is checked against |
31
+ | `makeModelTaskDriver({ models })` · `TaskDriver` | A reference parent agent backed by a chat model (tests, CLIs) |
32
+ | `installHarness(dir, harness, opts?)` · `describeHarness(harness)` · `WORKING_RULE` | Set a coding agent up; preview it first |
33
+ | `catalogue` · `visibleTools(host)` · `toolByName` · `registerCatalogue(server, deps)` · `serverInstructions({ host })` | The tools and how they reach an MCP server |
34
+ | `renderJob(job)` · `isSettled(job)` | A job as a few lines a model can act on |
35
+ | `resolveStory(deps, projectId, ref)` · `storyQuery(projectId, filter?)` · `renderStories(items, page, total)` · `STORY_ORDER` | The story tools' reading of planning cards |
36
+ | `ToolHostKind` (`Stdio`/`Http`) · `ToolHost` · `ToolDeps` · `anyHost`/`localTarget`/`cloudTarget`/`withExecutor`/`delegatedLlm`/`sessionCapable`/`performsModelTasks` | The host description and the availability predicates |
37
+ | `./executor`: `makeLocalSlotExecutor(dir, opts?)`, `createLocalFileHelper`, `createLocalShellHelper`, `dispatchGitCommand`, `verifyTarget`/`forgetIntegrity`, `targetPaths`/`apiPath`/`webPath`/`workerPath`, `backendEnv`/`frontendEnv`, `classifyTargetHealth`/`readTargetHealth`, `runBootCheck`, `confineToProject`, the spawn helpers | The publisher's job, on somebody's laptop |
38
+ | `./run`: `runLocal`, `stopLocal`, `localStatus`, `createLocalServer`, `startApi`/`startWorker`/`restartApi`/`stopProcess`, `readRun`/`writeRun`/`clearRun` | Building and running the generated app locally |
39
+ | `readMarker`/`writeMarker`/`discoverProject`/`isViableTree` · `readEnv`/`writeEnv`/`envStatus`/`replaceManagedBlock` | The `.viable/connect.json` marker and the managed `.env` block |
40
+ | `SdkError`, `SdkAuthError`, `SdkMisconfigured`, `SdkUnsupported` | Registered `ResilientError` classes |
41
+ | `ENV_TOKEN`, `ENV_API_URL`, `ENV_MCP_URL`, `ENV_TARGET`, `ENV_LLM`, `ENV_HARNESS`, `ENV_PROJECT_DIR` · `DEFAULT_MCP_URL` · `resolveMcpUrl(values)` · `TOOL_DEADLINE_MS` (45 s) · `COMMIT_WAIT_MS` (20 s) · `COMMIT_POLL_SEC` · `STORY_PAGE_SIZE` · `NEXT_TASK_WAIT_MS` · `PULL_WAIT_MS` | Configuration and deadlines |
42
+
43
+ ## One credential, and the routes the server declares
44
+
45
+ `makeSdkContext` registers `makeTokenCarrierGuard` under `DEFAULT_GUARD` and binds the SAME
46
+ immutable `connectProtocols(...)` tree the server mounts, so a path or a schema cannot be right on
47
+ one end and wrong on the other. The planning tree is bound the same way:
48
+ `makePlanningProtocols({ base: { alias: 'viable:manager-api:planning', path: '/planning' }, guards:
49
+ DEFAULT_GUARD, socketBase: <the /update base> })` — manager-api's mount minus its ownership gate, which
50
+ is the server's to apply — followed by `appendPlanningClient(context, { protocols, bind: false, poll:
51
+ COMMIT_POLL_SEC, timeout: TOOL_DEADLINE_MS, schemas: false })`. The base alias and path are literals
52
+ beside the `/update` base for the same reason that one is: they belong to manager-api, and every
53
+ planning alias and path derives from them. No socket opener is passed, so a commit is awaited by long
54
+ poll only, and the schema bundle is not fetched at startup — nothing a tool does reads a flow, and a
55
+ server nobody has asked anything yet makes no call. There is deliberately **no second credential path**: a connector that could
56
+ fall back to another form of authentication is a connector whose access nobody can revoke by
57
+ revoking a token. A literal token that is empty or lacks `CONNECT_TOKEN_PREFIX` is refused locally
58
+ (`SdkMisconfigured` / `SdkAuthError`), because a 401 says nothing about which of several plausible
59
+ mistakes was made and the answer is always the same one.
60
+
61
+ **`token` may be a thunk** (`() => string | Promise<string>`), resolved on every request — what a
62
+ credential holder (`@owlmeans/cli-auth`) hands over, since it is `''` until a browser sign-in
63
+ completes and a real token after, with no reconfiguration. Only a literal is validated eagerly; a
64
+ thunk's value is unknown at construction, and an empty one is simply "not signed in". `onRejected`
65
+ is passed to the carrier guard and fires when the platform 401s the presented token, which is where
66
+ the holder forgets a dead file token (or reports a dead environment one) — see [[auth-token]].
67
+
68
+ **The `/mcp` URL is a value the SDK resolves, never one it derives:** `resolveMcpUrl(values)` returns
69
+ `values[ENV_MCP_URL]` (`VIABLE_MCP_URL`, empty = unset) else `DEFAULT_MCP_URL`
70
+ (`https://api.owlmeans.com/mcp`), trailing slash dropped so a resource URI has one spelling. The
71
+ caller passes the already merged environment + `~/.owlmeans` values (environment wins). A deployment's
72
+ own resource identifier stays host-derived on the server.
73
+
74
+ **The context must also declare the platform's `/update` base itself.** The connector's socket route
75
+ and the planning commit feed hang under that namespace, and a parent an entrypoint registry cannot resolve fails the **whole
76
+ context at init** rather than the one call that would have used it — a server that exited at startup
77
+ with `Entrypoint viable:manager-api:update:base not found`. It is declared with the path the
78
+ platform declares and never binds: it is a namespace, and nothing calls it.
79
+
80
+ **`cfg.webService` names the API CLIENT, never the backend.** It is the alias the entrypoint handler
81
+ looks up with `context.service(...)`, and the only thing registered under it is the `ApiClient` that
82
+ `makeClientContext` appends (`web-client`). Naming the backend service there — which is exactly what
83
+ `addWebService` does — makes every call fail with `Service <backend> not found` before a request is
84
+ sent. The backend belongs in `cfg.services` as an ordinary descriptor marked `default: true`; the
85
+ connect routes name no service of their own, so that is the one they resolve to.
86
+
87
+ **A POST with nothing to say still sends `{}`.** The client sets no `Content-Type` for an absent
88
+ body, and Fastify answers **415 Unsupported Media Type** before the handler runs — an error about
89
+ media types for a call whose only fault was having no arguments. `makeRemoteConnectorApi` fills an
90
+ empty body for any POST route that was given none; `session.close` and `session.heartbeat` are
91
+ exactly that shape.
92
+
93
+ ## Two hosts, one interface
94
+
95
+ `ConnectorApi` is an interface because two implementations must stay interchangeable — one calling
96
+ the API over HTTP (`makeRemoteConnectorApi`, the npx server) and one calling the manager's own
97
+ handlers in process (`makeInProcessConnectorApi` in `viable-manager-api`, behind `POST /mcp`). Every
98
+ tool is written against it, so a tool cannot accidentally work in only one of the two. Which route
99
+ `openSession` calls fixes the mode: the delegated route carries the entitlement gate, so a caller
100
+ without the capability is refused at the boundary rather than by a check somewhere inside.
101
+
102
+ ## A SESSION belongs to a host that stays; `sessionCapable` is what says so
103
+
104
+ A session is a connector ATTACHED — a process that drains the project's operations and holds a model
105
+ task until its answer comes back. The URL-configured host answers one request and forgets, so
106
+ opening one there would claim the project's single connector slot, **supersede the stdio connector
107
+ legitimately holding it**, and be abandoned before the first operation was delivered.
108
+
109
+ So `ensureSession` — what `confirm_project`, `reinitialize_project`, `develop_story`,
110
+ `modify_project` and `resume_pipeline` call before returning their job — opens one only on a
111
+ `sessionCapable` host, and `next_task`/`submit_task_result` are available on `performsModelTasks`
112
+ (delegated **and** session-capable) rather than on the account setting alone. `serverInstructions`
113
+ reads the same predicate: a parent told to call `next_task` when the tool is not in its list is a
114
+ parent that waits for a run nobody will advance. A host that cannot serve the delegated mode says so
115
+ in one sentence instead, naming the stdio connector.
116
+
117
+ The in-process implementation refuses the five session verbs (`openSession`, `closeSession`,
118
+ `heartbeat`, `pullOps`, `submitOp`) with a message naming `@owlmeans/viable-mcp`, because
119
+ "unsupported" alone leaves the reader with nothing to do about it.
120
+
121
+ ## A tool that cannot work in a mode is HIDDEN, not failing
122
+
123
+ `ToolDefinition.availability` and `visibleTools(host)` decide the catalogue a parent actually sees. A
124
+ tool a host cannot serve is a tool the parent tries once, is refused, and remembers as broken — so
125
+ the list it reads is exactly the set of things that work for it. Predicates: `anyHost`,
126
+ `localTarget`, `cloudTarget`, `withExecutor`, `delegatedLlm`.
127
+
128
+ ## 45 seconds is the ceiling, which is why long operations are JOBS
129
+
130
+ Every MCP host bounds a tool call and the strictest default in the field is sixty seconds (Codex).
131
+ `TOOL_DEADLINE_MS` leaves room for the round trip and keeps the connector inside every host's
132
+ ceiling without configuration. A tool that outlives its host's ceiling is reported to the user as a
133
+ **broken server**, and the true answer — the platform was slow — never reaches them.
134
+
135
+ So anything that takes minutes returns a `ConnectJob` at once and is polled with `wait_for`.
136
+ `registerCatalogue` enforces the deadline per call and converts a throw into an `isError` result the
137
+ model can read and act on, because an exception crossing the transport tells it only that something
138
+ went wrong somewhere. `renderJob` ends every job with a single `next:` line — that is what keeps a
139
+ parent from inventing a polling strategy of its own, or from concluding that a blocked run has
140
+ failed.
141
+
142
+ ## The story tools speak planning
143
+
144
+ A user story is a planning CARD of `VIABLE_STORY_TYPE` under its project card, and every change to one
145
+ is a transition executed through `ConnectorApi.planning` — a `PlanningFacade`: the client facade
146
+ `appendPlanningClient` registers over HTTP, and `ensurePlanningService(ctx).for(scope)` in the
147
+ platform's in-process host. The scope a call answers for is the CREDENTIAL's; a tool sends none.
148
+
149
+ | Tool | Facade call |
150
+ |---|---|
151
+ | `list_stories` | `cards.list({ ...storyQuery(project, { status, area }), page, size, sort: STORY_ORDER })` → `renderStories` |
152
+ | `search_stories` | the same with `{ q }` |
153
+ | `create_story` | `execute({ action: create, card: { kind: card, type: VIABLE_STORY_TYPE, parent, title, fields: { primary: false } } }, { wait: true, timeout: COMMIT_WAIT_MS })` |
154
+ | `update_story` | `resolveStory` → `execute({ card, action: update, changes: { title }, expectSeq: head ?? seq }, { wait: true, … })` |
155
+ | `delete_story` | `resolveStory` → `execute({ card, action: delete }, { wait: true, … })` → the project-lock poll |
156
+ | `develop_story` | `resolveStory` → `execute({ card, action: transit, transition: start }, { wait: true, … })`, a `CommitTimeout` tolerated → `project.job(project, jobIdOf(StoryDevelop, project, card.id))` |
157
+ | `story_status` | `resolveStory` → the card's code, status and `fields.warning` |
158
+
159
+ Rules the table rests on:
160
+
161
+ - **A tool NAME is a parent agent's vocabulary and is never renamed**, and neither is an argument:
162
+ `storyId` stays `storyId` although the platform keys on card ids. New facts are added (`designSystem`
163
+ on `confirm_project`, the project status line and the design-system section of `project_status`),
164
+ never substituted.
165
+ - **`storyId` accepts a code or an id**, because `list_stories` prints the CODE — the handle every
166
+ generated file names a story by. `resolveStory` asks for both at once, the id wins, a code is also
167
+ tried uppercased, and neither answers for a story of another project (`ProjectStoryNotFound`).
168
+ - **Development is the story's `start`, not a call of its own.** The platform begins the run once that
169
+ move COMMITS, and refuses it there too (the flow, one story in progress, the balance). The wait is
170
+ `COMMIT_WAIT_MS`, well inside the tool deadline; a late commit is not a failure — the transition is
171
+ durable — so `develop_story` answers from the job row rather than outliving the host's ceiling. The
172
+ job id is composed with viable-common's `jobIdOf`, the one spelling the platform answers under.
173
+ - **A story a person writes goes as written, with no area.** Re-formatting the narrative and deciding
174
+ the area are the platform's, done in its planning middleware for the `connect` channel; a connector
175
+ that guessed an area would be a second answer. `update_story` carries only `title` and the head it
176
+ read, so a change made in between is refused (`WorkcardConflict`) rather than overwritten.
177
+ - **The delete commit is no proof the slot is done.** It says the card is gone and nothing about the
178
+ placeholder screens still being retired under the project lock, so `delete_story` keeps its two
179
+ unlocked observations.
180
+ - **Stories are read in `order`, then `createdAt`**: `order` is the analysis's flow ordinal (a
181
+ connective story sits at a fraction between two steps). `renderStories` keeps the line shape a parent
182
+ already reads — `code · status[ · primary][ · area]` over the narrative — under a header counting the
183
+ page by intrinsic state.
184
+ - **A planning refusal is phrased like any other**: `planning:illegal-transition:`,
185
+ `workcard-conflict:`, `workcard-not-found:`, `fields-invalid:`, `commit-timeout:`, `commit-failed:`
186
+ and the story markers (`viable-project:story:not-found:` / `:missconfigured:`) each have a sentence in
187
+ `REFUSALS`.
188
+
189
+ - **A sign-in refusal is phrased**: `oauth:sign-in-required:` (detail `<url> <code>`, the code absent
190
+ while no device sign-in is pending), `oauth:token-rejected:` (an environment token that was refused
191
+ is never replaced) and `api:auth:guard:auth-token` (a file token the platform refused — forgotten,
192
+ the next call signs in). Each ends with "call this tool again".
193
+
194
+ ## An out-of-credits refusal is phrased, and pushed through `notify`
195
+
196
+ `registerCatalogue`'s catch special-cases `ConnectOutOfCredits` (`@owlmeans/viable-common`
197
+ `connect/errors.ts`): rather than the raw `viable-connect:out-of-credits:...` marker, the tool
198
+ result reads as a sentence — what it needed, what the account has, and a link to top up — because
199
+ only `type` and `message` survive the platform's internal HTTP hop, so those three fields travel
200
+ packed into the message and are read back out with `finalizeUnmarshal()`. The same refusal is also
201
+ handed to the optional `ToolDeps.notify?(level, text)`, which a host wires to its own out-of-band
202
+ channel — the stdio `viable-mcp` host sends an MCP `notifications/message`; the platform's stateless
203
+ `/mcp` host has no channel and omits it, so `notify` is always best-effort and optional. Every other
204
+ error still returns as its own `.message`, unphrased, and never calls `notify`.
205
+
206
+ ## The session loop: serial, and free to redeliver
207
+
208
+ `openSession` pulls operations, answers them **one at a time**, and puts model tasks aside. Serial
209
+ because the thing on the other end of a local operation is a filesystem the platform believes it is
210
+ the only writer of — two concurrent template writes into one tree is not a throughput problem, it is
211
+ a corrupted tree.
212
+
213
+ Results are remembered by operation id. A connector that reconnects is handed everything still
214
+ outstanding, **including whatever it had already answered when the connection dropped**, and the
215
+ cached result answers it without doing the work again — re-executing a build or a model task because
216
+ an acknowledgement was lost is exactly the cost this avoids. A failed `submitOp` is logged, never
217
+ thrown: the operation stays in the platform's store and is redelivered.
218
+
219
+ Model tasks are **not executed here at all** — they are the parent agent's to run in its own clean
220
+ subagent, and what the loop owes them is delivery. The operation id is kept beside each task and
221
+ never shown to the parent: a parent that could name one could answer an operation it was never
222
+ given.
223
+
224
+ A local operation that fails reports `ConnectOpErrorKind.Refused`, never `Unavailable`. The
225
+ connector ran and could not do the thing; `Unavailable` tells the platform to give up on a run that
226
+ is fine.
227
+
228
+ **The pull long-poll is the transport.** It works through every proxy and needs no reconnection
229
+ logic. It is also the only transport a session ever uses — the URL-configured host opens no session
230
+ at all, so it never pulls. The contract declares a socket
231
+ (`connect.session.socket`, served by manager-api) and `SessionStats.transport` can say `'socket'`,
232
+ but **the SDK implements only the pull loop** — `PING_INTERVAL_MS`, `SOCKET_HANDSHAKE_MS` and
233
+ `RECONNECT_BACKOFF_MS` are declared for a socket client that does not exist yet. Treat the socket as
234
+ a platform capability, not an SDK one.
235
+
236
+ ## An answer is READ in the shapes models produce, not only the one asked for
237
+
238
+ The tool-call instruction asks for a JSON array and models mostly comply — but a single call comes
239
+ back as a bare object often enough, and some wrap the array in `{tool_calls: […]}`, that assuming
240
+ the array is a defect rather than strictness. The reference driver cast straight to an array, so a
241
+ bare object threw `parsed.map is not a function`; the TypeError was handed back AS the answer, the
242
+ model ladder read that as a bad answer and asked again with feedback that said nothing about what
243
+ was wrong, and the story failed with `retry-exceeded` having never been told. `toolCallsOf` accepts
244
+ all three shapes and still throws for an answer carrying no call at all — an empty answer is a bad
245
+ answer, and the retry is the right response to it.
246
+
247
+ The same rule is why `parseTaskResult` refuses with a described reason rather than a stack trace:
248
+ whatever comes back becomes a model's next prompt, so it has to be readable by one.
249
+
250
+ ## A redelivered model task must NOT be handed over twice
251
+
252
+ The platform redelivers every unanswered operation on each poll — that is what makes a connector
253
+ restart cost a round trip instead of a run, and for a slot command it is free because the result
254
+ cache answers it. A MODEL task is different: it is answered by a parent agent in tens of seconds,
255
+ and every poll during that window used to queue another copy. The parent then ran the same task
256
+ over and over — real model calls, paid for by the user, thrown away — while the job stayed blocked,
257
+ because only the first answer routed to a live operation and every later one reported that no
258
+ operation was waiting.
259
+
260
+ `TaskQueue` therefore remembers every task id it has handed over and ignores a second delivery of
261
+ one, keeping the memory after the task settles so a redelivery that raced the platform's deletion
262
+ is ignored rather than answered again. The operation id IS refreshed on a redelivery, because the
263
+ answer must route to the operation the platform is currently waiting on. `push` returns whether the
264
+ task was accepted, and `tasksDelivered` counts only accepted ones — a counter that grew per poll
265
+ would make a stuck run look busy.
266
+
267
+ ## The task envelope is text for a model to act on
268
+
269
+ The reader is a language model working from a tool result, so it must be able to act without a
270
+ schema in front of it. Everything it must do is stated **in order and before the material** — how to
271
+ run it (in a clean subagent, per harness), what to call afterwards (`submit_task_result`, with the
272
+ id spelled out), and what shape the answer takes — so a model that stops reading early has still
273
+ read the instruction. The task id appears at the top and in the follow-up call because it is the
274
+ only thing that routes an answer back: a parent that paraphrases the rest but copies the id still
275
+ works. A retry says which attempt it is and why the previous answer was refused. Harnesses differ
276
+ only in the isolation mechanism, never in what is asked; `Other` gets the request stated rather than
277
+ mechanised.
278
+
279
+ For Codex, the parent gives a fresh `viable-worker` only the task's system prompt, then its
280
+ conversation, then the requested result shape: the outer handoff instruction and
281
+ `submit_task_result` call are parent-only. It passes that final response through unchanged, but must
282
+ preserve the mode: a `text` task returns the requested source or text and never a JSON tool-call
283
+ array; that array belongs only to `tools` mode.
284
+
285
+ **`parseTaskResult` refuses a malformed answer locally**, and returns a `problem` rather than
286
+ throwing. The refusal is worth more than the parse: an answer that reaches the platform malformed
287
+ costs a whole retry — another task, another subagent, another wait — while one caught here is a
288
+ sentence the parent can act on immediately, with the subagent's context still open. It unfences,
289
+ rejects an array or a scalar in `Json` mode, and rejects a tool name the task never offered.
290
+
291
+ A task is handed out ONCE, and the platform then waits on it for up to 45 minutes. So the loop has
292
+ to survive a parent that lost the envelope — a compacted conversation, a subagent that died before
293
+ answering. `next_task` takes an optional `taskId` that re-reads a task already handed out, and when
294
+ nothing new is queued but something is unanswered it NAMES the outstanding ids rather than re-handing
295
+ them: re-handing would have a parent whose subagent is still working run the same task twice. A
296
+ refused answer keeps the task outstanding for exactly the same reason.
297
+
298
+ ## The harness installer is idempotent by construction, and never writes the token
299
+
300
+ A section is replaced between `<!-- viable:begin -->` and `<!-- viable:end -->`, a JSON entry is
301
+ merged under its own key, and a file whose content would not change is skipped. An instruction file
302
+ belongs to its project: overwriting it to add a paragraph deletes whatever else was in it, and
303
+ appending unconditionally grows a duplicate on every install. That is what makes `install_harness`
304
+ safe to offer as a tool the agent may call whenever it is unsure. A configuration that is not valid
305
+ JSON is **refused** — somebody is editing it, and overwriting would destroy every other server they
306
+ had configured.
307
+
308
+ **No file it writes contains the token**, and none REQUIRES one: a person who signed in with a browser
309
+ has the token in `~/.owlmeans`, which the server reads itself. So each configuration references
310
+ `VIABLE_API_TOKEN` in its harness's own syntax only where that cannot break a machine that never set
311
+ it — claude-code's `.mcp.json` uses `${VIABLE_API_TOKEN:-}` (an unset `${VAR}` makes Claude Code refuse
312
+ the whole file; the server ignores the empty value), Copilot's `.vscode/mcp.json` has no token prompt
313
+ at all, and Codex's `env_vars` lists `VIABLE_API_TOKEN`, `OWLMEANS_CREDENTIALS` and `HOME` (its filtered
314
+ environment otherwise hides the credentials file). The result is safe to commit. `WORKING_RULE` is written once and rendered
315
+ into every harness's instruction file, so the four cannot drift into four different protocols.
316
+
317
+ **The server command is written once, too.** Every harness configuration starts the connector from
318
+ `MCP_COMMAND` in `src/harness/templates.ts` — viable-mcp through `npx -y`, pinned with a caret at the
319
+ viable-mcp release, on ONE line with its `npx` so the release pin audit reads it as an install
320
+ command and moves it with every viable-mcp bump. Never a tag (`@next` is refused by that audit) and
321
+ never a per-harness literal: three copies spelled `@next` while the fourth carried the pin.
322
+ `tests/harness.spec.ts` asserts all four configurations name the viable-mcp manifest's version, that no
323
+ file contains a `vib_…` secret, and the optional-token shapes above.
324
+
325
+ ## The executor is the publisher's job, on somebody's laptop
326
+
327
+ `makeLocalSlotExecutor(dir)` answers the platform's slot commands against a directory here. The
328
+ dispatcher is the publisher's, switch for switch: the platform's remote helpers parse the ANSWERS
329
+ and cannot tell whether a pod or a laptop produced one, so an ordinary failure comes back in the
330
+ same shape ("error text or null"), and only an unknown command — a protocol fault rather than a
331
+ project fault — escapes as an exception. Everything is resolved per call rather than closed over,
332
+ because a re-initialization replaces the tree under a running connector. The integrity verdict is
333
+ forgotten after every command that changes the tree.
334
+
335
+ Five rules the local half adds, each learned from a defect:
336
+
337
+ - **`backendEnv` reads the root `.env` and `frontendEnv` the web package's own — the file split IS
338
+ the leak boundary.** The publisher has an allow-list (`frontendEnvVars`/`frontendSecrets`); here
339
+ the two files are never merged in either direction, because `FRONTEND_ENV_KEYS` announces
340
+ everything in the frontend set to the bundler and a merge would compile `OIDC_SECRET` and
341
+ `DATABASE_URL` into a bundle every visitor downloads.
342
+ - **`Discard` passes `git clean -fd -e .viable`.** `.viable/connect.json` is untracked until someone
343
+ commits it, and a discard that swept it leaves a tree no later session can recognise as a platform
344
+ project at all.
345
+ - **The always-keep list must not leave empty parent shells.** A wipe keeps `.viable`, `.env`, the
346
+ web package's `.env` and `.git` whatever the caller asked, so a directory holding a kept path is
347
+ walked and pruned rather than removed — and a keep that was not there (the web `.env` every
348
+ project without local branding lacks) must not leave the walked directory behind as a skeleton the
349
+ install then lands in.
350
+ - **An absolute path from elsewhere on the machine is re-rooted inside the project**, not refused —
351
+ the publisher's own behaviour, kept deliberately and pinned by a test. Concatenating it onto the
352
+ root instead builds a shadow tree: the write reports success, a later read of the same name
353
+ resolves to the untouched original, and the change looks silently ignored. `resolveInProject`
354
+ (exported as `confineToProject`) then compares the fully resolved path to the root — confinement,
355
+ not sanitization, and applied on **every** fs call rather than a `..`-to-`.` replace at one caller.
356
+ - **`run/state.ts` sits below both the shell commands and the run**, so the three do not form a
357
+ cycle: `DbSync` bounces the api child, `DbSync` is a shell command, and the shell commands are
358
+ reached through the executor the run is built on. Everything that touches a child process lives
359
+ there, and the run record is a file because the processes outlive the call — and, on a restarted
360
+ connector, the process — that started them.
361
+
362
+ ## Attaching a session is what writes the project marker
363
+
364
+ `.viable/connect.json` is how a connector started in a directory tomorrow knows which project it
365
+ is, and `attach_project` finds a project by its directory through it. It was declared, read at MCP
366
+ startup and documented in `mcp.md` before anything wrote it — a marker nothing writes is a lookup
367
+ that always misses.
368
+
369
+ `openSession` writes it when the session names a project and a directory, which is the moment the
370
+ directory becomes that project's. Best-effort and idempotent: a session that works is worth more
371
+ than a note about it, and it is skipped when the marker already names the same project. It holds
372
+ no secret and is meant to be committed, which is why the API URL and the slug are in it and the
373
+ token never is.
374
+
375
+ ## The managed block yields to every key the user assigned
376
+
377
+ A `.env` gives the LAST assignment of a key and the platform's block is appended, so a platform line
378
+ silently outranks whatever the user wrote above it. That made the documented promise — everything
379
+ outside the block is yours — false for the one value the platform cannot supply: `DATABASE_URL`, the
380
+ line the setup guide tells people to write. The application connected to the placeholder no matter
381
+ what its owner put in the file.
382
+
383
+ `writeEnv` therefore reads the file with the block cut out, and replaces any block line assigning a
384
+ key the user already assigns with a comment saying so. The rule is about VALUES, not lines: a key the
385
+ user has not claimed is still the platform's to set, and a key they later delete goes back to the
386
+ platform on the next push.
387
+
388
+ ## The two services a local project needs are ASKED for, never assumed
389
+
390
+ The platform provisions nothing on somebody's own machine, so a database — and, for a project with a
391
+ worker, a queue store — is the one thing it cannot supply and must not guess. `local_setup_guide`
392
+ reports what the machine already provides and, where something is missing, returns a QUESTION with
393
+ three answers: the user already has one, wants one installed here, or wants a free hosted plan.
394
+ Guessing means either a container on somebody's machine they did not ask for, or a connection string
395
+ invented for a database that does not exist — and the second surfaces minutes later as a boot error
396
+ about a connection, which sends the reader looking for a database rather than for a typo.
397
+
398
+ `set_local_service` records what they answered: it writes the value into the project's own half of
399
+ the `.env`, replacing that key rather than appending a second copy, and PROBES it immediately, so a
400
+ string that does not connect is caught while the user is still in the conversation. A credential
401
+ never reaches the marker, a harness configuration, or the platform, and the guide warns when the
402
+ file is not git-ignored.
403
+
404
+ ## A detached child outlives the connector, so the port is RECLAIMED before it is used
405
+
406
+ Every target process is spawned detached — that is what keeps a build from dying with the tool that
407
+ started it — and detaching is also why a connector killed mid-run (a host restart, a Ctrl-C, a
408
+ crashed test) leaves one alive. What survives holds port 3000, and the next attempt fails with the
409
+ TARGET's own "the api port is already in use", which reads as a defect in the generated app rather
410
+ than as a leftover.
411
+
412
+ Two rules, both ported from the publisher because a laptop needs them more than a pod does:
413
+ - `killGroupAndWait` never returns early on the child's own exit code. The child is a shell wrapping
414
+ `bun`, so a signal the shell dies from leaves `bun` alive while `exitCode` says gone; the wait
415
+ polls the GROUP instead of the child's exit event.
416
+ - `reclaimPort` runs before a spawn as well as after one, and matches on the script AND the process
417
+ marker (`--viable-api`, `--viable-worker`, `--viable-boot-check`) — never a port alone, and never
418
+ a marker alone, since reclaiming sends SIGKILL and a marker on its own matches any command line
419
+ that merely mentions it.
420
+
421
+ ## Running the generated app locally
422
+
423
+ `runLocal` builds and starts the api, the worker (when the project has one) and a local server that
424
+ holds the web port and proxies `/api` to the api process on the same origin — the generated app's
425
+ configuration assumes one origin, and splitting them across two loopback ports would put its CORS
426
+ setup in the path of a developer's first page load. There is no respawn ladder, no reconciler and no
427
+ health route: a developer watching their own terminal is the supervisor. What IS reproduced is the
428
+ shape — the same ports, the same argv marker, the same environment, and the same "port ownership is
429
+ the only proof" rule about restarts. Nothing from the publisher's public-hostname policy (robots,
430
+ CSP, the preview error reporter, the build-state header) is reproduced: a loopback address has no
431
+ reputation to spend and no crawler to answer.
432
+
433
+ `run_local` refuses to start a project whose `.env` is still missing a required key, because an app
434
+ launched without a database URL fails at boot with a message about a connection, which sends the
435
+ reader looking for a database that was never configured.
436
+
437
+ ## Tests
438
+
439
+ `bun test ./tests` — offline: the envelope and its parser, the harness installer, the tool catalogue,
440
+ the `registerCatalogue` out-of-credits and planning-refusal phrasing and `notify` wiring
441
+ (`mcp-catalogue.spec.ts`), the executor's files/git/layout rules, and the marker + managed-`.env`
442
+ block. The story tools run over a REAL `@owlmeans/server-planning` service (memory store, the Viable
443
+ types and flows, one plugin standing in for the platform's format seam) built in `tests/context.ts`;
444
+ `planning-wiring.spec.ts` pins the planning aliases and paths a context binds, and `remote.spec.ts`
445
+ drives the remote facade through a captured transport to pin its deadlines.
446
+
447
+ ## Depends On
448
+
449
+ - `@owlmeans/viable-common` — the whole wire contract · `@owlmeans/auth-token` — the carrier guard
450
+ - `@owlmeans/planning` — the protocol tree, the facade contract and its refusals ·
451
+ `@owlmeans/client-planning` — the remote facade and the long-poll commit wait
452
+ - `@owlmeans/api`, `@owlmeans/client-context`, `@owlmeans/client-entrypoint`, `@owlmeans/client-config`,
453
+ `@owlmeans/auth-common`, `@owlmeans/entrypoint`, `@owlmeans/route`, `@owlmeans/socket`,
454
+ `@owlmeans/config`, `@owlmeans/context`, `@owlmeans/error`, `@owlmeans/basic-ids`
455
+ - `@modelcontextprotocol/sdk` (types only, structurally), `zod`, `fs-extra`, `globby`, `ajv`
456
+
457
+ ## Related
458
+
459
+ - [[viable-mcp]] — the npx stdio server built on this
460
+ - [[auth-token]] — the credential and its carrier guard
461
+ - [[client-planning]] · [[planning]] — the facade the story tools write through
462
+ - `@owlmeans/llm-delegate` (`internal` monorepo, skill `llm-delegate`) — the other end of a model
463
+ task, inside the platform
@@ -18,6 +18,11 @@ export declare const recoverLongPoll: <T>(poll: () => Promise<T>, snapshot: () =
18
18
  * tool that outlives its host's ceiling is reported to the user as a broken server, and the true
19
19
  * answer — the platform was slow — never reaches them. Anything that legitimately takes longer is
20
20
  * a job, and a job returns at once.
21
+ *
22
+ * `planning` is the facade `makeSdkContext` registered with `appendPlanningClient`: its reads and
23
+ * its execute POST carry the same tool deadline, and a commit is awaited by long polls whose HTTP
24
+ * deadline outlasts their own hold by ten seconds. Its scope is empty on purpose — the platform
25
+ * reads the organization and the profile from the token.
21
26
  */
22
27
  export declare const makeRemoteConnectorApi: (context: Ctx) => ConnectorApi;
23
28
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"remote.d.ts","sourceRoot":"","sources":["../../src/api/remote.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AAS3E,OAAO,KAAK,EAAE,YAAY,EAA6C,MAAM,aAAa,CAAA;AAE1F,KAAK,GAAG,GAAG,aAAa,CAAC,YAAY,CAAC,CAAA;AAOtC,4FAA4F;AAC5F,eAAO,MAAM,yBAAyB,UAAW,OAAO,KAAG,OAgB1D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAU,CAAC,QAC/B,MAAM,OAAO,CAAC,CAAC,CAAC,YAAY,MAAM,OAAO,CAAC,CAAC,CAAC,KACjD,OAAO,CAAC,CAAC,CAQX,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,YAAa,GAAG,KAAG,YA0IrD,CAAA"}
1
+ {"version":3,"file":"remote.d.ts","sourceRoot":"","sources":["../../src/api/remote.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AAS3E,OAAO,KAAK,EAAE,YAAY,EAAiC,MAAM,aAAa,CAAA;AAE9E,KAAK,GAAG,GAAG,aAAa,CAAC,YAAY,CAAC,CAAA;AAOtC,4FAA4F;AAC5F,eAAO,MAAM,yBAAyB,UAAW,OAAO,KAAG,OAgB1D,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,GAAU,CAAC,QAC/B,MAAM,OAAO,CAAC,CAAC,CAAC,YAAY,MAAM,OAAO,CAAC,CAAC,CAAC,KACjD,OAAO,CAAC,CAAC,CAQX,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,sBAAsB,YAAa,GAAG,KAAG,YAuHrD,CAAA"}
@@ -1,3 +1,4 @@
1
+ import { planningOf } from '@owlmeans/client-planning';
1
2
  import { connectRef } from '@owlmeans/viable-common';
2
3
  import { TOOL_DEADLINE_MS } from '../consts.js';
3
4
  const TRANSIENT_TRANSPORT_CODES = new Set([
@@ -45,6 +46,11 @@ export const recoverLongPoll = async (poll, snapshot) => {
45
46
  * tool that outlives its host's ceiling is reported to the user as a broken server, and the true
46
47
  * answer — the platform was slow — never reaches them. Anything that legitimately takes longer is
47
48
  * a job, and a job returns at once.
49
+ *
50
+ * `planning` is the facade `makeSdkContext` registered with `appendPlanningClient`: its reads and
51
+ * its execute POST carry the same tool deadline, and a commit is awaited by long polls whose HTTP
52
+ * deadline outlasts their own hold by ten seconds. Its scope is empty on purpose — the platform
53
+ * reads the organization and the profile from the token.
48
54
  */
49
55
  export const makeRemoteConnectorApi = (context) => {
50
56
  return {
@@ -105,23 +111,7 @@ export const makeRemoteConnectorApi = (context) => {
105
111
  : await recoverLongPoll(async () => await read(waitSec), async () => await read(0));
106
112
  },
107
113
  },
108
- story: {
109
- list: async (id, query) => await context.entrypoint(connectRef.story.list).call({
110
- params: { id }, query: query ?? {}, timeout: TOOL_DEADLINE_MS,
111
- }),
112
- get: async (id, storyId) => await context
113
- .entrypoint(connectRef.story.get).call({ params: { id, storyId }, timeout: TOOL_DEADLINE_MS }),
114
- create: async (id, story) => await context
115
- .entrypoint(connectRef.story.create).call({ params: { id }, body: { story }, timeout: TOOL_DEADLINE_MS }),
116
- update: async (id, storyId, story) => await context.entrypoint(connectRef.story.update).call({
117
- params: { id, storyId }, body: { story }, timeout: TOOL_DEADLINE_MS,
118
- }),
119
- remove: async (id, storyId) => await context
120
- .entrypoint(connectRef.story.delete).call({ params: { id, storyId }, timeout: TOOL_DEADLINE_MS }),
121
- develop: async (id, storyId) => await context.entrypoint(connectRef.story.develop).call({
122
- params: { id, storyId }, timeout: TOOL_DEADLINE_MS,
123
- }),
124
- },
114
+ planning: planningOf(context, {}),
125
115
  files: {
126
116
  list: async (id) => await context.entrypoint(connectRef.files.list).call({
127
117
  params: { id }, timeout: TOOL_DEADLINE_MS,