@happyvertical/smrt-inference 0.60.18 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +35 -1
- package/README.md +86 -0
- package/agents/design-runs.md +110 -0
- package/agents/engines.md +458 -0
- package/dist/agent-cli/credentials.d.ts +28 -0
- package/dist/agent-cli/credentials.d.ts.map +1 -0
- package/dist/agent-cli/detect.d.ts +28 -0
- package/dist/agent-cli/detect.d.ts.map +1 -0
- package/dist/agent-cli/env.d.ts +14 -0
- package/dist/agent-cli/env.d.ts.map +1 -0
- package/dist/agent-cli/locate.d.ts +16 -0
- package/dist/agent-cli/locate.d.ts.map +1 -0
- package/dist/agent-cli/login.d.ts +30 -0
- package/dist/agent-cli/login.d.ts.map +1 -0
- package/dist/agent-cli/runner.d.ts +31 -0
- package/dist/agent-cli/runner.d.ts.map +1 -0
- package/dist/agent-cli/service.d.ts +20 -0
- package/dist/agent-cli/service.d.ts.map +1 -0
- package/dist/agent-cli/session.d.ts +42 -0
- package/dist/agent-cli/session.d.ts.map +1 -0
- package/dist/agent-cli/stream.d.ts +50 -0
- package/dist/agent-cli/stream.d.ts.map +1 -0
- package/dist/agent-cli/test-support.d.ts +21 -0
- package/dist/agent-cli/test-support.d.ts.map +1 -0
- package/dist/agent-cli/test-support.js +67 -0
- package/dist/agent-cli/test-support.js.map +1 -0
- package/dist/agent-cli/tools.d.ts +19 -0
- package/dist/agent-cli/tools.d.ts.map +1 -0
- package/dist/agent-cli/turn.d.ts +138 -0
- package/dist/agent-cli/turn.d.ts.map +1 -0
- package/dist/chatgpt/connection.d.ts +149 -0
- package/dist/chatgpt/connection.d.ts.map +1 -0
- package/dist/chatgpt/model.d.ts +42 -0
- package/dist/chatgpt/model.d.ts.map +1 -0
- package/dist/chatgpt/resolver.d.ts +39 -0
- package/dist/chatgpt/resolver.d.ts.map +1 -0
- package/dist/chatgpt/support.d.ts +36 -0
- package/dist/chatgpt/support.d.ts.map +1 -0
- package/dist/chunks/{InferenceOverrideCollection-BS_hqxS9.js → InferenceOverrideCollection-DrlOGPCI.js} +62 -3
- package/dist/chunks/InferenceOverrideCollection-DrlOGPCI.js.map +1 -0
- package/dist/chunks/work-profiles-DCgIbilc.js +484 -0
- package/dist/chunks/work-profiles-DCgIbilc.js.map +1 -0
- package/dist/design-run-store.d.ts +26 -0
- package/dist/design-run-store.d.ts.map +1 -0
- package/dist/design-run.d.ts +146 -0
- package/dist/design-run.d.ts.map +1 -0
- package/dist/engine-id.d.ts +5 -0
- package/dist/engine-id.d.ts.map +1 -0
- package/dist/engine-model.d.ts +56 -0
- package/dist/engine-model.d.ts.map +1 -0
- package/dist/engine-status.d.ts +37 -0
- package/dist/engine-status.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +182 -1
- package/dist/models/DesignRunRecord.d.ts +22 -0
- package/dist/models/DesignRunRecord.d.ts.map +1 -0
- package/dist/models.d.ts +1 -0
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +2 -2
- package/dist/node.js +1 -1
- package/dist/node.js.map +1 -1
- package/dist/server.d.ts +24 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2471 -150
- package/dist/server.js.map +1 -1
- package/dist/settings/controller.d.ts +111 -0
- package/dist/settings/controller.d.ts.map +1 -0
- package/dist/settings/host.d.ts +75 -0
- package/dist/settings/host.d.ts.map +1 -0
- package/dist/settings/key-store.d.ts +35 -0
- package/dist/settings/key-store.d.ts.map +1 -0
- package/dist/settings/resolver.d.ts +6 -2
- package/dist/settings/resolver.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +93 -7
- package/dist/smrt-knowledge.okf.md +15 -5
- package/dist/work-profiles.d.ts +127 -0
- package/dist/work-profiles.d.ts.map +1 -0
- package/package.json +15 -10
- package/dist/chunks/InferenceOverrideCollection-BS_hqxS9.js.map +0 -1
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { InferenceSettingsHost } from './host.js';
|
|
2
|
+
import { type InferenceKeyPayload } from './key-store.js';
|
|
3
|
+
import { type InferencePreferenceStoreLike } from './preferences.js';
|
|
4
|
+
import type { InferenceMode } from './targets.js';
|
|
5
|
+
/** The panel's props: shared by every host's `load`. */
|
|
6
|
+
declare function loadPage(options: InferenceSettingsControllerOptions, session: InferenceControllerSession, by?: string | null): Promise<{
|
|
7
|
+
tenantId: string;
|
|
8
|
+
canEdit: boolean;
|
|
9
|
+
canPersonalize: boolean;
|
|
10
|
+
defaults: {
|
|
11
|
+
keySet: boolean;
|
|
12
|
+
mode?: InferenceMode;
|
|
13
|
+
provider?: string;
|
|
14
|
+
baseUrl?: string;
|
|
15
|
+
model?: string;
|
|
16
|
+
defaultTier?: import("@happyvertical/smrt-core").InferenceTier;
|
|
17
|
+
};
|
|
18
|
+
providers: import("./settings-service.js").InferenceProviderOption[];
|
|
19
|
+
tiers: import("./settings-service.js").InferenceTierSettingsRow[];
|
|
20
|
+
defaultTier: import("./settings-service.js").InferenceDefaultTierSetting;
|
|
21
|
+
aliases: import("./settings-service.js").InferenceAliasSetting[];
|
|
22
|
+
fusions: import("./settings-service.js").InferenceFusionSetting[];
|
|
23
|
+
transcripts: import("./settings-service.js").InferenceTranscriptSettings;
|
|
24
|
+
usage: import("@happyvertical/smrt-core").AiUsageReport | null;
|
|
25
|
+
}>;
|
|
26
|
+
/** What {@link InferenceSettingsController.load} returns (the panel's props). */
|
|
27
|
+
export type InferenceSettingsPageData = Awaited<ReturnType<typeof loadPage>>;
|
|
28
|
+
type Tier = 'cheap' | 'good' | 'great' | 'best';
|
|
29
|
+
/** The principal of a settings request. */
|
|
30
|
+
export interface InferenceControllerSession {
|
|
31
|
+
tenantId: string;
|
|
32
|
+
/** Whether the session holds `permission` (the host's own check). */
|
|
33
|
+
can(permission: string): boolean;
|
|
34
|
+
}
|
|
35
|
+
/** A write's result: `fail()` it in the framework, or show `message`. */
|
|
36
|
+
export type InferenceSettingsOutcome<T = Record<never, never>> = ({
|
|
37
|
+
ok: true;
|
|
38
|
+
message?: string;
|
|
39
|
+
} & T) | {
|
|
40
|
+
ok: false;
|
|
41
|
+
status: number;
|
|
42
|
+
error: string;
|
|
43
|
+
};
|
|
44
|
+
export interface InferenceSettingsControllerOptions {
|
|
45
|
+
host: InferenceSettingsHost;
|
|
46
|
+
/** The smrt-preferences store for the request's principal. */
|
|
47
|
+
preferenceStore: () => Promise<InferencePreferenceStoreLike>;
|
|
48
|
+
}
|
|
49
|
+
export interface InferenceSettingsController {
|
|
50
|
+
/** Whether the session may write app-wide settings and keys. */
|
|
51
|
+
canCustomize(session: InferenceControllerSession): boolean;
|
|
52
|
+
/** The panel's props. `by` is the usage report grouping (`a,b`). */
|
|
53
|
+
load(session: InferenceControllerSession, by?: string | null): Promise<InferenceSettingsPageData>;
|
|
54
|
+
saveDefaults(session: InferenceControllerSession, change: {
|
|
55
|
+
mode: InferenceMode;
|
|
56
|
+
provider?: string;
|
|
57
|
+
baseUrl?: string;
|
|
58
|
+
model?: string;
|
|
59
|
+
defaultTier?: Tier;
|
|
60
|
+
}): Promise<InferenceSettingsOutcome>;
|
|
61
|
+
saveKey(session: InferenceControllerSession, change: InferenceKeyPayload): Promise<InferenceSettingsOutcome>;
|
|
62
|
+
saveTier(session: InferenceControllerSession, change: {
|
|
63
|
+
tier: Tier;
|
|
64
|
+
scope: 'app' | 'tenant';
|
|
65
|
+
target: Record<string, unknown> | null;
|
|
66
|
+
}): Promise<InferenceSettingsOutcome>;
|
|
67
|
+
saveDefaultTier(session: InferenceControllerSession, change: {
|
|
68
|
+
scope: 'app' | 'tenant';
|
|
69
|
+
tier: Tier | null;
|
|
70
|
+
}): Promise<InferenceSettingsOutcome>;
|
|
71
|
+
saveAlias(session: InferenceControllerSession, change: {
|
|
72
|
+
name: string;
|
|
73
|
+
candidates: unknown[] | null;
|
|
74
|
+
description?: string;
|
|
75
|
+
}): Promise<InferenceSettingsOutcome>;
|
|
76
|
+
saveFusion(session: InferenceControllerSession, change: {
|
|
77
|
+
name: string;
|
|
78
|
+
definition: Record<string, unknown> | null;
|
|
79
|
+
}): Promise<InferenceSettingsOutcome>;
|
|
80
|
+
saveTranscripts(session: InferenceControllerSession, change: {
|
|
81
|
+
settings: {
|
|
82
|
+
enabled: boolean;
|
|
83
|
+
sample: number;
|
|
84
|
+
maxBytes: number;
|
|
85
|
+
} | null;
|
|
86
|
+
}): Promise<InferenceSettingsOutcome>;
|
|
87
|
+
/** Probes return a key-free result and write nothing. */
|
|
88
|
+
testConnection(session: InferenceControllerSession, input: {
|
|
89
|
+
provider?: string;
|
|
90
|
+
preset?: string;
|
|
91
|
+
baseUrl?: string;
|
|
92
|
+
model?: string;
|
|
93
|
+
}): Promise<InferenceSettingsOutcome<{
|
|
94
|
+
result: unknown;
|
|
95
|
+
}>>;
|
|
96
|
+
testCandidate(session: InferenceControllerSession, candidate: Record<string, unknown>): Promise<InferenceSettingsOutcome<{
|
|
97
|
+
result: unknown;
|
|
98
|
+
}>>;
|
|
99
|
+
discoverModels(session: InferenceControllerSession): Promise<{
|
|
100
|
+
discovered: unknown;
|
|
101
|
+
}>;
|
|
102
|
+
}
|
|
103
|
+
export declare const NOT_ALLOWED_OUTCOME: {
|
|
104
|
+
readonly ok: false;
|
|
105
|
+
readonly status: 403;
|
|
106
|
+
readonly error: "You are not allowed to change this setting.";
|
|
107
|
+
};
|
|
108
|
+
/** Build the controller over a host. */
|
|
109
|
+
export declare function createInferenceSettingsController(options: InferenceSettingsControllerOptions): InferenceSettingsController;
|
|
110
|
+
export {};
|
|
111
|
+
//# sourceMappingURL=controller.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"controller.d.ts","sourceRoot":"","sources":["../../src/settings/controller.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAEvD,OAAO,EACL,KAAK,mBAAmB,EAGzB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAGL,KAAK,4BAA4B,EAElC,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAUlD,wDAAwD;AACxD,iBAAe,QAAQ,CACrB,OAAO,EAAE,kCAAkC,EAC3C,OAAO,EAAE,0BAA0B,EACnC,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI;;;;;;;;;;;;;;;;;;;GAqCnB;AAED,iFAAiF;AACjF,MAAM,MAAM,yBAAyB,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,CAAC,CAAC;AAE7E,KAAK,IAAI,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAEhD,2CAA2C;AAC3C,MAAM,WAAW,0BAA0B;IACzC,QAAQ,EAAE,MAAM,CAAC;IACjB,qEAAqE;IACrE,GAAG,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC;CAClC;AAED,yEAAyE;AACzE,MAAM,MAAM,wBAAwB,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IACzD,CAAC;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,CAAC,CAAC,GACpC;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD,MAAM,WAAW,kCAAkC;IACjD,IAAI,EAAE,qBAAqB,CAAC;IAC5B,8DAA8D;IAC9D,eAAe,EAAE,MAAM,OAAO,CAAC,4BAA4B,CAAC,CAAC;CAC9D;AAED,MAAM,WAAW,2BAA2B;IAC1C,gEAAgE;IAChE,YAAY,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC;IAC3D,oEAAoE;IACpE,IAAI,CACF,OAAO,EAAE,0BAA0B,EACnC,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,GACjB,OAAO,CAAC,yBAAyB,CAAC,CAAC;IACtC,YAAY,CACV,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE;QACN,IAAI,EAAE,aAAa,CAAC;QACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,IAAI,CAAC;KACpB,GACA,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,OAAO,CACL,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,QAAQ,CACN,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE;QACN,IAAI,EAAE,IAAI,CAAC;QACX,KAAK,EAAE,KAAK,GAAG,QAAQ,CAAC;QACxB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;KACxC,GACA,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,eAAe,CACb,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE;QAAE,KAAK,EAAE,KAAK,GAAG,QAAQ,CAAC;QAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;KAAE,GACrD,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,SAAS,CACP,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE;QACN,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAC7B,WAAW,CAAC,EAAE,MAAM,CAAC;KACtB,GACA,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,UAAU,CACR,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAA;KAAE,GACnE,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,eAAe,CACb,OAAO,EAAE,0BAA0B,EACnC,MAAM,EAAE;QACN,QAAQ,EAAE;YAAE,OAAO,EAAE,OAAO,CAAC;YAAC,MAAM,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,CAAA;SAAE,GAAG,IAAI,CAAC;KACzE,GACA,OAAO,CAAC,wBAAwB,CAAC,CAAC;IACrC,yDAAyD;IACzD,cAAc,CACZ,OAAO,EAAE,0BAA0B,EACnC,KAAK,EAAE;QACL,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GACA,OAAO,CAAC,wBAAwB,CAAC;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC,CAAC;IAC1D,aAAa,CACX,OAAO,EAAE,0BAA0B,EACnC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACjC,OAAO,CAAC,wBAAwB,CAAC;QAAE,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC,CAAC;IAC1D,cAAc,CACZ,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC;QAAE,UAAU,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CACrC;AAED,eAAO,MAAM,mBAAmB;;;;CAItB,CAAC;AAEX,wCAAwC;AACxC,wBAAgB,iCAAiC,CAC/C,OAAO,EAAE,kCAAkC,GAC1C,2BAA2B,CAyJ7B"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server wiring every host of `InferenceSettingsPanel` needs, free of any
|
|
3
|
+
* web framework: the secret store (sealed under the runtime's master key),
|
|
4
|
+
* the user resolver stored API keys are written through and read from, its
|
|
5
|
+
* registration for inference calls, and the settings service with the
|
|
6
|
+
* authorizer that gates its writes.
|
|
7
|
+
*
|
|
8
|
+
* A SvelteKit template app and the app shell both build their host from this,
|
|
9
|
+
* so a key saved on the Inference page is the key the process's inference
|
|
10
|
+
* calls (including the shell's assistant) use, with no restart.
|
|
11
|
+
*/
|
|
12
|
+
import { type SmrtClassOptions } from '@happyvertical/smrt-core';
|
|
13
|
+
import { type SecretMasterKeyProvider, SecretService } from '@happyvertical/smrt-secrets';
|
|
14
|
+
import type { DatabaseInterface } from '@happyvertical/sql';
|
|
15
|
+
import { type ChatGPTPlanResolverOptions } from '../chatgpt/resolver.js';
|
|
16
|
+
import { type UserInferenceResolver } from '../resolver.js';
|
|
17
|
+
import { InferenceSettingsService } from './settings-service.js';
|
|
18
|
+
/** What {@link createInferenceSettingsHost} needs from the host app. */
|
|
19
|
+
export interface InferenceSettingsHostOptions {
|
|
20
|
+
/** The application database (resolved on first use). */
|
|
21
|
+
database: () => Promise<DatabaseInterface>;
|
|
22
|
+
/**
|
|
23
|
+
* The application master key for the secret store. `SMRT_SECRET_MASTER_KEY`
|
|
24
|
+
* wins where it is set; a local runtime supplies `secretMasterKey()` here
|
|
25
|
+
* (null off the local profile).
|
|
26
|
+
*/
|
|
27
|
+
masterKeyProvider?: SecretMasterKeyProvider;
|
|
28
|
+
/** Database options of the `InferenceOverride` collection. */
|
|
29
|
+
overrides: () => SmrtClassOptions;
|
|
30
|
+
/**
|
|
31
|
+
* Sign in with ChatGPT (an opt-in billing path, never a fallback): the
|
|
32
|
+
* connection, and which calls ask for it. Composed OUTSIDE the user
|
|
33
|
+
* resolver by {@link InferenceSettingsHost.install}.
|
|
34
|
+
*/
|
|
35
|
+
chatgptPlan?: Omit<ChatGPTPlanResolverOptions, 'fallback'>;
|
|
36
|
+
}
|
|
37
|
+
/** The principal of a settings request. */
|
|
38
|
+
export interface InferenceSettingsSession {
|
|
39
|
+
tenantId: string;
|
|
40
|
+
/** Whether the session holds `permission` (the host's own check). */
|
|
41
|
+
can(permission: string): boolean;
|
|
42
|
+
}
|
|
43
|
+
export interface InferenceSettingsHost {
|
|
44
|
+
/** The secret store; built on first use, retried after a failure. */
|
|
45
|
+
secrets(): Promise<SecretService>;
|
|
46
|
+
/**
|
|
47
|
+
* The resolver stored API keys are written through and read from: the
|
|
48
|
+
* signed-in user's key, then the tenant's, then the stored tier bindings,
|
|
49
|
+
* then config.
|
|
50
|
+
*/
|
|
51
|
+
userResolver(): UserInferenceResolver;
|
|
52
|
+
/**
|
|
53
|
+
* Register {@link userResolver} for every inference call in this process
|
|
54
|
+
* (the chain validation stays outermost).
|
|
55
|
+
*/
|
|
56
|
+
install(): UserInferenceResolver;
|
|
57
|
+
/**
|
|
58
|
+
* Settings reads, plus writes for a session holding `permission`. An app
|
|
59
|
+
* scope write is allowed for that session; a tenant scope write only for
|
|
60
|
+
* the session's own tenant.
|
|
61
|
+
*/
|
|
62
|
+
settingsService(session: InferenceSettingsSession, permission: string): Promise<InferenceSettingsService>;
|
|
63
|
+
}
|
|
64
|
+
/** Build the host. Nothing touches the database until first use. */
|
|
65
|
+
export declare function createInferenceSettingsHost(options: InferenceSettingsHostOptions): InferenceSettingsHost;
|
|
66
|
+
/**
|
|
67
|
+
* A `{ status, error }` for a failed settings write. The message names no key
|
|
68
|
+
* or secret: authorization failures get a fixed sentence, anything else its
|
|
69
|
+
* own message (key-origin errors never echo the key).
|
|
70
|
+
*/
|
|
71
|
+
export declare function inferenceSettingsFailure(cause: unknown): {
|
|
72
|
+
status: number;
|
|
73
|
+
error: string;
|
|
74
|
+
};
|
|
75
|
+
//# sourceMappingURL=host.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/settings/host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EACL,KAAK,gBAAgB,EAEtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,KAAK,uBAAuB,EAC5B,aAAa,EACd,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,KAAK,0BAA0B,EAEhC,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAIL,KAAK,qBAAqB,EAC3B,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAEjE,wEAAwE;AACxE,MAAM,WAAW,4BAA4B;IAC3C,wDAAwD;IACxD,QAAQ,EAAE,MAAM,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC3C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,uBAAuB,CAAC;IAC5C,8DAA8D;IAC9D,SAAS,EAAE,MAAM,gBAAgB,CAAC;IAClC;;;;OAIG;IACH,WAAW,CAAC,EAAE,IAAI,CAAC,0BAA0B,EAAE,UAAU,CAAC,CAAC;CAC5D;AAED,2CAA2C;AAC3C,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,qEAAqE;IACrE,GAAG,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC;CAClC;AAED,MAAM,WAAW,qBAAqB;IACpC,qEAAqE;IACrE,OAAO,IAAI,OAAO,CAAC,aAAa,CAAC,CAAC;IAClC;;;;OAIG;IACH,YAAY,IAAI,qBAAqB,CAAC;IACtC;;;OAGG;IACH,OAAO,IAAI,qBAAqB,CAAC;IACjC;;;;OAIG;IACH,eAAe,CACb,OAAO,EAAE,wBAAwB,EACjC,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,wBAAwB,CAAC,CAAC;CACtC;AAED,oEAAoE;AACpE,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,4BAA4B,GACpC,qBAAqB,CAyDvB;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG;IACxD,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;CACf,CAYA"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider API keys for an Inference settings page.
|
|
3
|
+
*
|
|
4
|
+
* A key is stored once, as the `inference.provider-config` secret the user
|
|
5
|
+
* resolver reads (`docs/content/inference-settings.md`): the page's
|
|
6
|
+
* `saveKey` action binds it to the endpoint it was entered for, turns it
|
|
7
|
+
* into that stored config, and writes it through the resolver, so a saved
|
|
8
|
+
* key is the key inference calls use. The browser never receives a key back,
|
|
9
|
+
* only whether one is set.
|
|
10
|
+
*
|
|
11
|
+
* Free of any runtime or web framework, so a template app and the app shell
|
|
12
|
+
* share it, tested with a real resolver over a real secret store.
|
|
13
|
+
*/
|
|
14
|
+
import type { UserInferenceResolver } from '../resolver.js';
|
|
15
|
+
/** What the panel's `onSaveKey` posts. */
|
|
16
|
+
export interface InferenceKeyPayload {
|
|
17
|
+
provider: string;
|
|
18
|
+
key: string;
|
|
19
|
+
preset?: string;
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Store the key the owner entered for the signed-in user. `model` is the
|
|
24
|
+
* owner's saved default model (a preset key needs one). Throws
|
|
25
|
+
* `InferenceKeyOriginError` (status 400, names no key) when the key cannot be
|
|
26
|
+
* bound to an endpoint.
|
|
27
|
+
*/
|
|
28
|
+
export declare function saveInferenceKey(resolver: Pick<UserInferenceResolver, 'write'>, change: InferenceKeyPayload, model?: string): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Whether a key is stored for this principal (the user's, else the tenant's),
|
|
31
|
+
* from the resolver's redacted view. A store that cannot be read shows "not
|
|
32
|
+
* set": the page still loads, and the write path reports why.
|
|
33
|
+
*/
|
|
34
|
+
export declare function inferenceKeyIsSet(resolver: Pick<UserInferenceResolver, 'resolveBindings'>): Promise<boolean>;
|
|
35
|
+
//# sourceMappingURL=key-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"key-store.d.ts","sourceRoot":"","sources":["../../src/settings/key-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAG5D,0CAA0C;AAC1C,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,IAAI,CAAC,qBAAqB,EAAE,OAAO,CAAC,EAC9C,MAAM,EAAE,mBAAmB,EAC3B,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAMf;AAED;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,IAAI,CAAC,qBAAqB,EAAE,iBAAiB,CAAC,GACvD,OAAO,CAAC,OAAO,CAAC,CAUlB"}
|
|
@@ -22,8 +22,12 @@ import { InferenceOverrideCollection } from '../models/InferenceOverrideCollecti
|
|
|
22
22
|
import type { InferenceTenantTargetPolicy } from './override-service.js';
|
|
23
23
|
/** Options for {@link createInferenceOverrideResolver}. */
|
|
24
24
|
export interface InferenceOverrideResolverOptions {
|
|
25
|
-
/**
|
|
26
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Database options for the override collection (list bounds are stripped).
|
|
27
|
+
* A function is called once, on the first resolution, so a host can name a
|
|
28
|
+
* runtime that resolves after this resolver is installed.
|
|
29
|
+
*/
|
|
30
|
+
db?: SmrtClassOptions | (() => SmrtClassOptions);
|
|
27
31
|
/** An existing collection instead of `db`. */
|
|
28
32
|
overrides?: InferenceOverrideCollection;
|
|
29
33
|
/** Resolver to defer to for tiers with no stored binding. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../../src/settings/resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAIL,KAAK,iBAAiB,EAKtB,KAAK,gBAAgB,EAEtB,MAAM,0BAA0B,CAAC;AAOlC,OAAO,EAAE,2BAA2B,EAAE,MAAM,0CAA0C,CAAC;AAUvF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AAGzE,2DAA2D;AAC3D,MAAM,WAAW,gCAAgC;IAC/C
|
|
1
|
+
{"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../../src/settings/resolver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAIL,KAAK,iBAAiB,EAKtB,KAAK,gBAAgB,EAEtB,MAAM,0BAA0B,CAAC;AAOlC,OAAO,EAAE,2BAA2B,EAAE,MAAM,0CAA0C,CAAC;AAUvF,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,uBAAuB,CAAC;AAGzE,2DAA2D;AAC3D,MAAM,WAAW,gCAAgC;IAC/C;;;;OAIG;IACH,EAAE,CAAC,EAAE,gBAAgB,GAAG,CAAC,MAAM,gBAAgB,CAAC,CAAC;IACjD,8CAA8C;IAC9C,SAAS,CAAC,EAAE,2BAA2B,CAAC;IACxC,6DAA6D;IAC7D,IAAI,CAAC,EAAE,iBAAiB,CAAC;IACzB,kFAAkF;IAClF,kBAAkB,CAAC,EAAE,2BAA2B,CAAC;IACjD;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAkED,0BAA0B;AAC1B,wBAAgB,+BAA+B,CAC7C,OAAO,GAAE,gCAAqC,GAC7C,iBAAiB,CA0HnB"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,15 +3,17 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-inference",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.61.0",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "4a80a96c9aa5549e3f8fc43ce510101fa4ab9ecb02546f06a408d05d822c1309",
|
|
11
|
+
"packageJson": "e0cc45f73bed6ca0105f2842476bc21aea8aca8b0537c62f9105f005ba504724",
|
|
12
|
+
"agents": "a1708fbd080774788fb1409c9bbe3b775aa11ed1353b61e8a5eff222ca6894ee",
|
|
13
|
+
"moduleDoc:agents/engines.md": "c87be497657f94365f31dab459cace6dffea3d9c93ab43a9fddb0e7fc84f44c1",
|
|
13
14
|
"moduleDoc:agents/resolver.md": "71de7295b6988b27b3b27e2ae82fd71e525ef53613c7714a1deea6c45ba92ef6",
|
|
14
15
|
"moduleDoc:agents/hosted.md": "563141ef3ff09c453de8cfe99db3500da77fa28efe6bc3990e3f84a6cf32653d",
|
|
16
|
+
"moduleDoc:agents/design-runs.md": "a131857521358fad6a6c12f109a5a5df9e7fc088a9d811caf20589a1fafe194a",
|
|
15
17
|
"moduleDoc:agents/fusions.md": "e1dc3f94fe20b1989c8d6e07dbe28e5bd72ae1d327bc3edbc9b8d4365d6dc231",
|
|
16
18
|
"moduleDoc:agents/settings.md": "1ba893ced5676ea41cd10f4454991db7de8c949d93d030ea1d1e78024e9f0cce"
|
|
17
19
|
},
|
|
@@ -24,10 +26,12 @@
|
|
|
24
26
|
"./node",
|
|
25
27
|
"./resolver",
|
|
26
28
|
"./server",
|
|
27
|
-
"./svelte"
|
|
29
|
+
"./svelte",
|
|
30
|
+
"./test-support"
|
|
28
31
|
],
|
|
29
32
|
"dependencies": {
|
|
30
33
|
"@happyvertical/ai": "catalog:",
|
|
34
|
+
"@happyvertical/auth": "catalog:",
|
|
31
35
|
"@happyvertical/smrt-config": "workspace:*",
|
|
32
36
|
"@happyvertical/smrt-core": "workspace:*",
|
|
33
37
|
"@happyvertical/smrt-prompts": "workspace:*",
|
|
@@ -73,6 +77,78 @@
|
|
|
73
77
|
"sensitive-fields-excluded"
|
|
74
78
|
],
|
|
75
79
|
"objects": [
|
|
80
|
+
{
|
|
81
|
+
"name": "DesignRunRecord",
|
|
82
|
+
"qualifiedName": "@happyvertical/smrt-inference:DesignRunRecord",
|
|
83
|
+
"collection": "designrunrecords",
|
|
84
|
+
"description": "Domain checkpoint, not a queue: SmrtJob owns admission, worker liveness and cancellation. Generated mutations are closed; the host's authenticated store binds owner and tenant on every operation.",
|
|
85
|
+
"tableName": "_smrt_inference_design_runs",
|
|
86
|
+
"packageName": "@happyvertical/smrt-inference",
|
|
87
|
+
"extends": "SmrtObject",
|
|
88
|
+
"fields": [
|
|
89
|
+
{
|
|
90
|
+
"name": "ownerId",
|
|
91
|
+
"type": "text",
|
|
92
|
+
"required": true,
|
|
93
|
+
"columnType": "TEXT",
|
|
94
|
+
"default": ""
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"name": "tenantId",
|
|
98
|
+
"type": "text",
|
|
99
|
+
"required": false,
|
|
100
|
+
"columnType": "UUID"
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
"name": "revision",
|
|
104
|
+
"type": "integer",
|
|
105
|
+
"required": false,
|
|
106
|
+
"columnType": "INTEGER",
|
|
107
|
+
"default": 0
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
"name": "payload",
|
|
111
|
+
"type": "text",
|
|
112
|
+
"required": true,
|
|
113
|
+
"columnType": "TEXT"
|
|
114
|
+
}
|
|
115
|
+
],
|
|
116
|
+
"relationships": [],
|
|
117
|
+
"methods": [
|
|
118
|
+
"execute"
|
|
119
|
+
],
|
|
120
|
+
"methodSignatures": [
|
|
121
|
+
{
|
|
122
|
+
"name": "execute",
|
|
123
|
+
"async": true,
|
|
124
|
+
"params": [
|
|
125
|
+
"args: unknown",
|
|
126
|
+
"context?: unknown"
|
|
127
|
+
],
|
|
128
|
+
"returns": "Promise<unknown>"
|
|
129
|
+
}
|
|
130
|
+
],
|
|
131
|
+
"conflictColumns": [
|
|
132
|
+
"tenant_id",
|
|
133
|
+
"slug",
|
|
134
|
+
"context"
|
|
135
|
+
],
|
|
136
|
+
"surfaces": [],
|
|
137
|
+
"withheldSurfaces": [
|
|
138
|
+
{
|
|
139
|
+
"kind": "api",
|
|
140
|
+
"operation": "execute",
|
|
141
|
+
"code": "api-disabled",
|
|
142
|
+
"reason": "api is disabled",
|
|
143
|
+
"objectName": "@happyvertical/smrt-inference:DesignRunRecord"
|
|
144
|
+
}
|
|
145
|
+
],
|
|
146
|
+
"relationshipFeatures": [
|
|
147
|
+
"uuidColumns"
|
|
148
|
+
],
|
|
149
|
+
"tags": [],
|
|
150
|
+
"risks": []
|
|
151
|
+
},
|
|
76
152
|
{
|
|
77
153
|
"name": "InferenceOverride",
|
|
78
154
|
"qualifiedName": "@happyvertical/smrt-inference:InferenceOverride",
|
|
@@ -298,10 +374,15 @@
|
|
|
298
374
|
"junctionCollections": 0,
|
|
299
375
|
"hierarchicalObjects": 0,
|
|
300
376
|
"polymorphicAssociations": 0,
|
|
301
|
-
"uuidColumns":
|
|
377
|
+
"uuidColumns": 6
|
|
302
378
|
},
|
|
303
|
-
"agentDoc": "# smrt-inference\n\nBinding behavior for core's inference tiers (epic #4749). Core owns the names\nand the seam ([core inference.md](../core/agents/inference.md)); this package\nowns alias chains, classified fallback, ladder degradation and\n`smrt doctor --ai` (#4752), the fusion interpreter (#4753), the settings\npanel with layered binding storage (#4754), per-user and per-tenant\nbindings (#4756), candidate capability checks (#4758), and hosted\nprovisioning and the spend gate (#4759, #4760). App-author guide:\n[docs/content/inference.md](../../docs/content/inference.md).\n\n## Entries\n\n- Root (browser-safe): importing it calls `registerInference()`, which sets\n the executor (`alias`, `candidates`, `fusion`) and a validating resolver\n (`setInferenceResolver()`). The resolver binds nothing: it validates chain\n config, then defers to a resolver registered earlier (#4756 per-user\n bindings, `./resolver`) or to core's built-in config resolution. No aliases and no chain\n targets means no change in behavior. `browser-safe.test.ts` holds the graph\n free of `node:`, the AI SDK and smrt-config by walking its import graph;\n the bundle-gate browser fixture also builds it (the package has a model).\n- `./node`: `checkInferenceBindings()`, `probeInferenceCandidate()`,\n `inferenceProbeUrl()`, `formatInferenceDoctorReport()`; the CLI's\n `doctor --ai` and #4754's test connection call these. Also hosted\n provisioning (`src/hosted.ts`, #4759).\n- `./resolver` (Node-only, #4756): `createUserInferenceResolver()` and\n `registerUserInferenceResolver()` over smrt-secrets / tenancy / users. The\n root re-exports only the browser-safe stored-config shape\n (`src/provider-config.ts`): parse, redact, tier → target map.\n- `./models` (browser-safe, held by `browser-safe.test.ts` and the\n bundle-gate browser fixture): the `_smrt_inference_overrides` model;\n generated consumer registration imports it from here.\n- `./server` (Node-only): settings service, override service, override\n resolver, key rule, preference kind (#4754). `./svelte`: the panel.\n- `./gate` (Node-only, #4760): the hosted spend gate and kill switch\n (below). `browser-safe.test.ts` keeps it off the root graph.\n\n## Per-user and per-tenant bindings (#4756)\n\n`createUserInferenceResolver()` resolves per tier: the user's stored config,\nthe tenant's, `fallback`, the app `inference` block, then the configured\nclient; every resolution carries `target.source` (`byo | local | hosted |\napp`, the `source` usage tag). Keys live only in the smrt-secrets type\n`inference.provider-config` (`context = tenantId`), every stored binding is\nself-contained (own `baseUrl` + `apiKey`, or a preset), the user layer\napplies only to a principal of that tenant, and agents pass `userId: null`\n(tenant layer only). The stored config also carries `mode` (#4757).\nDetails: [agents/resolver.md](agents/resolver.md).\n\n## Resolver composition\n\nOne resolver is registered, outermost first: the #4752 validating wrapper,\nthe #4756 user resolver, its `fallback`, then core's config resolution.\nHosts using the #4754 override table pass\n`createInferenceOverrideResolver({ db })` as that `fallback`:\n`registerUserInferenceResolver(createUserInferenceResolver({ db, fallback:\ncreateInferenceOverrideResolver({ db }) }))`. Order per tier: user stored\nbinding, tenant stored binding, allowed tenant override row, app override\nrow, `inference` config, configured client. Keys are stored once, in\n`inference.provider-config`: the host turns #4754's origin-bound\n`bindInferenceKey()` record into a self-contained binding with\n`inferenceProviderConfigFromKey(record, { model })` and writes it through\nthe user resolver's `write(level, config)`; never a second secret type.\n\n## Hosted inference (#4759, #4760)\n\n`./node` provisions per-user gateway keys through `ai.admin` of the\n`bifrost` / `litellm` provider (`SMRT_INFERENCE_HOSTED_*`, read once), storing\nthe key only in the user's `inference.provider-config` (`source: 'hosted'`).\nPlan changes update the key budget, revoke ends local use and then deletes the\nkey (failures are owed and retried by reconcile), and the tenant project is\nlooked up before one is created (`@happyvertical/ai` >= 0.111.7). `./gate`'s\n`registerHostedInferenceGate({ killSwitch, spend })` is core's\n`InferenceGate`: kill switch `inference.hosted.enabled` (a global DISABLE\nalways wins), tenant, entitlement, then plan spend caps; a block throws\n`InferenceUnavailableError` (`entitlement`) and writes a `blocked` usage row.\nDetails: [agents/hosted.md](agents/hosted.md).\n\n## Config\n\n```ts\nconfig({ inference: {\n aliases: { frontier: { candidates: [\n { provider: 'anthropic', model: 'claude-…' }, // provider key var\n { provider: 'openai', model: 'gpt-…', baseUrl, apiKeyEnv }, // own key + endpoint\n { preset: 'lemonade', model: 'qwen…' }, // #4674 preset\n { alias: 'local' }, // expanded in place\n ] } },\n tiers: { great: { alias: 'frontier' }, cheap: { candidates: [ … ] } },\n degrade: true, // default\n} });\n```\n\nA candidate is exactly one of provider/model, preset/model, or alias.\n`apiKeyEnv` is read at call time and needs a `baseUrl` (core's pair rule: a\nkey only travels with its own endpoint); a named variable that is unset skips\nthe candidate as `credential`. `findInferenceConfigIssues()` /\n`validateInferenceConfig()` name every offender by path: empty alias, unknown\nalias (tier or nested), cycle, key without endpoint, unknown preset. The\nexecutor also validates every resolved target it runs (a resolver's chains\nnever pass through config), and a candidate key is never dropped: without\nits own `baseUrl` core's pair rule refuses it.\n\n## Executor (`src/executor.ts`)\n\n- Free of SDK imports: it drives the clients core builds through\n `context.clientFor(target)`; tests use fake clients.\n- Failure classes (`classify.ts`): `quota | credential | missing-model |\n transient | refusal | missing-capability`, from error class names, `code`, `retryable` and HTTP\n status across `cause` / `error` / `context.originalError`, never message\n text. The SDK maps 5xx and other HTTP failures to `API_ERROR` /\n `UNKNOWN_ERROR` without a status or cause (happyvertical/sdk#1493); those\n count as `transient`. A definitive client error that survives in the chain\n (other 4xx, `invalid_request_error`, context length) is not a routing\n failure. Core's typed bind refusal (`INFERENCE_TARGET_UNBOUND`: pair rule,\n `HAVE_AI_*`) is `credential` and advances. Aborts and unclassified errors stop the walk and are rethrown (an\n unclassified one is still recorded).\n- `transient` retries the same candidate once after 200–500 ms of jitter;\n every class then advances. A `refusal` finish reason with nothing streamed\n also advances; finish callbacks are replayed only for the kept answer.\n- Streamed text is never extended: a candidate that emitted text and then\n failed ends the walk with a `partial` substitution and\n `InferenceExhaustedError` (`reason: 'partial'`, `partialText`), unless\n `allowPartial` returns the text. A hosted-gate block (`AI_UNAVAILABLE`\n from `clientFor()`, #4760) stops the walk and records nothing (core wrote\n the `blocked` row). A step whose target names a `source` (a ladder step's\n resolved binding) records that source over the chain's, so hosted spend\n meters as hosted; `expandTarget()` hands a chain's own `source` to its\n candidate steps, so a hosted chain reached on a ladder step is gated in\n `clientFor()` and meters as hosted too. A `stream()` consumer that stops reading\n aborts the provider stream (internal signal merged with the caller's).\n- Ladder: when a tier's chain is spent and `degrade !== false`, resolve the\n next lower tier through `context.resolveTier()`, stopping below\n `minimumTier`. Never up. Steps already tried (same identity) are skipped,\n so unbound lower tiers try the configured client once.\n- Tags on the answering call: caller tags, `tierRequested`, `tierResolved`\n (the tier that answered), and `substitutions` (JSON array of\n `{ from, to, reason }`, labels `provider/model`, `preset:<id>/model`,\n `default`). A call that never answered records one zero-token row through\n `context.recordUsage()` (core's usage handlers; no second writer) with\n `outcome: failed | partial`, `reason` and the full trail ending `to: null` (reason `unclassified` when a non-routing error ended it),\n then throws `InferenceExhaustedError` (`INFERENCE_EXHAUSTED`).\n- Capabilities (#4758): before calling a candidate, a call that sends\n `responseFormat` (JSON) or `tools` checks `context.capabilitiesFor(target)`\n (core's detection, [inference.md](../core/agents/inference.md)). A\n mismatch the caller's `capabilityFallback` option permits (`json: 'text'`,\n `tools: 'drop'`) runs the candidate without the feature, tagged\n `capabilityFallback`; any other is a `missing-capability` substitution and\n the walk advances with no model call. The option never reaches a provider.\n Core's `InferenceUnavailableError` (`reason: 'capability'`) also classifies\n as `missing-capability`. No detector (older core) or no requirement: no\n check. Context limits are core's (single targets only).\n- Add a class to `INFERENCE_FAILURE_CLASSES` and a kind to `EXECUTOR_KINDS`\n (`createChainExecutor()` in `fusion.ts` dispatches on it); consumers\n ignore kinds they do not run.\n\n## Fusions (#4753)\n\n`{ fusion: '<key>' }` tier targets run consumer-defined fusions (`single` 1\ncall, `pair` 3, `handoff` 2) from, highest first, the resolver's stored app\nrows (core's `lookupFusion()`, #4800), `inference.fusions`, or\n`defineFusion()`; every source is re-validated before it runs. SMRT ships the interpreter, never a fusion. Seats are\nsmrt-prompts keys run through `createChainClient()`; a dead seat never\naborts a `pair`, all seats dead throws `InferenceFusionError`; each run writes\none `_smrt_ai_runs` row. Fusions are defined at app scope only; a tenant\nmay bind a tier to an allow-listed fusion, never define one. Details:\n[agents/fusions.md](agents/fusions.md).\n\n## Doctor (`src/node.ts`)\n\nPer tier, alias and fusion (structure only): provider recognized (AI SDK provider list or preset id),\nkey variable present (a provider's default variable only warns: a\nsame-provider target inherits the configured key), model named (warns),\nalias resolvable, cycle-free. `probe` GETs `/models` (OpenAI-compatible,\nAnthropic, Gemini) or Ollama `/api/tags` with a 3 s timeout, sending the key\nonly to its own endpoint. A binding errors when its config is invalid or no\ncandidate can answer; one bad candidate in a working chain warns. Keys never\nappear in the report. With `probe` each candidate also reports its\ncapabilities and their source (#4758, `formatInferenceCapabilities()`): the\nlisting's context length, `supported_parameters` and input modalities\n(`inferenceCapabilitiesFromModelListing()`) are the `probe` layer; the SDK\n`provider` layer only through the `sdkCapabilities` option (the doctor builds\nno SDK clients).\n\n## Settings UI and binding storage (#4754)\n\n`./svelte` `InferenceSettingsPanel`, `./server` `InferenceSettingsService` /\n`InferenceOverrideService` / `createInferenceOverrideResolver()`, `./models`\nthe `_smrt_inference_overrides` model (ships through `smrt db:migrate`).\nKeys go to smrt-secrets through the host and are bound to their endpoint's\norigin; user choices are the smrt-preferences kind `inference`; app/tenant\nbindings are override rows, tenants limited to the app row's allow-list and\nthe `tenantTargetPolicy` hook. The app's transcript setting (#4781) is the\napp-only `transcripts` row, editable in the panel only with `appEditable`,\napplied as core's transcript app settings layer; the Usage tab shows\ntranscript counts and links to a host route, never content. Details: [agents/settings.md](agents/settings.md),\nconsumer guide [docs/content/inference-settings.md](../../docs/content/inference-settings.md).\n\n## Validation\n\n```bash\npnpm --filter @happyvertical/smrt-inference test\npnpm --filter @happyvertical/smrt-inference test:postgres # hosted provisioning on PostgreSQL (advisory lock, runOnce)\npnpm --filter @happyvertical/smrt-inference typecheck\npnpm --filter @happyvertical/smrt-inference build\n```\n",
|
|
379
|
+
"agentDoc": "# smrt-inference\n\nBinding behavior for core's inference tiers (epic #4749). Core owns the names\nand the seam ([core inference.md](../core/agents/inference.md)); this package\nowns alias chains, classified fallback, ladder degradation and\n`smrt doctor --ai` (#4752), the fusion interpreter (#4753), the settings\npanel with layered binding storage (#4754), per-user and per-tenant\nbindings (#4756), candidate capability checks (#4758), and hosted\nprovisioning and the spend gate (#4759, #4760). App-author guide:\n[docs/content/inference.md](../../docs/content/inference.md).\n\n## Entries\n\n- Root (browser-safe): importing it calls `registerInference()`, which sets\n the executor (`alias`, `candidates`, `fusion`) and a validating resolver\n (`setInferenceResolver()`). The resolver binds nothing: it validates chain\n config, then defers to a resolver registered earlier (#4756 per-user\n bindings, `./resolver`) or to core's built-in config resolution. No aliases and no chain\n targets means no change in behavior. `browser-safe.test.ts` holds the graph\n free of `node:`, the AI SDK and smrt-config by walking its import graph;\n the bundle-gate browser fixture also builds it (the package has a model).\n- `./node`: `checkInferenceBindings()`, `probeInferenceCandidate()`,\n `inferenceProbeUrl()`, `formatInferenceDoctorReport()`; the CLI's\n `doctor --ai` and #4754's test connection call these. Also hosted\n provisioning (`src/hosted.ts`, #4759).\n- `./resolver` (Node-only, #4756): `createUserInferenceResolver()` and\n `registerUserInferenceResolver()` over smrt-secrets / tenancy / users. The\n root re-exports only the browser-safe stored-config shape\n (`src/provider-config.ts`): parse, redact, tier → target map.\n- `./models` (browser-safe, held by `browser-safe.test.ts` and the\n bundle-gate browser fixture): the `_smrt_inference_overrides` model;\n generated consumer registration imports it from here.\n- `./server` (Node-only): settings service, override service, override\n resolver, key rule, preference kind (#4754); local CLI turns, ChatGPT model\n rounds and connection diagnostics ([agents/engines.md](agents/engines.md)).\n `./svelte`: the panel.\n- `./test-support` (Node-only): shared fake CLI installers and isolated lookup\n dependencies for engine/host tests; fixture source is bundled, never run on\n real credentials ([agents/engines.md](agents/engines.md)).\n- `./gate` (Node-only, #4760): the hosted spend gate and kill switch\n (below). `browser-safe.test.ts` keeps it off the root graph.\n\n## Per-user and per-tenant bindings (#4756)\n\n`createUserInferenceResolver()` resolves per tier: the user's stored config,\nthe tenant's, `fallback`, the app `inference` block, then the configured\nclient; every resolution carries `target.source` (`byo | local | hosted |\napp`, the `source` usage tag). Keys live only in the smrt-secrets type\n`inference.provider-config` (`context = tenantId`), every stored binding is\nself-contained (own `baseUrl` + `apiKey`, or a preset), the user layer\napplies only to a principal of that tenant, and agents pass `userId: null`\n(tenant layer only). The stored config also carries `mode` (#4757).\nDetails: [agents/resolver.md](agents/resolver.md).\n\n## Resolver composition\n\nOne resolver is registered, outermost first: the #4752 validating wrapper,\nthe #4756 user resolver, its `fallback`, then core's config resolution.\nHosts using the #4754 override table pass\n`createInferenceOverrideResolver({ db })` as that `fallback`:\n`registerUserInferenceResolver(createUserInferenceResolver({ db, fallback:\ncreateInferenceOverrideResolver({ db }) }))`. Order per tier: user stored\nbinding, tenant stored binding, allowed tenant override row, app override\nrow, `inference` config, configured client. Keys are stored once, in\n`inference.provider-config`: the host turns #4754's origin-bound\n`bindInferenceKey()` record into a self-contained binding with\n`inferenceProviderConfigFromKey(record, { model })` and writes it through\nthe user resolver's `write(level, config)`; never a second secret type.\n\n## Hosted inference (#4759, #4760)\n\n`./node` provisions per-user gateway keys through `ai.admin` of the\n`bifrost` / `litellm` provider (`SMRT_INFERENCE_HOSTED_*`, read once), storing\nthe key only in the user's `inference.provider-config` (`source: 'hosted'`).\nPlan changes update the key budget, revoke ends local use and then deletes the\nkey (failures are owed and retried by reconcile), and the tenant project is\nlooked up before one is created (`@happyvertical/ai` >= 0.111.7). `./gate`'s\n`registerHostedInferenceGate({ killSwitch, spend })` is core's\n`InferenceGate`: kill switch `inference.hosted.enabled` (a global DISABLE\nalways wins), tenant, entitlement, then plan spend caps; a block throws\n`InferenceUnavailableError` (`entitlement`) and writes a `blocked` usage row.\nDetails: [agents/hosted.md](agents/hosted.md).\n\n## Sign in with ChatGPT (`src/chatgpt/`, `./server`)\n\nLocal profile only; a PREVIEW for open source apps\n([limitations](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations)).\n`createChatGPTPlanConnection({ appName, credentialsPath })` wraps the SDK's\n`LocalChatGPTSessionManager` (`@happyvertical/auth/local`, loaded lazily): the\nSDK's own owner-only file at `credentialsPath` is the only credential store;\nsmrt never reads it, and no result, log or error carries a token (status is\n`signedIn`, `signingIn`, an account label, a fixed-vocabulary error;\n`clientOptions()` hands the provider `{ accessToken }` only). `start()` returns\nthe URL only after checking https on `auth.openai.com`. The resolver\n(`createChatGPTPlanResolver`, composed outside the user resolver by\n`createInferenceSettingsHost({ chatgptPlan })`) answers only calls whose\n`appliesTo` is true: `chatgpt-plan` with `source: 'byo'` when signed in,\n`unavailable: 'unconfigured'` otherwise, never an API-key fallback, never a\ndefault. The provider rejects `maxTokens`, sampling, `user`, response formats,\nreasoning, forced single-function `toolChoice` and `stream()` with tools; the\ncaller sends none of them (`classifyChatGPTPlanFailure` names the failures).\nGuide: [docs/content/inference-settings.md](../../docs/content/inference-settings.md).\n\n[Owner work profiles and durable design runs](agents/design-runs.md).\n\n## Config\n\n```ts\nconfig({ inference: {\n aliases: { frontier: { candidates: [\n { provider: 'anthropic', model: 'claude-…' }, // provider key var\n { provider: 'openai', model: 'gpt-…', baseUrl, apiKeyEnv }, // own key + endpoint\n { preset: 'lemonade', model: 'qwen…' }, // #4674 preset\n { alias: 'local' }, // expanded in place\n ] } },\n tiers: { great: { alias: 'frontier' }, cheap: { candidates: [ … ] } },\n degrade: true, // default\n} });\n```\n\nA candidate is exactly one of provider/model, preset/model, or alias.\n`apiKeyEnv` is read at call time and needs a `baseUrl` (core's pair rule: a\nkey only travels with its own endpoint); a named variable that is unset skips\nthe candidate as `credential`. `findInferenceConfigIssues()` /\n`validateInferenceConfig()` name every offender by path: empty alias, unknown\nalias (tier or nested), cycle, key without endpoint, unknown preset. The\nexecutor also validates every resolved target it runs (a resolver's chains\nnever pass through config), and a candidate key is never dropped: without\nits own `baseUrl` core's pair rule refuses it.\n\n## Executor (`src/executor.ts`)\n\n- Free of SDK imports: it drives the clients core builds through\n `context.clientFor(target)`; tests use fake clients.\n- Failure classes (`classify.ts`): `quota | credential | missing-model |\n transient | refusal | missing-capability`, from error class names, `code`, `retryable` and HTTP\n status across `cause` / `error` / `context.originalError`, never message\n text. The SDK maps 5xx and other HTTP failures to `API_ERROR` /\n `UNKNOWN_ERROR` without a status or cause (happyvertical/sdk#1493); those\n count as `transient`. A definitive client error that survives in the chain\n (other 4xx, `invalid_request_error`, context length) is not a routing\n failure. Core's typed bind refusal (`INFERENCE_TARGET_UNBOUND`: pair rule,\n `HAVE_AI_*`) is `credential` and advances. Aborts and unclassified errors stop the walk and are rethrown (an\n unclassified one is still recorded).\n- `transient` retries the same candidate once after 200–500 ms of jitter;\n every class then advances. A `refusal` finish reason with nothing streamed\n also advances; finish callbacks are replayed only for the kept answer.\n- Streamed text is never extended: a candidate that emitted text and then\n failed ends the walk with a `partial` substitution and\n `InferenceExhaustedError` (`reason: 'partial'`, `partialText`), unless\n `allowPartial` returns the text. A hosted-gate block (`AI_UNAVAILABLE`\n from `clientFor()`, #4760) stops the walk and records nothing (core wrote\n the `blocked` row). A step whose target names a `source` (a ladder step's\n resolved binding) records that source over the chain's, so hosted spend\n meters as hosted; `expandTarget()` hands a chain's own `source` to its\n candidate steps, so a hosted chain reached on a ladder step is gated in\n `clientFor()` and meters as hosted too. A `stream()` consumer that stops reading\n aborts the provider stream (internal signal merged with the caller's).\n- Ladder: when a tier's chain is spent and `degrade !== false`, resolve the\n next lower tier through `context.resolveTier()`, stopping below\n `minimumTier`. Never up. Steps already tried (same identity) are skipped,\n so unbound lower tiers try the configured client once.\n- Tags on the answering call: caller tags, `tierRequested`, `tierResolved`\n (the tier that answered), and `substitutions` (JSON array of\n `{ from, to, reason }`, labels `provider/model`, `preset:<id>/model`,\n `default`). A call that never answered records one zero-token row through\n `context.recordUsage()` (core's usage handlers; no second writer) with\n `outcome: failed | partial`, `reason` and the full trail ending `to: null` (reason `unclassified` when a non-routing error ended it),\n then throws `InferenceExhaustedError` (`INFERENCE_EXHAUSTED`).\n- Capabilities (#4758): before calling a candidate, a call that sends\n `responseFormat` (JSON) or `tools` checks `context.capabilitiesFor(target)`\n (core's detection, [inference.md](../core/agents/inference.md)). A\n mismatch the caller's `capabilityFallback` option permits (`json: 'text'`,\n `tools: 'drop'`) runs the candidate without the feature, tagged\n `capabilityFallback`; any other is a `missing-capability` substitution and\n the walk advances with no model call. The option never reaches a provider.\n Core's `InferenceUnavailableError` (`reason: 'capability'`) also classifies\n as `missing-capability`. No detector (older core) or no requirement: no\n check. Context limits are core's (single targets only).\n- Add a class to `INFERENCE_FAILURE_CLASSES` and a kind to `EXECUTOR_KINDS`\n (`createChainExecutor()` in `fusion.ts` dispatches on it); consumers\n ignore kinds they do not run.\n\n## Fusions (#4753)\n\n`{ fusion: '<key>' }` tier targets run consumer-defined fusions (`single` 1\ncall, `pair` 3, `handoff` 2) from, highest first, the resolver's stored app\nrows (core's `lookupFusion()`, #4800), `inference.fusions`, or\n`defineFusion()`; every source is re-validated before it runs. SMRT ships the interpreter, never a fusion. Seats are\nsmrt-prompts keys run through `createChainClient()`; a dead seat never\naborts a `pair`, all seats dead throws `InferenceFusionError`; each run writes\none `_smrt_ai_runs` row. Fusions are defined at app scope only; a tenant\nmay bind a tier to an allow-listed fusion, never define one. Details:\n[agents/fusions.md](agents/fusions.md).\n\n## Doctor (`src/node.ts`)\n\nPer tier, alias and fusion (structure only): provider recognized (AI SDK provider list or preset id),\nkey variable present (a provider's default variable only warns: a\nsame-provider target inherits the configured key), model named (warns),\nalias resolvable, cycle-free. `probe` GETs `/models` (OpenAI-compatible,\nAnthropic, Gemini) or Ollama `/api/tags` with a 3 s timeout, sending the key\nonly to its own endpoint. A binding errors when its config is invalid or no\ncandidate can answer; one bad candidate in a working chain warns. Keys never\nappear in the report. With `probe` each candidate also reports its\ncapabilities and their source (#4758, `formatInferenceCapabilities()`): the\nlisting's context length, `supported_parameters` and input modalities\n(`inferenceCapabilitiesFromModelListing()`) are the `probe` layer; the SDK\n`provider` layer only through the `sdkCapabilities` option (the doctor builds\nno SDK clients).\n\n## Settings UI and binding storage (#4754)\n\n`./svelte` `InferenceSettingsPanel`, `./server` `InferenceSettingsService` /\n`InferenceOverrideService` / `createInferenceOverrideResolver()`, `./models`\nthe `_smrt_inference_overrides` model (ships through `smrt db:migrate`).\nKeys go to smrt-secrets through the host and are bound to their endpoint's\norigin; user choices are the smrt-preferences kind `inference`; app/tenant\nbindings are override rows, tenants limited to the app row's allow-list and\nthe `tenantTargetPolicy` hook. The app's transcript setting (#4781) is the\napp-only `transcripts` row, editable in the panel only with `appEditable`,\napplied as core's transcript app settings layer; the Usage tab shows\ntranscript counts and links to a host route, never content. Details: [agents/settings.md](agents/settings.md),\nconsumer guide [docs/content/inference-settings.md](../../docs/content/inference-settings.md).\n`./server` also ships the framework-free host wiring both the template and\nthe app shell use: `createInferenceSettingsHost` (secret store under the\nruntime's master key, user resolver over the override resolver, settings\nservice with its authorizer), `createInferenceSettingsController` (the\npanel's `load` and writes, gated on `inference.customize`; a refusal and a\nkey-origin error name no key), and `saveInferenceKey` / `inferenceKeyIsSet`.\nA host supplies only its session check, preference store and routes.\n\n## Validation\n\n```bash\npnpm --filter @happyvertical/smrt-inference test\npnpm --filter @happyvertical/smrt-inference test:postgres # hosted provisioning on PostgreSQL (advisory lock, runOnce)\npnpm --filter @happyvertical/smrt-inference typecheck\npnpm --filter @happyvertical/smrt-inference build\n```\n",
|
|
304
380
|
"moduleDocs": [
|
|
381
|
+
{
|
|
382
|
+
"path": "agents/engines.md",
|
|
383
|
+
"module": "engines",
|
|
384
|
+
"content": "# Local assistant engines (`./server`)\n\n## Codex containment (owner-authorized 2026-11-12 policy)\n\nCodex 0.162.1 is usable. Enable **only `code_mode_host`** (when protection is on) in addition to the\nexisting modern MCP protocol feature. The host necessarily registers\n`apply_patch`; shell/unified execution and all other optional machine features\nstay disabled. Every Codex attempt (including resume/fallback) now gets a NEW\nempty 0700 `<engine state>/run/turn-*/work` folder, removed in the existing\nfinally cleanup after completion, error, abort and timeout. Concurrent turns\nnever share it. User config/rules are ignored; project document bytes are zero\nand bundled skills disabled. Schema/config files remain outside the writable\ncwd and contain no credential.\n\nExact containment overrides: `sandbox_mode=\"workspace-write\"`,\n`sandbox_workspace_write.network_access=false`,\n`sandbox_workspace_write.writable_roots=[]`,\n`sandbox_workspace_write.exclude_slash_tmp=true`,\n`sandbox_workspace_write.exclude_tmpdir_env_var=true`,\n`approval_policy=\"never\"`, `web_search=\"disabled\"`,\n`shell_environment_policy.inherit=\"none\"`. No bypass, add-dir, full access or\nterminal approval. Native sandbox policy controls writes/network, not parser\ninspection after an effect. It permits reads according to platform policy; an\nempty cwd is not a read-visibility jail. Provider and loopback MCP HTTP transports\nrun in the CLI parent; sandboxed model commands cannot use the network or inherit\nthe app's MCP token. API keys remain stripped from the CLI parent environment.\n\nThe secured spec opts `codexParser` into recognizing only `file_change` and\n`command_execution` as confined built-ins. Record `agent_tool_confined` plus\nfixed `apply_patch`/`exec_command` names, never their payload/path/output; continue\nthe app request. Unknown items, foreign MCP and unoffered app tools still stop\nwith W1's redacted name diagnostics. App mutations still require the existing\nscoped MCP dispatcher and durable independent owner approval. Existing work\nprofiles, one-step classified fallback and child-group kill/timeout are retained.\nCodex maximum effort maps to xhigh; explicit model remains `-m`.\n\nReadiness exercises the exact invocation's help plus startup in a disposable\nHOME/CODEX_HOME with no auth, token, proxy or reachable model endpoint; abort at\n`turn.started`. Compatible 0.162.1 now passes; incompatible versions still return\nplain `tool_host_policy` or invocation failure. This is a cheap local startup\npreflight, not a billed inference test or proof of account entitlement.\n\nVerified flags: installed `codex exec --help` 0.162.1 and\n[OpenAI configuration reference](https://learn.chatgpt.com/docs/config-file/config-reference).\nA separate native `codex sandbox -P smrt` control used a named profile with\n`filesystem={\"/\"=\"read\",\":workspace_roots\"=\"write\"}` and\n`network.enabled=false`: writing inside succeeded, a sibling write and connection\nto a listening loopback HTTP socket were denied. This tests OS enforcement, not\na model response; the production exec uses the equivalent workspace overrides.\n\n| Invariant / reachable trigger | Positive | Negative/control | Actor/context, executor/runtime | Edge / level / validation |\n| --- | --- | --- | --- | --- |\n| Private Codex attempts, including resume | Distinct empty 0700 roots, own-file writes disappear at cleanup | Failure/abort/timeout and concurrent runs cannot share cwd | Local owner, no DB executor; Node26 subprocess | CLI spec/stub; inference test |\n| Confined incidental builtins | Patch/command item logs only fixed names, request finishes | Unknown item/foreign MCP/unoffered app tool still kills; token/arguments absent | Owner-bound app authority; OS sandbox independent of DB | Stream + full stub turn; inference test |\n| Ready/startup | Native compatible CLI and stub with code host starts | Unsupported flags/host, missing runtime, signed-out, directory failure | Local process; no model request | Preflight; inference + exact desktop env tests |\n| Ranked OpenAI choices/fallback | Strongest verified offered model, one lower on classified pre-output refusal, fixed wording/memo | Unknown IDs never guessed; no retry after text/tool, no engine/key fallback | Owner/account/catalog generation; existing preference store | Fake sign-in/catalog/model + host tests |\n| Live app data / Stop | Live read/create via scoped MCP and Stop kills child; fixture held delete decided once | Customer delete remains absent; UI never decides through a model tool | Local owner/tenant, SQLite generated tools | Built product; docs/qa-live-engines.md |\n\nReuse: configured MCP reviewed inference/Svelte/template/app-shell and architecture\ncontext queried disposable sandboxes, rank/fallback and connection composition.\nName + purpose `rg` in UI/Svelte/chat/core/inference found `buildAgentRun`,\n`runProcess`, `codexParser`, `reportAgentFailure`, `strongestWorkModel`,\n`runWorkModelWithFallback` and the existing connection catalog. Extend these\nowning modules. New `rankOpenAIWorkModels`/`nextWorkModel` live in the existing\nwork-profiles module; no parallel engine, approval service or credential reader.\n\n## Historical 2026-11-11 incompatibility evidence (superseded by containment above)\n\nNative probes on the installed CLI use its default model, disposable empty\nHOME/CODEX_HOME, a loopback fake Responses provider with auth disabled, and one\nfixture MCP read tool. No provider credential, account request or real model\nturn is used. The fake reply only enumerates the host's tool registry and, in\nthe MCP-call control, invokes that fixture read. No built-in file/shell tool is\nexecuted. These are protocol facts, not a claim of complete OS sandbox testing.\n\nCommon invocation: `exec --json --skip-git-repo-check --ignore-user-config\n--ignore-rules`, prompt on stdin, private empty cwd, `--enable mcp_2026_07_28`,\nand `-c sandbox_mode=\"read-only\" -c approval_policy=\"never\"\n-c web_search=\"disabled\"`. The app server is loopback, `required=true`, with\n`bearer_token_env_var` naming the existing environment variable; no token goes\nin argv or files. `default_tools_approval_mode=\"approve\"` refers only to MCP\ntransport: the server still owns permissions and independent owner holds.\n\nBaseline `--disable` features: `shell_tool`, `unified_exec`, `apps`, `plugins`,\n`hooks`, `multi_agent`, `multi_agent_v2`, `view_image`, `image_generation`,\n`browser_use`, `computer_use`, `in_app_browser`, `memories`, `skill_search`,\n`tool_suggest`, `goals`, `code_mode`, `code_mode_host`,\n`request_permissions_tool`. Native `features list` in the disposable home also\nreports `apply_patch_freeform` as **removed/false**, not an available kill switch.\n\n| Option tried (changes from baseline only) | Native result | Capability/security consequence |\n| --- | --- | --- |\n| No change: code host disabled | MCP discovery/list succeeds, but its tool is absent from the model registry; native execution returns `code-mode host is disabled` | Current supported app policy: fail closed as `tool_host_policy`; no model turn is started by readiness. |\n| Enable only `code_mode_host` | Registry contains `mcp__smrt__probe` **and `apply_patch`**; fixture `tools/call` succeeds with protocol 2026-07-28 | App MCP works, but the model retains a built-in filesystem-editing interface. Read-only sandbox and never-approve remain; this does not satisfy “built-ins absent”. Not enabled by SMRT. |\n| Also enable `code_mode_only_strict_3p_tools` | Same MCP + `apply_patch` registry | The strict flag does not remove the built-in tool. Not enabled. |\n| Also enable both `code_mode_only` and `code_mode_only_strict_3p_tools` | Same registry | Combining the strict flags still does not yield MCP-only tools. Not enabled. |\n| Enable `code_mode_host` and `code_mode` | Same registry | Legacy code-mode flag does not remove `apply_patch`. Not enabled. |\n| Enable `code_mode_host` and `shell_tool` (keep `unified_exec` disabled) | Also registers `exec_command` and `write_stdin` | Adds a model-visible shell interface. Read-only/never-approve are narrower than full access but are not an app-only capability boundary. Not enabled. |\n\nThe empty cwd is not a filesystem visibility jail. A read-only sandbox permits\ninspection according to its platform policy; it does not prove that arbitrary\nabsolute paths outside the cwd are invisible. No write/network boundary bypass\nwas attempted, and no platform-wide enforcement guarantee is inferred from\nregistry enumeration. Provider/MCP transport access is separate from a spawned\ncommand's network policy. See the official [sandbox contract](https://learn.chatgpt.com/docs/sandboxing)\nand [CLI flags](https://learn.chatgpt.com/docs/cli/reference).\n\nOwner choices are: retain this refusal and use a compatible engine; request an\nupstream built-in-tool allow-list/MCP-only host; or explicitly review a broader\nfilesystem/shell policy in a separate change. This implementation adopts only\nthe first choice. Connect AI says “Not supported with this Codex version yet”\nand explains the file-tool conflict. No model downgrade, API billing fallback,\ncode-host enable or sandbox weakening is implemented.\n\nCodex's app MCP server is required: it waits for the live catalog within its\nstartup timeout instead of continuing after the optional-server grace period\nwith no app tools. A failed required MCP startup reports fixed app-connection\nwords and a correlated `agent_mcp_unavailable` diagnostic, never child output.\nAll machine-tool, user-settings, token and loopback restrictions remain intact.\n\nThe legacy `assistant token failed:` diagnostic remains for LocalRuntimeError\ntoken failures, using a fixed class label and allow-listed code only. It follows\nthe correlated failure record; arbitrary error names/messages are never logged.\n\n`src/agent-cli/` owns discovery, CLI-reported authentication, login processes,\nlocked-down subprocess invocation, parsing, the process-tree lifetime, MCP token\nlifetime and a subprocess-owned turn. `src/chatgpt/model.ts` adapts one model\nround; `src/engine-model.ts` defines its model seam. `src/engine-status.ts`\ncomposes connection diagnostics without selecting a default engine.\n\nThese modules never import app-shell, smrt-chat, app-runtime, a web framework or\na host model. Keep all value exports on `./server`; root and `./models` stay\nbrowser-safe. Plain product labels are metadata, not branded UI.\n\n## Two host contracts\n\nA chat-style host calls `createChatGPTModel({ connection, model?, toolNamespace,\nsettingsHref? })` then `EngineModel.complete({ messages, tools, maxTokens, signal,\nonText })` for each round. It executes returned `toolCalls` through its own\npolicy, persists history and replays `raw` provider calls and tool responses.\nOnly `chat()` + `onProgress` reach the plan; token limits, sampling, reasoning,\nresponse formats, user, forced tool choice and stream flags never do. The host\nmust bound total rounds/time/tokens. `EngineModelFailure` carries safe fixed\nwords and an optional host route; arbitrary provider errors need a generic\nhost error handler. Never expose/log an error's message, cause or SDK options.\nThere is no API-key fallback. Connection `clientOptions()` is the only credential\nsource; resolver selection remains explicit (`createChatGPTPlanResolver` with\n`appliesTo` and host-verified principal). The SDK owns its credential file.\n\nA subprocess host calls `runAgentTurn({ text, tool, mcpUrl, signal, emit, deps,\nhost })`. `tool` is `claude-code` or `codex`:\n\n- `deps.locate`, `stateDir`, `baseEnv?`, `limits?` supply a discovered executable,\n private app-owned state directory, base environment and time/result bounds.\n- `deps.credentials` supplies `mint`/`revoke`. `tokenCredentials(store,\n { holder, label, scopes })` adapts app-runtime's local MCP token store\n structurally, with no dependency on app-runtime. The host verifies the owner\n first, uses a distinct holder per concurrently active conversation, and\n scopes the token to its policy. Tokens expire after 15 minutes by default;\n custom turn bounds must stay below that or supply a longer-lived credential\n implementation. Never persist the returned secret.\n- `host.appendMessage` and `lastSession` own authenticated storage/session\n continuity. `guidance()` returns the system guidance and current-turn prompt;\n it runs again if an expired CLI session must restart.\n- `host.allowTool` is a stream guard. The authenticated MCP endpoint must also\n enforce the tool policy; stream inspection is no replacement for authorization.\n- `host.approvals.subscribe/get` supplies only approvals belonging to this turn\n and owner. It is an observation interface, with no approval decision method.\n Correlation follows serial tool results in order; unrelated events must be\n filtered by the host. `describeResult` supplies UI words and optional host\n metadata (`details`, also persisted on the tool message); `completionNote?`\n supplies a closing note for host-specific state such as drafts.\n\nThe host publishes canonical pending holds before returning a tool response.\nA fast independent decision may already be approved/denied when inference reads\nit; it remains a held call and emits the existing approval event, never an\nordinary successful result that bypasses chat's protected-result guard. Both CLI\nfixtures cover pending, early-approved and early-denied correlation. Model output\ndoes not supply approval identity or authority.\n- `emit` receives text, tool_call, tool_result, approval_required,\n approval_decided, done and error events. `done.stop` is complete, waiting,\n aborted, timeout or error. Pending approvals return waiting; only the owner's\n independent UI/authority can approve. Host callback/storage failures propagate\n after process and token cleanup. CLI exit output is never forwarded.\n\n## Security invariants\n\nAllow-list child environment variables: no provider API keys, endpoint overrides\nor host secrets. Token only in child environment, never argv, logs or config\nfiles. MCP must use HTTP loopback (127.0.0.1, localhost or ::1). Claude built-ins\nare absent. Codex enables only its necessary code host and confines its patch\ncapability as specified above; shell, web and subagent features stay disabled.\nUser config/hooks/plugins are ignored. Codex workspaces are private, empty and\nnew per attempt. Stream guards reject foreign tools\nand unknown Codex action kinds. Stop/timeout kills the process group (Windows\nuses taskkill /T). CLI credentials are never read: query the CLI's own status\nand run its own login command, which opens the vendor page itself.\n\nClaude's `StructuredOutput` is accepted only when the host supplies\n`outputSchema` (and thus `--json-schema`). It is a result channel: its call\nand correlated result never become executable app tools or tool messages;\nonly the final `structured_output` is published, with intermediate prose\nsuppressed. Without a host schema it remains forbidden. All CLI lockdown\nflags stay intact. Blocked tools report a bounded ASCII name (unsafe names\nbecome `unknown`) and `builtin`, `unoffered_mcp`, or `unknown_item` in the\ncorrelated guard diagnostic and safe error message, never their arguments.\n\nNative continuation proof (2026-11-12 UTC): a fresh built product chat request\nescalated before `app.addField` executed, then completed all three v2 design\npasses with the exact core-owned proposal (`Members`, `Visit note`, text,\n`expectedRevision: 1`). Each requested `fable` / maximum effort and reported\n`claude-fable-5-1`; provider-reported effort was unavailable. Pass duration,\ntokens and app-tool calls were respectively 26783 ms / 53618 / 1,\n28841 ms / 54889 / 1, and 26331 ms / 56277 / 1. All three accepted the native\n`StructuredOutput` channel; no schema repair or write occurred. The identical\nschema-enabled formatter event is forbidden by the base parser and accepted\nas a non-executable result channel by this parser. Without a host schema it\nremains forbidden. The earlier v1 proof completed its passes but could not\nprepare a supported operation because write schemas were absent; v2 supplies\ntheir metadata while retaining read-only execution. This proves proposal\ncompletion, not final Apply, which requires the trusted durable host action seam.\n\nDo not offer in-app Claude subscription login or proxy/store its credentials.\nThe person uses their own unmodified Claude Code CLI and its vendor login.\nChatGPT plan sign-in is a separate, opt-in preview for local open-source apps;\nkeep its published limitations visible to users.\n\n## Diagnostics and tests\n\n`createAgentCliService()` creates a host-local 15-second detection cache and\nlogin manager. `inferenceEngineStatus(engine, host)` asks only the selected\nengine: host `apiStatus`, connection `status`, or CLI `cliStatus`. Host `actions`\nprovide navigation; inference has no hard-coded application routes.\n\n`agent-cli/{detect,session,turn}.test.ts`, `engine-status.test.ts` and\n`chatgpt/{model,support}.test.ts` use stub executables/fake providers only.\nThey cover missing/signed-out/unknown status, cache isolation, key stripping,\nsecret-free args/config/events/messages/logs, loopback rejection, built-in tool\nlockdown, fail-closed guards, session continuity, tree death on abort/timeout,\ntoken cleanup, model option restrictions, raw call replay and classified errors.\nApp-shell keeps integration tests for its real MCP owner policy, approvals,\ndrafts, guidance, persistence, sign-in resolver selection and settings routes.\n\nRun package build/test/typecheck as documented in AGENTS.md. No live CLI or\nprovider account is needed. PostgreSQL tests remain optional and unrelated to\nthese Node subprocess/model adapters.\n\n## Reuse audit for the C2 extraction\n\nAudited against base `06c0b64fe3`, including every added source file and its\nexported types, helpers and constants. C2 adds no component, model, route or\nMCP tool definition. CLI product/tool metadata and stream/model/host contracts\nare the API introduced by moving existing shell behavior to its owning package.\n\nDiscovery used the configured **smrt-dev-mcp** server's\n`review_smrt_project({ directory, detectDuplicates: true,\nincludeSourceEvidence: true })` on inference and app-shell, and\n`build_context({ task: 'architecture', idea, rootDir })` for these purpose\nqueries: \"local Claude Code/Codex CLI detection login sanitized environment\nprocess tree MCP token invocation stream parser\"; \"ChatGPT plan model adapter\nmodel round connection diagnostics authorization browser owner approval\nobservation fake CLI fixtures\". `build_package_specialist_context` for inference\nchecked the proposed shared test entry. This server exposes architecture lookup\nand manifest object lists; it has no standalone component/intent/recipe search\ntool. The intent index and local source/catalog searches fill that gap.\n\nRead `docs/knowledge/intents/index.md`, especially local credentials, prompts/AI,\nauth and human approvals. Run name and purpose searches with `rg -n` over\n`packages/{smrt-ui,smrt-svelte,chat,core,inference,app-runtime,smrt-app-mcp,cli,agents}`,\nthen repository-wide production-source searches. Also inspect\n`smrt-desktop/src/bundler/{runtime,child-env}.ts`, `planner/src/lib/assistant/models.ts`,\n`vitest/src/{index,test-db}.ts`, and the recipe/component knowledge catalogs.\nThe exact source audit is below; internal parsing/lookup helpers belong to the\nsame protocol implementation as their exported entry points.\n\n| New source file (under `src/`) | Names/purpose searched | Existing capability reused or reason to retain |\n| --- | --- | --- |\n| `agent-cli/credentials.ts` | `AgentCredentials`, `McpTokenStoreLike`, `tokenCredentials`, `AGENT_TOKEN_TTL_SECONDS`; owner token mint/revoke/holder | Adapts app-runtime's existing `LocalMcpTokenStore.issue/revokeHolder`. No credential store added; structural interface prevents an inference-to-runtime dependency. |\n| `agent-cli/detect.ts` | `AgentCliStatus`, `AgentCliLocation`, `cliEnv`, `locateCli`, `detectAgentCli(s)`, `versionOf`, `signedInFrom`; version/status parsing | Moves shell's existing CLI command-based discovery. Inference doctor probes provider endpoints, not installed CLI sessions. No equivalent in core/chat/UI/agents. |\n| `agent-cli/env.ts` | `childEnv`, `nodeDir`, `allowed`; provider-key stripping, allow-list child environment | Desktop `buildChildEnv` forces build locale/npm policy, rejects MCP-token extras and omits CLI sign-in location variables. Its build-process contract is unsuitable; retain the existing shell CLI-specific allow-list. |\n| `agent-cli/locate.ts` | `LocateDeps`, `defaultLocateDeps`, `candidateDirs`, `locateBinary`, `isExecutable`, `listDirs`, `names`, `findIn`, `viaLoginShell`; executable/PATH/login-shell lookup | Existing CLI/desktop runtime launchers run known binaries; none locate the owner's agent CLI in user install directories without credential reads. Moves shell's lookup and its private filesystem/name helpers. |\n| `agent-cli/login.ts` | `AgentLogin`, `LoginSnapshot`, `LoginState`, `Running`, `LOGIN_TIMEOUT_MS`; vendor-owned CLI login | Reuses the CLI's own login/status commands, not a new auth/session store. app-runtime owner setup and users' browser sessions are different identities. |\n| `agent-cli/runner.ts` | `RunOptions`, `RunResult`, `CollectResult`, `runProcess`, `runCollect`, `killTree`, `killNow`, `hookExit`; bounded stdin/stdout/stderr, process-group cleanup | Desktop bundler process tracking and ingestion extraction are private, different lifetime contracts. No public reusable runner supplies this stream/stdin/abort/timeout/redaction contract. Preserve the shell runner and private kill/exit hooks. |\n| `agent-cli/service.ts` | `createAgentCliService`, `configureAgentCli`, `invalidateCliStatus`, `agentLogin`, `cliStatus`, `allCliStatus`, private `deps`; host-local detection cache/login lifecycle | Composes the moved detector/login manager; no existing CLI status cache. Inference settings cache stores settings, not installed CLI authentication. |\n| `agent-cli/session.ts` | `AgentRunSpec`, `SpecInput`, `TOKEN_ENV`, `assertLoopbackUrl`, `buildAgentRun`, `toml`, `claudeSpec`, `codexSpec`; MCP-only Claude/Codex invocation | Moves shell's locked-down CLI protocol. MCP auth's private `validateUrl` permits HTTPS and forbids query scopes; desktop route grammar is path-only. Neither replaces this HTTP-loopback URL guard. Private TOML/spec helpers encode vendor-specific flags. |\n| `agent-cli/stream.ts` | `AgentEvent`, `MCP_SERVER_NAME`, `shellToolName`, `claudeParser`, `codexParser`, `obj`, `str`, `parse`, `textOfContent`; fail-closed CLI event normalization | Chat's model/tool-loop progress does not parse vendor subprocess JSON. Preserve the shell protocol parsers and their internal JSON/text helpers. |\n| `agent-cli/tools.ts` | `AgentTool`, `AgentToolInfo`, `AGENT_TOOLS`, `AGENT_TOOL_INFO`, `isAgentTool`; CLI product metadata | Moves the existing shell metadata; no new application tools. Core recipe/cookbook model metadata describes a different noun. |\n| `agent-cli/turn.ts` | `AgentTurnStop/Event/Limits/Message/Options/Host`, `AgentEngineDeps`, `runAgentTurn`, `tokenFailureMessage`, `tokenFailureCode`, `cut`; result cutting | Moves shell turn behavior behind host callbacks. Chat `runAssistantTurn` owns a provider tool loop and persistence; importing it would violate layering. Approval observation delegates to host authority. Chat's private truncator uses a different output marker. Shell wire types now reuse these shared event/stop types. |\n| `chatgpt/model.ts` | `ChatGPTModelOptions`, `createChatGPTModel`; plan-only model round | Reuses existing `ChatGPTPlanConnection.clientOptions`, SDK `getAI().chat` and failure classifier. Connection/resolver do not adapt model rounds; doctor is diagnostics. No alternate provider/login implementation added. |\n| `chatgpt/support.ts` | `browserCommand`, `SpawnLike`, `openSystemBrowser`, `ChatGPTFailureNote`, `chatgptFailureNote`; authorization opener/failure words | Reuses `isChatGPTAuthorizationUrl` and `classifyChatGPTPlanFailure`. CLI `createBrowserOpener/openInBrowser` accepts arbitrary URLs, has no result contract/Windows quoting guard and depends on inference (cycle). Keep this specialized wrapper and fixed failure vocabulary. |\n| `engine-model.ts` | `EngineModelToolCall/Request/Reply/Failure`, `EngineModel`, `engineModelReply`; model-round seam | Reuses SDK `AIMessage`, `AITool`, `AIToolCall`. Core `InferenceModelClient.message` is text-only; cookbook `EngineModel` is schema metadata; planner `AssistantModel` is WebLLM catalog data; chat's error type lacks action links and cannot be imported here. Flattened calls/raw replay require this seam. |\n| `engine-status.ts` | `InferenceEngineId/Action/Status/StatusHost`, `cliTool`, `engineLabel`, `cliEngineStatus`, `chatgptEngineStatus`, `inferenceEngineStatus` | Composes existing connection status, moved CLI detection and host API diagnostics. Shell `AssistantEngineId/AssistantStatus` now alias these canonical types instead of repeating their shapes. No equivalent engine-choice dispatcher exists. smrt-ui `PageHeaderCrumb` is page ancestry and `ToastAction` executes a callback; neither is a framework-free engine remediation link contract. |\n| `agent-cli/test-support.ts` | `tempDir`, `installStub`, `installFakeCli`, `fakeDeps`, `exists`; isolated CLI fixtures | Removed the parallel shell implementation. Shell re-exports inference's `./test-support` entry. smrt-vitest supplies databases/manifests, not CLI fixtures; smrt-ui test support supplies DOM/a11y. Reuse the existing Vite custom-entry mechanism and `?raw` asset loader, keeping the fixture usable from a built package. |\n| `agent-cli/test-fixtures/stub-cli.mjs` | `start`, `say`, `mcpUrl`, `callTool`, `sessionOf`, `sibling`, `out`; CLI JSON protocol fakes, local tool calls, resume/dump/hang/failure scenarios | Deleted shell's duplicate fixture; one inference-owned fake serves both packages. This is test data, never a production engine or provider. |\n\nAdded `credentials.test.ts`, `turn.test.ts`, `chatgpt/model.test.ts` and\n`engine-status.test.ts` exercise these contracts with test-local in-memory hosts,\nspies and fake endpoints. Moved `detect.test.ts`, `session.test.ts` and\n`chatgpt/support.test.ts` retain the original shell assertions. Their local\n`setup`, `threadHost`, `turn`, `runOn`, `textOf`, `waitFor`, `alive`, request and\nprovider-factory setup/drive/assertion functions are test scenarios, not additional public\ncapabilities. Existing shell adapter and DOM tests remain in place.\n\nThe MCP reviews raised only existing hosted flag detection, existing shell\napproval/polling code and a downstream-UI heuristic for inference. None is a\ncopy introduced by C2: inference remains framework-agnostic, and owner approval\nauthority stays with the host. This audit does not replace that authority.\n\n## Live desktop regression design (R7/R8)\n\n| Behavior | Trigger / positive | Failure control | Actor / executor | Boundary / validation |\n| --- | --- | --- | --- | --- |\n| Process readiness | CLI help with locked invocation, own auth status, private writable cwd | Missing runtime/flags, signed-out CLI, inaccessible directory; no model request | Local owner; no database effect | Exact desktop environment + inference stub tests |\n| Failure diagnostics | Start/stream failure logs reference, phase, fixed cause and code location | Credential-shaped message/output never logged | Server only; existing turn cleanup | Inference/chat tests and built-app log |\n| Single failure | Failed turn restores draft and offers one retry | No duplicate banner, stored fallback or composer alert | Authenticated thread; ChatService | Dock component regression |\n| Live effects | Both CLIs read lists and create a named member | Delete held until independent owner decision, replay refused, abort kills tree | Original owner/tenant; existing MCP dispatcher and durable authority | Built app, fresh SQLite; docs/qa-live-engines.md in product |\n\nReuse search: MCP reviews of inference, chat, desktop, Svelte and template host;\nintent index; `rg` name/purpose searches for preflight, engine diagnostics,\nreference/error IDs, environment helpers and retry presentation in owning\npackages, core, smrt-ui and smrt-svelte. Extend existing detection, turn error\nboundary and dock instead of adding a second engine or error presentation.\n\n## Owner work profiles\n\n`work-profiles.ts` exports browser-safe `recommendedWorkProfile` and\n`resolveWorkProfile`: `assist` defaults to high effort, `design` to maximum,\n`background` to low. Design/assist API calls resolve to `best`; the host must\napply the selected tier to its existing inference client. Owner settings may\nselect engine/model/effort and each numeric budget, pass/repair counts,\nautomatic escalation and preview. These settings carry no tool authority.\nThe preferences package stores owner overrides; inference contains no storage.\n\nClaude recommendations select the strongest installed alias, `fable`, then\n`opus`, then `sonnet`; hosts can supply the installed alias inventory. Codex recommendations use the reviewed OpenAI model table. ChatGPT automatic\nrecommendations intersect that table with the signed-in account's live catalog.\n`rankOpenAIWorkModels` annotates exact IDs only, preserving a future SDK's explicit\nfinite `intelligenceRank`; `strongestWorkModel` never infers strength from response\norder or spelling. Reviewed 2026-11-12 against\n[OpenAI's recommended models](https://learn.chatgpt.com/docs/models#recommended-models):\nAstra, 6.1 Sol, 6.1 Terra, Luna. This is versioned app recommendation data grounded\nin official descriptions, not an undocumented server quality field. Unknown IDs\nremain selectable explicitly but never become automatic recommendations. Refresh\nthis table when the catalog adds a new model; an unknown-only catalog truthfully\nhas no automatic strongest choice. Both design and assist pick the strongest\nranked offered model. Background keeps its low-effort profile.\n\n`ChatGPTPlanConnection.models()` retains ranks and its ten-minute account cache;\n`defaultModel()` uses ranks. `createChatGPTModel` discovers the catalog when needed\nand derives a single next-lower fallback from it. Host memos include account\nconnection generation, catalog and owner preference revision. Fixed fallback\nwording is sent through existing text progress. The installed SDK still rejects\nreasoning/format controls on plan requests; omit them, retain requested effort in\nmetadata, and never claim vendor enforcement. Live sign-in/entitlement/inference\nrequires the owner and is not proven by fake catalog tests.\n\nThe browser-safe root exports the same `engineLabel` used by server status;\nproduct names come from the existing pure CLI metadata. No server-status graph\nis imported by settings. `ResolvedWorkProfile.modelSelection` is derived display\nevidence: `strongest` requires the recommended Claude `fable` alias or the\nselected top-ranked catalog entry; an explicit model is `custom`, and an\nunverified/provider selection is `configured`. Tier names alone do not establish\nmodel strength. The metadata includes requested and resolved selection ids when\nknown; these are selection aliases, not a claimed provider-reported model.\n\n`runAgentTurn({ profile, outputSchema })` supplies explicit model and effort,\nClaude `--json-schema`, or Codex `--output-schema` through a private per-pass\nfile. Codex maximum maps to `model_reasoning_effort=\"xhigh\"`. Existing machine\nfeature prohibitions and parser guards remain in force, including unknown\nstructured-output tool kinds: they are refused, never allowed as built-in tools.\nClaude's final `structured_output` object is serialized for the host's schema\nvalidator. A host still validates and bounds repair attempts through the design\nrun driver. ChatGPT's SDK rejects reasoning and JSON format controls, so its\nadapter omits those unsupported controls; schema validation/repair stays host\nside. Recorded effort is the requested policy where the provider cannot honor\nan effort option; it is not a claim of vendor enforcement.\n\nToken mint receives the pass timeout; `tokenCredentials` requests a lifetime\nof at least that timeout plus one minute, retaining owner holder/scopes and\nrevocation at exit. CLI usage is recorded only when input/output token counts\nare reported, otherwise unknown. `host.recordExecution` and stored assistant\n`meta.workRun` (when a CLI session exists) carry profile, runtime-reported model (unknown when omitted),\nrequested alias/model, duration, tool count and\nfallback. `createChatGPTModel` accepts the same profile and execution callback.\n\nBoth real invocation adapters wire `runWorkModelWithFallback` when a host\nsupplies a scoped fallback store and the next verified model. Only explicit\nplan-model refusal codes qualify; arbitrary failures, policy refusals, quota,\nnetwork errors, published text or any tool activity never retry another model.\nOne fallback step is allowed, with shared fixed wording. The host persists the\nmemo under owner, engine, refused requested model and a connection/catalog key;\nchange the key after account/catalog or selection changes. No engine or billing\npath fallback is performed. No live CLI/provider call is needed for tests.\n\nFor Settings, pass a freshly resolved profile through\n`projectWorkModelSelection` with that same tenant-scoped store, owner, engine,\nrequested model and connection key. A remembered different model changes only\ndisplay metadata to `fallback`; `profile.model` remains the original request so\nexecution reads the same memo and cannot begin a fallback-of-fallback chain.\nThe projector only reads the existing memo: it performs no provider probe,\nnotification or write and exposes no connection key in the result. Hosts must\nshare their key derivation between display and execution, invalidating it after\nconnection/selection changes. The existing profile and browser-safety tests cover\nselection evidence, scope, model immutability and the public label import.\n\nReuse audit: smrt-dev-mcp `review_smrt_project` on inference and\n`build_context(task: architecture)` inventoried package exports/models. The\nintent index and name/purpose searches across smrt-ui, smrt-svelte, chat, core\nand inference found no existing work-intelligence resolver or owner-engine\nfallback memo. `work-profiles.ts` owns that pure inference policy and reuses\n`InferenceEngineId` moved unchanged to browser-safe `engine-id.ts`; existing session/turn/credentials/model adapters own all\nexecution. No UI helper, credential store, queue or approval system was added.\n\nNative CLI budget enforcement is limited to the subprocess wall deadline and\nobserved tool-result truncation for display/history. The vendor has already\nreceived the MCP result by then: this is not a model-context result bound.\nResource pages are bounded before context entry; generic MCP observations still\nneed a safe serializer with a minimum envelope preserving outcome, approvals and\ncursors without inviting mutation retries. Claude's installed help has no per-call token or\nstep limit flag; Codex is contained by its native sandbox. Numeric\nstep/token settings remain host/driver admission and accounting budgets, not a\nclaim that a vendor CLI stops at those token counts. Hosts must reserve a\nconservative allowance before a CLI pass when native usage is unknown and\nmust not count unknown usage as zero. The driver pauses future passes at run\nexhaustion; a request already admitted may exceed a token estimate. Claude\naggregate usage includes cache reads/creation as well as uncached input/output;\nCodex cached input is already part of input_tokens and is not counted twice.\n\nA sessionless CLI pass records execution through `host.recordExecution`; its\nmessage has no session metadata. Existing hosts retain the original tool/session\nmessage union without fabricated session IDs.\n\n## Per-app local CLI protection (S1 owner setting)\n\nIntegration hold: protection-off is a tested local prototype pending an owner boundary decision. App-tool approval gates remain enforced, but unrestricted native commands can edit the app's database files directly. The current implementation does not provide an always-enforced raw-file deletion guarantee. Either scope that guarantee to app tools with an explicit warning, or retain app-data isolation through an OS confinement design before integrating this mode.\n\n`AgentTurnOptions.protection` defaults to true; omitted means the containment documented above, unchanged. Only the verified owner settings route may persist false, after an explicit command/file risk confirmation. This is not an MCP/tool argument.\n\n| Protection | Claude Code | Codex |\n| --- | --- | --- |\n| On (default) | Native tools absent; personal settings/plugins ignored | Required MCP/code host only; incidental built-ins confined to the private per-turn working folder |\n| Off (owner confirmation) | Native shell/files/network and personal settings/plugins allowed; MCP bearer readable/exfiltratable by shell | Native tools and personal config/plugins allowed under the owner's OS authority; full-access sandbox |\n\nWith protection **off**, both engines start in persistent `<engine state>/work` (not the project/source tree). Claude Code 2.1.319 uses `--permission-mode bypassPermissions --permission-prompts none`: native operations run without a terminal prompt. Omit `--tools \"\"`, `--allowedTools`, `--strict-mcp-config`, `--setting-sources \"\"`, `--disable-slash-commands` and `--no-chrome` so the person's normal tools/config/plugins are available. The app's private `--mcp-config` still supplies its scoped endpoint by environment reference. The cookbook host sets engine state to the app data root, so its exact cwd is `<app data>/work`; protected Codex uses `<app data>/run/turn-*/work`. Other hosts may supply a dedicated engine-state subdirectory.\n\n**Unprotected Claude token exposure:** the turn's app MCP bearer token is injected into the CLI environment (`SMRT_SHELL_MCP_TOKEN`). With shell access, the model can read that environment and exfiltrate the token over its native network tools. Output redaction protects the displayed/persisted answer only; it cannot prevent reading or exfiltration. This mode does not claim credential isolation. The owner must decide whether this switch ships.\n\nThe cookbook host mints only the offered tool slugs intersected with the turn's permission ceiling ([host binding](../../template-sveltekit/host/server.ts)); verification further intersects with the owner's live grants and requires active owner identity ([token store](../../app-runtime/src/local-mcp-tokens.ts)). The bearer can invoke those app reads/writes as that owner while valid, subject to live tool exposure and the same server approval checks; it cannot decide approvals or change owner-only safety settings. A stolen bearer is not cryptographically tied to its child process. Its intended MCP destination is HTTP loopback only ([URL validation](../src/agent-cli/session.ts)); that destination restriction does not prevent the unprotected shell sending the credential elsewhere. Expiry is fixed at `max(15 minutes, requested turn timeout + 60 seconds)` ([credentials](../src/agent-cli/credentials.ts)), not a sliding login. The turn revokes its holder on completion, error, Stop or timeout in `runAgentTurn`'s `finally`; revocation is best effort, so expiry remains the backstop. No token value appears in these docs.\n\nCodex 0.162.1 off uses `sandbox_mode=\"danger-full-access\"`, `approval_policy=\"never\"`, `web_search=\"live\"`; it omits the optional-feature disable list, `--ignore-user-config`, `--ignore-rules` and protected workspace overrides. This explicitly permits commands, files and network under the person's OS authority and own CLI config/plugins. Modern MCP and `code_mode_host` remain enabled for app tools. `shell_environment_policy.inherit=\"none\"` remains forced in BOTH states: model shell commands do not inherit the app credential. Protection on retains the fresh 0700 per-attempt folder and cleanup. These flags were checked against installed `claude --help` and `codex exec --help`, not inferred.\n\nAlways: strip API-key environment variables, loopback-only MCP, short-lived owner-bound token in child environment (never argv/config/logs), app tool allow-list, owner deletion policy, Stop/timeout process-group kill and credential revocation. Off-mode native events record only sanitized tool names (`agent_tool_native`), not input/output; they do not fail an otherwise valid app request. Other app MCP tools remain fail-closed. Off-mode answers buffer to a message/tool boundary and reuse `redactInferenceSecret` to prevent split credential echoes reaching UI/history. Work-profile model/effort and classified one-step fallback are unchanged. Status/preflight caches are separated by protection mode.\n\nStub command specs, stream turns and credential-echo tests cover both modes. The shared ChatGPT connection accepts an optional SDK `begin().cancel` handle; without it, cancellation is explicitly unavailable and pending status remains truthful. Late/expired successful callbacks are signed out instead of silently reconnecting. SDK listener/state/timeout fixes belong upstream.\n\nS1 live proof used the built `s1-settings` product with the desktop sidecar environment and four harmless turns, one engine/state pair each. Claude on refused shell access (zero tool calls); Claude off used Bash for `date +%F`. Codex on reported shell unavailable; Codex off used exec_command for the same harmless date command. Product `docs/qa-live-engines.md` carries the exact prompts, requested/reported models and final validation. These checks do not exercise ChatGPT sign-in or chat; its SDK event-stream fix remains unreleased.\n\nChatGPT failure diagnostics (V2): `reportAgentFailure('chatgpt', ...)` follows bounded own-data `cause` wrappers and records only allow-listed provider codes plus a bounded `req_` or UUID request id. It never logs error messages, account fields, response bodies, tokens or arbitrary metadata. The wire error remains the existing safe message; the correlated server reference identifies the cause. Tests exercise direct and wrapped SDK failures and rejection of secret-bearing message/account fields.\n"
|
|
385
|
+
},
|
|
305
386
|
{
|
|
306
387
|
"path": "agents/resolver.md",
|
|
307
388
|
"module": "resolver",
|
|
@@ -312,6 +393,11 @@
|
|
|
312
393
|
"module": "hosted",
|
|
313
394
|
"content": "# Hosted inference (#4759, #4760)\n\n## Provisioning (`src/hosted.ts`, #4759)\n\n`provisionHostedInference({ db, tenantId, userId, budget })`,\n`revokeHostedInference({ db, tenantId, userId })`, or one\n`createHostedInferenceProvisioner({ db, secrets?, gateway?, admin?, actor? })`\n(`provision`, `revoke`, `syncBudget`, `status`, `listActive`, `listKnown`,\n`revokeTenant`, `syncTenantBudget`, `reconcileTenant`,\n`acknowledgeGatewayRevocation` to drop an owed deletion an operator did by\nhand).\n\n- **Gateway.** Admin calls go through `ai.admin` (`AIAdminInterface`) of the\n `bifrost` / `litellm` provider of `@happyvertical/ai` >= 0.111.7\n (happyvertical/sdk#1494); never reimplement gateway administration here.\n `HostedGatewayAdmin` is `HOSTED_GATEWAY_ADMIN_METHODS` (`createProject`,\n `createVirtualKey`, `updateVirtualKey`, `deleteVirtualKey`,\n `listProjects`); a provider missing one is `HOSTED_GATEWAY_UNSUPPORTED`.\n SMRT persists only `AIVirtualKey.id`, the non-secret handle (Bifrost id,\n LiteLLM `token_id`); an id that equals or looks like a key value (`sk-…`)\n is dropped on create and when older state is read, so that key counts as\n having no id. Budget sync sends\n `updateVirtualKey(id, { budget })` only (Bifrost refuses `models` /\n `metadata`, LiteLLM `providerConfigs`: `ADMIN_UNSUPPORTED_FIELD`);\n `unsupported` now means the grant has no key id. Revoke ends local use\n before touching the gateway (config restored, state retired with the key\n owed, then `deleteVirtualKey`; `false` is `missing`, an already revoked\n key, nothing owed). A deletion the gateway did not perform (`failed`, a\n key a failed provision left, `unsupported`: no admin configured or no key\n id; entries from before 0.111.7 also read `unsupported`) goes to the\n state's `pendingGatewayRevocations` (id + alias, never the key), is\n audited with `manualGatewayRevocation`, and is retried by `revoke()` /\n `reconcileTenant()`; each retry that settles one writes\n `inference.hosted.revoke-retry` with `settled: [{ keyId, keyAlias,\n gateway }]`, closing those records. Entries without an id stay for an\n operator (`acknowledgeGatewayRevocation`).\n- **Config, read once from the environment** (`getHostedGatewayConfig()`;\n unset provider = hosted off): `SMRT_INFERENCE_HOSTED_PROVIDER`\n (`bifrost|litellm`), `_BASE_URL` (the OpenAI-compatible endpoint keys are\n used against), `_ADMIN_URL`, `_ADMIN_KEY` (LiteLLM master key, required for\n litellm; or a Bifrost admin key), `_ADMIN_USER` / `_ADMIN_PASSWORD`\n (Bifrost Basic auth), `_MODEL`, `_<TIER>_MODEL`, `_MODELS` (comma list the\n key may use; default the binding's models), `_KEY_DURATION`,\n `_ADMIN_TIMEOUT_MS` (deadline per admin call, default 30 s, also passed as\n the SDK `timeout`; a call past it is a failure, so a stalled gateway never\n holds the lifecycle lock). A create that fails ambiguously (timeout,\n transport reset, 5xx, unclassified; anything but a credential, quota,\n missing-model or refusal answer per `classifyInferenceFailure`) records\n its alias as owed, since the gateway may have minted the key.\n Errors name missing fields, never values.\n- **Storage** (smrt-secrets, `context = tenantId`): the key lives only in\n the user's `inference.provider-config:user:<id>` (`source: 'hosted'`,\n `mode: 'hosted'`, `gatewayKeyAlias`, a binding per configured tier);\n `inference.hosted:user:<id>` (category `inference.hosted`) holds status,\n generation, key id and alias, budget and the user's prior config;\n `inference.hosted:project` the tenant's gateway project (created once\n through `runOnce()`, name `smrt tenant <tenantId>`, LiteLLM id\n `smrt-<tenantId>-<nonce>`). Without a stored record, `listProjects({\n tenantId })` runs first and adopts the lowest-id project with that name\n (and id prefix on LiteLLM), audited `adopted: true`, so a crash between\n create and persist never makes a second project; a failed lookup fails\n the provision rather than create blind. Every write passes\n `auditDetails.operation` (`inference.hosted.provision|revoke|budget|project`)\n to `SecretAuditLog`.\n- **Idempotency and ordering.** An active grant whose binding is still the\n stored one is returned (`created: false`), its budget synced when it\n differs. The create path runs under `runOnce()` keyed by `(tenantId,\n userId, generation)`; revoke advances the generation. Aliases\n (`smrt-<tenant>-<user>-g<n>-<nonce>`) and LiteLLM project ids\n (`smrt-<tenant>-<nonce>`) are unique per attempt, so a failed attempt's\n leftovers never block the retry. Lifecycle operations run one at a time\n per process (a process-wide chain: rare operations, and it bounds the\n pooled connections held) and, on PostgreSQL, under a per-tenant\n `pg_advisory_xact_lock` held in a transaction for the whole operation\n (its writes use other pooled connections: at most three per process), so\n a tenant-wide revoke or reconcile never misses an in-flight provision.\n The optional `entitled(tenantId)` check runs inside that lock before a\n key is minted (`HOSTED_NOT_ENTITLED`) and before an entitled reconcile\n acts (a stale snapshot then revokes), so a stale gain or late retry after\n a downgrade does not activate. Hosts running the listener or reconciler\n across processes should set it. A failed binding write deletes or records the new\n key and restores the previous state after the claim rolls back (no delete\n inside the claim transaction: single-connection adapters would wait on\n it). A user who replaced the hosted binding keeps their config: an\n explicit `provision()` retires the stale key and mints anew; a reconcile\n only retires it and marks the state `optedOut`, which later reconciles\n respect until an explicit `provision()`. Writes through the #4756\n resolver (the settings panel) do not take this lock.\n- **Revoke** restores the prior config when it holds a binding or a mode,\n else writes `{ mode: 'off' }`; a config the user replaced is kept.\n- **Budget** is integer micro-dollars (`{ limitMicros, window? }`, `day |\n week | month | year`, default month), converted to the gateway's USD\n `maxLimit` and `1d|7d|30d|365d` only at the admin call. #4760's spend gate\n is the authoritative pre-call check; the gateway budget is defense in depth.\n An unchanged budget is never re-sent (a gateway update may restart the\n spend window); after a failed or timed-out update (`budgetSyncUncertainAt`,\n it may still land) syncs re-apply the stored budget until a confirmed\n update 15 minutes later.\n- **Entitlement hook.** `createHostedInferenceEntitlementListener({\n provisioner, users, budgetFor?, defaultBudget? })` structurally matches\n smrt-subscriptions' `EntitlementChangeListener` (register it with\n `registerEntitlementChangeListener()`; the host wraps its webhook write in\n `trackEntitlementChange()`). A change touching `inference.hosted`\n reconciles the tenant to the change's `after` snapshot through\n `createHostedInferenceReconciler()`: entitled provisions `users(tenantId)`\n (membership is the host's; exclude users an operator revoked) unless\n they opted out, and syncs budgets; not entitled revokes every grant; both\n retry owed deletions (also for active grants: they are old keys). The\n plan's budget is the grant's `metadata.budget` (`{ limitMicros, window }`).\n A replayed webhook diffs to \"no change\", so hosts also call the reconciler\n with `snapshotEntitlements()` on redelivery and on a schedule; that is\n what repairs a reaction lost to a crash. Per-user failures are thrown\n together after all users were tried.\n- **Keys.** Never in results, errors (gateway failures carry only the\n operation and error code), audit details, `runOnce()` results or logs.\n Usage rows carry `source: hosted` and `gatewayKeyAlias` (from\n `InferenceTarget.usageTags`). Other processes see a new binding after the\n resolver cache expires; this process is invalidated through\n `invalidateUserInferenceResolvers()`.\n\n## Spend gate and kill switch (`src/gate.ts`, #4760)\n\n`createHostedInferenceGate({ killSwitch, spend, principal?,\nrequireSubscription?, onWarning? })` is core's `InferenceGate` (seam:\n[core inference.md](../../core/agents/inference.md), \"Hosted gate\");\n`registerHostedInferenceGate(gate | options)` installs it and the\nprincipal's user as the `userId` usage tag. Host wiring:\n\n```ts\nregisterHostedInferenceGate({\n killSwitch: new KillSwitchService({ db }), // smrt-features\n spend: await HostedAiSpendEvaluator.create({ db }), // smrt-subscriptions\n});\n```\n\nBoth stores are structural: smrt-features and smrt-subscriptions build with\nthe CLI, which depends on this package, so a dependency on either is a turbo\ncycle. Checks, in order, on every `source: hosted` call:\n\n1. **Kill switch** `inference.hosted.enabled` (`HOSTED_INFERENCE_KILL_SWITCH`):\n global DISABLE, then the tenant's DISABLE, blocks (`policy:\n 'kill-switch'`, `disabledBy`). Uncached, no model call: **the incident\n lever** (`smrt inference:hosted disable [--tenant <id>]`; programmatic\n `setHostedInferenceEnabled(store, { enabled, tenantId? })`,\n `getHostedInferenceSwitch()`). Stored as smrt-features override rows\n with kill-switch semantics, not as a flag: a tenant ENABLE can never\n lift a global DISABLE, and `inference.hosted` (the plan key) stays a pure\n entitlement. Hosts with an admin UI write the same DISABLE rows through\n `FeatureOverrideService` and their authorizer.\n2. **Tenant**: request tenant, else the principal's; none blocks (`no-tenant`).\n3. **Entitlement**: no entitled subscription blocks (`subscription`) unless\n `requireSubscription: false`.\n4. **Spend**: the plan's tenant and per-user caps (smrt-subscriptions\n AGENTS, \"Hosted AI spend caps\"): `blocked` blocks with `cap`, `spend`\n (micro-dollars) and `resetsAt`; `warn` returns `warn` and calls\n `onWarning` (errors swallowed). The user is the principal's, only in its\n own tenant, and none for `userId: null` (agents).\n\nAny thrown error propagates and core blocks with `gate-error`. The plan\ncheck does not test the `inference.hosted` feature key: provisioning the\nhosted binding (#4759) is where entitlement to hosted is granted.\n"
|
|
314
395
|
},
|
|
396
|
+
{
|
|
397
|
+
"path": "agents/design-runs.md",
|
|
398
|
+
"module": "design-runs",
|
|
399
|
+
"content": "# Durable design runs\n\n`createDesignRunDriver` is an engine-neutral ordered pass executor. A run is a\nworkflow record in `_smrt_inference_design_runs`, not a second queue. Run normal\napplication migrations before starting it. The host admits work through existing\n`SmrtJobCollection.enqueueJob` and executes it through `TaskRunner`; browser\nconnection lifetime must never own its cancellation signal.\n\nThe host binds `createDesignRunStore` to the authenticated owner and tenant. Its\n`enqueue(transaction, state)` callback enqueues the existing job in that same\ntransaction, using the stable run id as `dedupeKey`. Start and resume either save\nthe checkpoint and admit the job together, or neither commits. Run ids are UUIDs.\nAll generated REST, CLI, and MCP surfaces on `DesignRunRecord` are disabled.\n\nInstall `installDesignRunExecutor(db, handler)` once when booting the host. Its\nhandler receives the hydrated record, arguments and runner context. Verify\n`isRunnerExecutionContext`, the job target, tenant and current owner authority;\nthen build a worker store whose `authorizeWrite(transaction, state)` verifies the\nlive job claim on every checkpoint. Pass the runner's `signal` to `driver.run`.\nSupply `ownsExecution` with that same live claim proof so a recovered job can\nreplace the crashed pass's stale lease immediately. Only `execute` is background-eligible. The installer returns teardown; reinstall\nit after process restart before starting the runner.\n\nA host definition pins a version string and an ordered list of plain-text pass\nnames and JSON schemas. Every engine, including CLI engines, returns an object\nthrough `executePass`; the mandatory host `validate(schema, output)` callback\nmust use a full JSON Schema implementation such as Ajv, not a partial handwritten\nvalidator. Invalid outputs and validation errors are checkpointed and supplied to\nthe next repair attempt. Repairs stop at `repairRetries`. Accepted outputs are\ncheckpointed before deterministic `check` code runs. Checks receive their own\nabort signal, may feed facts to the next pass, request a bounded repeat, or pause\nfor owner approval. Checks must be read-only or idempotent because a crash may\nreplay them. A profile supplies quality and budgets, never permission or approval.\n\nAn approval hold retains the accepted output, current pass index and `check`\nphase, clears repair state and releases the settled check lease. Resume reruns\nthat same check, including for the final pass; only a cleared check can advance\nor finish the run. It never calls the model again for that accepted output or\nduplicates its attempts/token usage. A denied check may fail terminally. Hosts\nmust give effects stable identities and recover their exact recorded result\nwhen replay follows a crash after apply but before the completion checkpoint.\nRecover a running/checking job by calling `run` under its legitimate replacement\nTaskRunner claim (`ownsExecution`), without clearing leases through frontend\n`resume`, weakening liveness proof or enabling generic failed-run retries.\nFor a definitive check rejection, the trusted host may return `failure` with\nits own safe, static explanation. This ends the run as `failed`, retaining the\nvalidated output, input, usage and attempts; it takes precedence over an approval\nhold or repeat. Never copy model output or caught exception text into `failure`.\nOrdinary thrown errors still receive the driver's generic failure explanation.\n\nA trusted host check may return `complete: true` after mechanically validating\nand applying its accepted proposal. This ends the run at its actual pass index,\nretaining the `check` phase, input, outputs, attempts and accumulated usage. It\ndoes not manufacture later passes or their usage. Failure, approval hold and\nbounded repeat take precedence over completion, in that order. An approval hold\ntherefore resumes the same check before completion, without another model call.\nModel output fields cannot select completion. Done runs remain terminal for\n`run`, `stop` and `resume` even when their index is below the configured count.\nThe host owns versioned adaptive eligibility and exact owner-selected pass-count\nsemantics; the inference driver does not reinterpret work-profile budgets.\nThe existing design-run tests cover first/later completion, conflicting check\nresults, approval resume, lost completion CAS with same-action recovery under a\nreplacement claim, and stale completion after Stop.\n\nInputs carry resource ids. `readResource` rejects ids outside the host's pinned\nlist; the host checks current owner access and supplies summary-first pages with\nopaque cursors. A page exceeding `toolResultChars`, including its envelope, is\nrejected before it enters model context. Files and credentials are never inlined\ninto checkpoints.\n\nToken and elapsed-time allowances accumulate across model calls, repair calls,\nand mechanical checks. Before each call, the driver durably reserves its entire\nallowed token and time budget. Successful calls reconcile to reported actual\nusage; unknown token usage or a crash retains the reservation conservatively.\nChecks reserve time too. A timeout or exhausted cumulative budget produces a\nresumable `stopped` run with a plain explanation. Raise total budgets on resume;\nusage never resets. Stop is cooperative: cancel the existing job as well, and\nforward its signal into engine requests. A still-active pass lease prevents\nimmediate overlapping resume. The worker store's `authorizeRelease` must lock\nand prove the captured job id, worker id and attempt (running or its terminal\nStop outcome, never a pending/recovered claim). `releaseLease` freshly reads a\nstopped checkpoint with the same `leaseRevision` and atomically clears that\nlease with a revision CAS. The driver calls it only after the original engine\nor check promise truly settles; winning an abort/timeout race alone cannot\nrelease a lease. A retained `leaseRevision` blocks frontend resume even after\nits deadline. Crash recovery of a running job requires `ownsExecution` from a\nreplacement TaskRunner claim; a stopped run whose original process died needs\nan explicit host liveness recovery path, never an inference from elapsed time\nor missing jobs. A cooperative stopped call can therefore resume immediately\nwhen its backing job has also settled. Delayed release cannot clear a newer\nrunning/resumed claim. CAS revisions prevent stale workers overwriting\nStop or newer progress. Definitive schema/check failures end as `failed`.\n\nProgress uses exactly `{ runId, pass: { index, count, name }, status, note? }`.\nIndices are one-based. Statuses are `running`, `checking`, `waiting-approval`,\n`stopped`, `failed`, and `done`. Publish this on the existing event stream;\nsubscriber failures cannot interrupt durable work. Each attempt stores its\n`WorkRunMetadata`, including actual provider usage when available. Host tool\npolicy, durable approvals and history apply throughout all passes.\n\n## Reuse audit\n\nThe intent index, `review_smrt_project` and `build_context` were consulted before\nimplementation. Searches across smrt-ui, smrt-svelte, chat, core, jobs and inference\nfound no existing ordered schema-repair driver. Existing `SmrtJob`, `TaskRunner`,\n`McpTaskStore` and durable MCP continuations remain the queue, liveness,\ncancellation and input primitives. Job events have independent retention and do\nnot provide atomic workflow CAS, so a dedicated inference workflow checkpoint\nholds pass inputs/outputs and cumulative budgets. Inference depends on no jobs\nruntime; the authenticated host supplies the transaction admission callback.\n"
|
|
400
|
+
},
|
|
315
401
|
{
|
|
316
402
|
"path": "agents/fusions.md",
|
|
317
403
|
"module": "fusions",
|