@happyvertical/smrt-inference 0.60.18 → 0.61.1

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 (82) hide show
  1. package/AGENTS.md +35 -1
  2. package/README.md +86 -0
  3. package/agents/design-runs.md +110 -0
  4. package/agents/engines.md +458 -0
  5. package/dist/agent-cli/credentials.d.ts +28 -0
  6. package/dist/agent-cli/credentials.d.ts.map +1 -0
  7. package/dist/agent-cli/detect.d.ts +28 -0
  8. package/dist/agent-cli/detect.d.ts.map +1 -0
  9. package/dist/agent-cli/env.d.ts +14 -0
  10. package/dist/agent-cli/env.d.ts.map +1 -0
  11. package/dist/agent-cli/locate.d.ts +16 -0
  12. package/dist/agent-cli/locate.d.ts.map +1 -0
  13. package/dist/agent-cli/login.d.ts +30 -0
  14. package/dist/agent-cli/login.d.ts.map +1 -0
  15. package/dist/agent-cli/runner.d.ts +31 -0
  16. package/dist/agent-cli/runner.d.ts.map +1 -0
  17. package/dist/agent-cli/service.d.ts +20 -0
  18. package/dist/agent-cli/service.d.ts.map +1 -0
  19. package/dist/agent-cli/session.d.ts +42 -0
  20. package/dist/agent-cli/session.d.ts.map +1 -0
  21. package/dist/agent-cli/stream.d.ts +50 -0
  22. package/dist/agent-cli/stream.d.ts.map +1 -0
  23. package/dist/agent-cli/test-support.d.ts +21 -0
  24. package/dist/agent-cli/test-support.d.ts.map +1 -0
  25. package/dist/agent-cli/test-support.js +67 -0
  26. package/dist/agent-cli/test-support.js.map +1 -0
  27. package/dist/agent-cli/tools.d.ts +19 -0
  28. package/dist/agent-cli/tools.d.ts.map +1 -0
  29. package/dist/agent-cli/turn.d.ts +138 -0
  30. package/dist/agent-cli/turn.d.ts.map +1 -0
  31. package/dist/chatgpt/connection.d.ts +149 -0
  32. package/dist/chatgpt/connection.d.ts.map +1 -0
  33. package/dist/chatgpt/model.d.ts +42 -0
  34. package/dist/chatgpt/model.d.ts.map +1 -0
  35. package/dist/chatgpt/resolver.d.ts +39 -0
  36. package/dist/chatgpt/resolver.d.ts.map +1 -0
  37. package/dist/chatgpt/support.d.ts +36 -0
  38. package/dist/chatgpt/support.d.ts.map +1 -0
  39. package/dist/chunks/{InferenceOverrideCollection-BS_hqxS9.js → InferenceOverrideCollection-Dc3mkL-1.js} +62 -3
  40. package/dist/chunks/InferenceOverrideCollection-Dc3mkL-1.js.map +1 -0
  41. package/dist/chunks/work-profiles-DCgIbilc.js +484 -0
  42. package/dist/chunks/work-profiles-DCgIbilc.js.map +1 -0
  43. package/dist/design-run-store.d.ts +26 -0
  44. package/dist/design-run-store.d.ts.map +1 -0
  45. package/dist/design-run.d.ts +146 -0
  46. package/dist/design-run.d.ts.map +1 -0
  47. package/dist/engine-id.d.ts +5 -0
  48. package/dist/engine-id.d.ts.map +1 -0
  49. package/dist/engine-model.d.ts +56 -0
  50. package/dist/engine-model.d.ts.map +1 -0
  51. package/dist/engine-status.d.ts +37 -0
  52. package/dist/engine-status.d.ts.map +1 -0
  53. package/dist/index.d.ts +3 -0
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +2 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/manifest.json +182 -1
  58. package/dist/models/DesignRunRecord.d.ts +22 -0
  59. package/dist/models/DesignRunRecord.d.ts.map +1 -0
  60. package/dist/models.d.ts +1 -0
  61. package/dist/models.d.ts.map +1 -1
  62. package/dist/models.js +2 -2
  63. package/dist/node.js +1 -1
  64. package/dist/node.js.map +1 -1
  65. package/dist/server.d.ts +24 -0
  66. package/dist/server.d.ts.map +1 -1
  67. package/dist/server.js +2471 -150
  68. package/dist/server.js.map +1 -1
  69. package/dist/settings/controller.d.ts +111 -0
  70. package/dist/settings/controller.d.ts.map +1 -0
  71. package/dist/settings/host.d.ts +75 -0
  72. package/dist/settings/host.d.ts.map +1 -0
  73. package/dist/settings/key-store.d.ts +35 -0
  74. package/dist/settings/key-store.d.ts.map +1 -0
  75. package/dist/settings/resolver.d.ts +6 -2
  76. package/dist/settings/resolver.d.ts.map +1 -1
  77. package/dist/smrt-knowledge.json +93 -7
  78. package/dist/smrt-knowledge.okf.md +15 -5
  79. package/dist/work-profiles.d.ts +127 -0
  80. package/dist/work-profiles.d.ts.map +1 -0
  81. package/package.json +15 -10
  82. package/dist/chunks/InferenceOverrideCollection-BS_hqxS9.js.map +0 -1
package/AGENTS.md CHANGED
@@ -31,7 +31,12 @@ provisioning and the spend gate (#4759, #4760). App-author guide:
31
31
  bundle-gate browser fixture): the `_smrt_inference_overrides` model;
32
32
  generated consumer registration imports it from here.
33
33
  - `./server` (Node-only): settings service, override service, override
34
- resolver, key rule, preference kind (#4754). `./svelte`: the panel.
34
+ resolver, key rule, preference kind (#4754); local CLI turns, ChatGPT model
35
+ rounds and connection diagnostics ([agents/engines.md](agents/engines.md)).
36
+ `./svelte`: the panel.
37
+ - `./test-support` (Node-only): shared fake CLI installers and isolated lookup
38
+ dependencies for engine/host tests; fixture source is bundled, never run on
39
+ real credentials ([agents/engines.md](agents/engines.md)).
35
40
  - `./gate` (Node-only, #4760): the hosted spend gate and kill switch
36
41
  (below). `browser-safe.test.ts` keeps it off the root graph.
37
42
 
@@ -76,6 +81,28 @@ always wins), tenant, entitlement, then plan spend caps; a block throws
76
81
  `InferenceUnavailableError` (`entitlement`) and writes a `blocked` usage row.
77
82
  Details: [agents/hosted.md](agents/hosted.md).
78
83
 
84
+ ## Sign in with ChatGPT (`src/chatgpt/`, `./server`)
85
+
86
+ Local profile only; a PREVIEW for open source apps
87
+ ([limitations](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations)).
88
+ `createChatGPTPlanConnection({ appName, credentialsPath })` wraps the SDK's
89
+ `LocalChatGPTSessionManager` (`@happyvertical/auth/local`, loaded lazily): the
90
+ SDK's own owner-only file at `credentialsPath` is the only credential store;
91
+ smrt never reads it, and no result, log or error carries a token (status is
92
+ `signedIn`, `signingIn`, an account label, a fixed-vocabulary error;
93
+ `clientOptions()` hands the provider `{ accessToken }` only). `start()` returns
94
+ the URL only after checking https on `auth.openai.com`. The resolver
95
+ (`createChatGPTPlanResolver`, composed outside the user resolver by
96
+ `createInferenceSettingsHost({ chatgptPlan })`) answers only calls whose
97
+ `appliesTo` is true: `chatgpt-plan` with `source: 'byo'` when signed in,
98
+ `unavailable: 'unconfigured'` otherwise, never an API-key fallback, never a
99
+ default. The provider rejects `maxTokens`, sampling, `user`, response formats,
100
+ reasoning, forced single-function `toolChoice` and `stream()` with tools; the
101
+ caller sends none of them (`classifyChatGPTPlanFailure` names the failures).
102
+ Guide: [docs/content/inference-settings.md](../../docs/content/inference-settings.md).
103
+
104
+ [Owner work profiles and durable design runs](agents/design-runs.md).
105
+
79
106
  ## Config
80
107
 
81
108
  ```ts
@@ -195,6 +222,13 @@ app-only `transcripts` row, editable in the panel only with `appEditable`,
195
222
  applied as core's transcript app settings layer; the Usage tab shows
196
223
  transcript counts and links to a host route, never content. Details: [agents/settings.md](agents/settings.md),
197
224
  consumer guide [docs/content/inference-settings.md](../../docs/content/inference-settings.md).
225
+ `./server` also ships the framework-free host wiring both the template and
226
+ the app shell use: `createInferenceSettingsHost` (secret store under the
227
+ runtime's master key, user resolver over the override resolver, settings
228
+ service with its authorizer), `createInferenceSettingsController` (the
229
+ panel's `load` and writes, gated on `inference.customize`; a refusal and a
230
+ key-origin error name no key), and `saveInferenceKey` / `inferenceKeyIsSet`.
231
+ A host supplies only its session check, preference store and routes.
198
232
 
199
233
  ## Validation
200
234
 
package/README.md CHANGED
@@ -60,10 +60,96 @@ await article.do('Summarize this', { tier: 'great' });
60
60
  to targets on the app's allow-list; keys stay in smrt-secrets.
61
61
  - **Hosted inference**: per-user gateway keys (`./node`) and the spend gate
62
62
  and kill switch (`./gate`).
63
+ - **Sign in with ChatGPT** (`./server`, local apps): a connection service over
64
+ the SDK's `LocalChatGPTSessionManager` and an opt-in resolver that yields a
65
+ `chatgpt-plan` target, so a person can use their own ChatGPT plan. It is a
66
+ preview for open source apps
67
+ ([limitations](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations)),
68
+ never a default and never a fallback. See
69
+ [Inference settings](../../docs/content/inference-settings.md#sign-in-with-chatgpt-local-apps).
63
70
 
64
71
  The app-author guide, with a worked example, is
65
72
  [Inference tiers, bindings and usage](../../docs/content/inference.md).
66
73
 
74
+ ## Assistant engines (Node hosts)
75
+
76
+ Import these adapters from `@happyvertical/smrt-inference/server`. The host
77
+ supplies authenticated persistence, tool policy, owner approvals and UI events.
78
+ There is no dependency on smrt-chat or app-shell. The full
79
+ [host contracts and security rules](agents/engines.md) describe each callback.
80
+
81
+ For a chat-style tool loop, use the person's explicit ChatGPT connection:
82
+
83
+ ```ts
84
+ import { createChatGPTModel } from '@happyvertical/smrt-inference/server';
85
+
86
+ const model = await createChatGPTModel({
87
+ connection, // createChatGPTPlanConnection, after explicit engine selection
88
+ toolNamespace: { name: 'app_tools', description: 'Tools for your own app' },
89
+ settingsHref: '/settings/ai',
90
+ });
91
+ const reply = await model.complete({
92
+ messages, tools, maxTokens: 2048, signal,
93
+ onText: delta => send({ type: 'text', delta }),
94
+ });
95
+ // Host executes reply.toolCalls through its policy/approval gate, persists
96
+ // results and replays reply.raw on the next round. Bound the loop in the host.
97
+ ```
98
+
99
+ The model uses only `chat()` and `onProgress`; `maxTokens` stays in the host.
100
+ There is no API-key fallback. Known failures are `EngineModelFailure`; treat
101
+ other errors generically and never expose provider messages or causes.
102
+
103
+ For either local CLI engine, let its subprocess own the turn:
104
+
105
+ ```ts
106
+ import {
107
+ createAgentCliService, locateCli, runAgentTurn, tokenCredentials,
108
+ } from '@happyvertical/smrt-inference/server';
109
+
110
+ const cli = createAgentCliService(); // one per host, not per status request
111
+ const tool = 'claude-code'; // or 'codex': same host contract
112
+ await runAgentTurn({
113
+ tool, text, signal, emit: send,
114
+ mcpUrl: 'http://127.0.0.1:4801/mcp', // host endpoint enforces owner/tool policy
115
+ deps: {
116
+ locate: selected => locateCli(selected, cli.agentCliDeps()),
117
+ stateDir: async () => privateAgentDirectory,
118
+ credentials: tokenCredentials(localTokenStore, {
119
+ holder: conversationHolder, label: 'App assistant', scopes: ['assistant.use'],
120
+ }),
121
+ },
122
+ host: {
123
+ appendMessage, lastSession,
124
+ guidance: async () => ({ systemPrompt: guidance, prompt: text }),
125
+ allowTool: name => offeredTools.has(name),
126
+ approvals: { subscribe: subscribeTurnApprovals, get: getOwnerApproval },
127
+ describeResult: async ({ text }) => ({ summary: summarize(text) }),
128
+ },
129
+ });
130
+ ```
131
+
132
+ The host verifies the owner before minting a token. The CLI receives it only in
133
+ its environment, with provider keys stripped, built-in tools disabled, a
134
+ loopback-only MCP URL and a private working directory. Stop/timeout kills its
135
+ process tree. Status and sign-in use the CLI's own commands; no credential
136
+ stores are read. **Do not offer in-app Claude subscription login**: use the
137
+ person's own Claude Code and its vendor login. ChatGPT sign-in remains a
138
+ separate opt-in preview under the limitations linked above.
139
+
140
+ `inferenceEngineStatus(engine, { cliStatus, chatgpt, apiStatus, actions })`
141
+ composes installed/signed-in/configured diagnostics; API-key resolution and
142
+ settings destinations come from the host. The saved API-key engine continues
143
+ through the normal inference resolver and SDK, independently of these adapters.
144
+
145
+ CLI engine tests can import `@happyvertical/smrt-inference/test-support` for
146
+ `tempDir`, `installStub`, `installFakeCli` and `fakeDeps`. The fake CLI source is
147
+ bundled into that Node-only test entry, so host adapter tests share the same
148
+ fixture without reading another package's source tree. Never supply real
149
+ credentials to the fake CLI: its diagnostic scenarios intentionally record the
150
+ fake environment. The [reuse audit](agents/engines.md#reuse-audit-for-the-c2-extraction)
151
+ lists each extracted file and the alternatives checked.
152
+
67
153
  ## Checking bindings
68
154
 
69
155
  ```bash
@@ -0,0 +1,110 @@
1
+ # Durable design runs
2
+
3
+ `createDesignRunDriver` is an engine-neutral ordered pass executor. A run is a
4
+ workflow record in `_smrt_inference_design_runs`, not a second queue. Run normal
5
+ application migrations before starting it. The host admits work through existing
6
+ `SmrtJobCollection.enqueueJob` and executes it through `TaskRunner`; browser
7
+ connection lifetime must never own its cancellation signal.
8
+
9
+ The host binds `createDesignRunStore` to the authenticated owner and tenant. Its
10
+ `enqueue(transaction, state)` callback enqueues the existing job in that same
11
+ transaction, using the stable run id as `dedupeKey`. Start and resume either save
12
+ the checkpoint and admit the job together, or neither commits. Run ids are UUIDs.
13
+ All generated REST, CLI, and MCP surfaces on `DesignRunRecord` are disabled.
14
+
15
+ Install `installDesignRunExecutor(db, handler)` once when booting the host. Its
16
+ handler receives the hydrated record, arguments and runner context. Verify
17
+ `isRunnerExecutionContext`, the job target, tenant and current owner authority;
18
+ then build a worker store whose `authorizeWrite(transaction, state)` verifies the
19
+ live job claim on every checkpoint. Pass the runner's `signal` to `driver.run`.
20
+ Supply `ownsExecution` with that same live claim proof so a recovered job can
21
+ replace the crashed pass's stale lease immediately. Only `execute` is background-eligible. The installer returns teardown; reinstall
22
+ it after process restart before starting the runner.
23
+
24
+ A host definition pins a version string and an ordered list of plain-text pass
25
+ names and JSON schemas. Every engine, including CLI engines, returns an object
26
+ through `executePass`; the mandatory host `validate(schema, output)` callback
27
+ must use a full JSON Schema implementation such as Ajv, not a partial handwritten
28
+ validator. Invalid outputs and validation errors are checkpointed and supplied to
29
+ the next repair attempt. Repairs stop at `repairRetries`. Accepted outputs are
30
+ checkpointed before deterministic `check` code runs. Checks receive their own
31
+ abort signal, may feed facts to the next pass, request a bounded repeat, or pause
32
+ for owner approval. Checks must be read-only or idempotent because a crash may
33
+ replay them. A profile supplies quality and budgets, never permission or approval.
34
+
35
+ An approval hold retains the accepted output, current pass index and `check`
36
+ phase, clears repair state and releases the settled check lease. Resume reruns
37
+ that same check, including for the final pass; only a cleared check can advance
38
+ or finish the run. It never calls the model again for that accepted output or
39
+ duplicates its attempts/token usage. A denied check may fail terminally. Hosts
40
+ must give effects stable identities and recover their exact recorded result
41
+ when replay follows a crash after apply but before the completion checkpoint.
42
+ Recover a running/checking job by calling `run` under its legitimate replacement
43
+ TaskRunner claim (`ownsExecution`), without clearing leases through frontend
44
+ `resume`, weakening liveness proof or enabling generic failed-run retries.
45
+ For a definitive check rejection, the trusted host may return `failure` with
46
+ its own safe, static explanation. This ends the run as `failed`, retaining the
47
+ validated output, input, usage and attempts; it takes precedence over an approval
48
+ hold or repeat. Never copy model output or caught exception text into `failure`.
49
+ Ordinary thrown errors still receive the driver's generic failure explanation.
50
+
51
+ A trusted host check may return `complete: true` after mechanically validating
52
+ and applying its accepted proposal. This ends the run at its actual pass index,
53
+ retaining the `check` phase, input, outputs, attempts and accumulated usage. It
54
+ does not manufacture later passes or their usage. Failure, approval hold and
55
+ bounded repeat take precedence over completion, in that order. An approval hold
56
+ therefore resumes the same check before completion, without another model call.
57
+ Model output fields cannot select completion. Done runs remain terminal for
58
+ `run`, `stop` and `resume` even when their index is below the configured count.
59
+ The host owns versioned adaptive eligibility and exact owner-selected pass-count
60
+ semantics; the inference driver does not reinterpret work-profile budgets.
61
+ The existing design-run tests cover first/later completion, conflicting check
62
+ results, approval resume, lost completion CAS with same-action recovery under a
63
+ replacement claim, and stale completion after Stop.
64
+
65
+ Inputs carry resource ids. `readResource` rejects ids outside the host's pinned
66
+ list; the host checks current owner access and supplies summary-first pages with
67
+ opaque cursors. A page exceeding `toolResultChars`, including its envelope, is
68
+ rejected before it enters model context. Files and credentials are never inlined
69
+ into checkpoints.
70
+
71
+ Token and elapsed-time allowances accumulate across model calls, repair calls,
72
+ and mechanical checks. Before each call, the driver durably reserves its entire
73
+ allowed token and time budget. Successful calls reconcile to reported actual
74
+ usage; unknown token usage or a crash retains the reservation conservatively.
75
+ Checks reserve time too. A timeout or exhausted cumulative budget produces a
76
+ resumable `stopped` run with a plain explanation. Raise total budgets on resume;
77
+ usage never resets. Stop is cooperative: cancel the existing job as well, and
78
+ forward its signal into engine requests. A still-active pass lease prevents
79
+ immediate overlapping resume. The worker store's `authorizeRelease` must lock
80
+ and prove the captured job id, worker id and attempt (running or its terminal
81
+ Stop outcome, never a pending/recovered claim). `releaseLease` freshly reads a
82
+ stopped checkpoint with the same `leaseRevision` and atomically clears that
83
+ lease with a revision CAS. The driver calls it only after the original engine
84
+ or check promise truly settles; winning an abort/timeout race alone cannot
85
+ release a lease. A retained `leaseRevision` blocks frontend resume even after
86
+ its deadline. Crash recovery of a running job requires `ownsExecution` from a
87
+ replacement TaskRunner claim; a stopped run whose original process died needs
88
+ an explicit host liveness recovery path, never an inference from elapsed time
89
+ or missing jobs. A cooperative stopped call can therefore resume immediately
90
+ when its backing job has also settled. Delayed release cannot clear a newer
91
+ running/resumed claim. CAS revisions prevent stale workers overwriting
92
+ Stop or newer progress. Definitive schema/check failures end as `failed`.
93
+
94
+ Progress uses exactly `{ runId, pass: { index, count, name }, status, note? }`.
95
+ Indices are one-based. Statuses are `running`, `checking`, `waiting-approval`,
96
+ `stopped`, `failed`, and `done`. Publish this on the existing event stream;
97
+ subscriber failures cannot interrupt durable work. Each attempt stores its
98
+ `WorkRunMetadata`, including actual provider usage when available. Host tool
99
+ policy, durable approvals and history apply throughout all passes.
100
+
101
+ ## Reuse audit
102
+
103
+ The intent index, `review_smrt_project` and `build_context` were consulted before
104
+ implementation. Searches across smrt-ui, smrt-svelte, chat, core, jobs and inference
105
+ found no existing ordered schema-repair driver. Existing `SmrtJob`, `TaskRunner`,
106
+ `McpTaskStore` and durable MCP continuations remain the queue, liveness,
107
+ cancellation and input primitives. Job events have independent retention and do
108
+ not provide atomic workflow CAS, so a dedicated inference workflow checkpoint
109
+ holds pass inputs/outputs and cumulative budgets. Inference depends on no jobs
110
+ runtime; the authenticated host supplies the transaction admission callback.