stitchkit 0.136.4 → 0.136.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/agent-runtime/providers/openrouter-spend.d.ts +4 -2
  3. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  4. package/dist/entrypoints/agent-executor/acp.js +5 -5
  5. package/dist/entrypoints/agent-executor/claude-sdk.js +7 -7
  6. package/dist/entrypoints/agent-executor/claude.js +7 -7
  7. package/dist/entrypoints/agent-executor/codex.js +9 -9
  8. package/dist/entrypoints/agent-executor/testing.js +9 -9
  9. package/dist/entrypoints/agent-executor.js +5 -5
  10. package/dist/entrypoints/agent-runtime/coding-tools.js +2 -2
  11. package/dist/entrypoints/agent-runtime/postgres.js +4 -4
  12. package/dist/entrypoints/agent-runtime/sandbox.js +7 -7
  13. package/dist/entrypoints/agent-runtime/sqlite/bun.js +5 -5
  14. package/dist/entrypoints/agent-runtime/sqlite/node.js +5 -5
  15. package/dist/entrypoints/agent-runtime/testing.js +4 -4
  16. package/dist/entrypoints/agent-runtime.js +4 -4
  17. package/dist/entrypoints/application/diagnostic-journal.js +3 -3
  18. package/dist/entrypoints/application/directory-inbox.js +7 -7
  19. package/dist/entrypoints/cli/publish.d.ts +14 -6
  20. package/dist/entrypoints/cli/publish.d.ts.map +1 -1
  21. package/dist/entrypoints/cli/publish.js +685 -30
  22. package/dist/entrypoints/cli.js +7 -124
  23. package/dist/entrypoints/files/packaging.js +2 -2
  24. package/dist/entrypoints/files.d.ts +1 -0
  25. package/dist/entrypoints/files.d.ts.map +1 -1
  26. package/dist/entrypoints/files.js +9 -9
  27. package/dist/entrypoints/node.js +3 -3
  28. package/dist/entrypoints/observability.js +1 -1
  29. package/dist/entrypoints/process.js +3 -3
  30. package/dist/entrypoints/server.js +6 -6
  31. package/dist/entrypoints/service-host/macos.js +7 -7
  32. package/dist/entrypoints/service-host/work.js +6 -6
  33. package/dist/entrypoints/service-host.js +9 -9
  34. package/dist/entrypoints/spend.js +85 -15
  35. package/dist/entrypoints/telegram.js +3 -3
  36. package/dist/entrypoints/tools.js +1 -1
  37. package/dist/{index-05b65gj4.js → index-0s75mjh7.js} +1 -1
  38. package/dist/{index-s2e3h616.js → index-150b1qyw.js} +10 -1
  39. package/dist/{index-tcv71frn.js → index-1fhbe4e4.js} +1 -1
  40. package/dist/{index-8cek82ar.js → index-1h0dtfz3.js} +1 -1
  41. package/dist/{index-jwtmw39p.js → index-2qnqvq11.js} +1 -1
  42. package/dist/index-2rs7ze0q.js +376 -0
  43. package/dist/{index-2wm9b9vs.js → index-3cwq5byx.js} +2 -2
  44. package/dist/{index-mtpcax6d.js → index-5md04mwc.js} +3 -3
  45. package/dist/{index-b0mh2t9x.js → index-67mzzkdv.js} +3 -3
  46. package/dist/{index-d5mhgx72.js → index-8tn10tp6.js} +1 -1
  47. package/dist/{index-0sxj3y45.js → index-afaq0nc4.js} +1 -1
  48. package/dist/{index-nfm15ej7.js → index-bbpygynk.js} +1 -1
  49. package/dist/{index-g04hszcm.js → index-chapre0y.js} +1 -1
  50. package/dist/{index-vh4291qh.js → index-ctaxjpa4.js} +1 -1
  51. package/dist/{index-x1r7kxzd.js → index-e4zt2x70.js} +3 -3
  52. package/dist/{index-s0n0nnz5.js → index-f103md2v.js} +122 -3
  53. package/dist/{index-2c5w2d1d.js → index-gyfsh29t.js} +1 -1
  54. package/dist/{index-kgkevngs.js → index-kadgaw1s.js} +4 -4
  55. package/dist/{index-ca1v40d3.js → index-kd48gk7d.js} +1 -1
  56. package/dist/{index-ke6jtxkd.js → index-mr3njw67.js} +1 -1
  57. package/dist/{index-cmqvf0dz.js → index-ppy23bd2.js} +1 -1
  58. package/dist/{index-43k180c2.js → index-rnhp7je8.js} +2 -2
  59. package/dist/{index-2tgmggcm.js → index-smvmnz5y.js} +1 -1
  60. package/dist/{index-9m1m92rg.js → index-tjhhsnjv.js} +1 -1
  61. package/dist/{index-64t6pheq.js → index-w161azza.js} +1 -1
  62. package/dist/{index-mttkdm5a.js → index-xqppqn97.js} +1 -1
  63. package/dist/{index-sjq4akrx.js → index-xsrma0jd.js} +2 -2
  64. package/dist/{index-zqc64g69.js → index-ypm85xwe.js} +1 -1
  65. package/dist/{index-zagc12j1.js → index-zcq3dby3.js} +1 -1
  66. package/dist/{index-29v1p1f4.js → index-zhngww7q.js} +1 -1
  67. package/dist/internal/atomic-file-owner.d.ts +91 -0
  68. package/dist/internal/atomic-file-owner.d.ts.map +1 -0
  69. package/dist/internal/atomic-file.d.ts +29 -7
  70. package/dist/internal/atomic-file.d.ts.map +1 -1
  71. package/dist/internal/bounded-file-read.d.ts +6 -2
  72. package/dist/internal/bounded-file-read.d.ts.map +1 -1
  73. package/dist/spend/receipt-merge.d.ts +8 -4
  74. package/dist/spend/receipt-merge.d.ts.map +1 -1
  75. package/dist/spend/reconcile.d.ts +15 -2
  76. package/dist/spend/reconcile.d.ts.map +1 -1
  77. package/dist/spend/schemas.d.ts +1 -0
  78. package/dist/spend/schemas.d.ts.map +1 -1
  79. package/dist/tools/cli/distribution-config.d.ts +56 -0
  80. package/dist/tools/cli/distribution-config.d.ts.map +1 -0
  81. package/dist/tools/cli/distribution-routes.d.ts +20 -0
  82. package/dist/tools/cli/distribution-routes.d.ts.map +1 -0
  83. package/dist/tools/cli/publication-source.d.ts +77 -0
  84. package/dist/tools/cli/publication-source.d.ts.map +1 -0
  85. package/llms/agent-runtime-openrouter.txt +1 -1
  86. package/llms/cli-publish.txt +15 -3
  87. package/llms/cli.2.txt +84 -63
  88. package/llms/cli.3.txt +67 -1
  89. package/llms/cli.txt +1 -1
  90. package/llms/files.txt +1 -1
  91. package/llms/process.txt +24 -4
  92. package/llms/spend.txt +11 -5
  93. package/llms/stitchkit.txt +1 -1
  94. package/llms-full.txt +136 -15
  95. package/llms.txt +7 -7
  96. package/package.json +1 -1
  97. package/dist/index-pp97q86a.js +0 -221
  98. package/dist/{index-5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GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7C,gFAAgF;IAChF,YAAY,CAAC,CAAC,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,SAAS,WAAW,EAAE,CAAC,CAAC;IACzE,2FAA2F;IAC3F,YAAY,CAAC,CAAC,KAAK,EAAE;QACnB,aAAa,EAAE,MAAM,CAAC;QACtB,KAAK,EAAE,MAAM,CAAC;KACf,GAAG,OAAO,CAAC,SAAS,YAAY,EAAE,CAAC,CAAC;CACtC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Configuration validation and safe path matching for `createCliDistributionRoutes`.
3
+ */
4
+ import type { CliSignatureVerdict, CliTrustRoot } from './signature.js';
5
+ export declare const SAFE_ASSET_SEGMENT: RegExp;
6
+ /** Diagnostic event emitted when a CLI distribution route responds with 503 or 404. */
7
+ export interface CliDistributionUnavailableEvent {
8
+ readonly route: 'manifest' | 'version-manifest' | 'asset' | 'installer';
9
+ readonly channel: string;
10
+ readonly version?: string;
11
+ readonly asset?: string;
12
+ readonly reason: 'unconfigured-root' | 'empty-trust-root' | 'missing' | 'unsafe-path' | 'too-large' | 'invalid-manifest' | 'identity-mismatch' | 'untrusted-signature' | 'unlisted-asset' | 'io-error';
13
+ readonly verdict?: CliSignatureVerdict;
14
+ readonly error?: unknown;
15
+ }
16
+ /** Configuration for {@link createCliDistributionRoutes}. */
17
+ export interface CliDistributionRoutesOptions {
18
+ /** Absolute path to the CLI distribution root directory, or `undefined` to serve 503 fail-closed. */
19
+ readonly root: string | undefined;
20
+ /** Expected `manifest.name` verified against the signed manifest on every request. */
21
+ readonly name: string;
22
+ /** Trust root whose Ed25519 public keys verify manifest signatures; empty `keys` fails closed with 503. */
23
+ readonly trust: CliTrustRoot;
24
+ /** Release channels mounted under `${basePath}/channels/<channel>/...` (default `['stable', 'beta']`). */
25
+ readonly channels?: readonly string[];
26
+ /** Channel served by `${basePath}/install.sh` (defaults to the first entry of `channels`). */
27
+ readonly installerChannel?: string;
28
+ /** URL path prefix for the routes (default `'/cli'`; `'/'` mounts at root). */
29
+ readonly basePath?: string;
30
+ /** Binary filename written into `install.sh` (defaults to `name`). */
31
+ readonly binaryName?: string;
32
+ /** Default `INSTALL_DIR` in `install.sh` (default `'$HOME/.local/bin'`). */
33
+ readonly installDir?: string;
34
+ /** Maximum byte size read for any manifest file (default `256 * 1024`). */
35
+ readonly maxManifestBytes?: number;
36
+ /** Optional `RawRoute.serviceName` attached to every returned route for observability. */
37
+ readonly serviceName?: string;
38
+ /** Optional observer invoked when a manifest or asset is unavailable or refused; throws are isolated. */
39
+ readonly onUnavailable?: (event: CliDistributionUnavailableEvent) => void;
40
+ }
41
+ export interface ResolvedDistributionConfig {
42
+ readonly root: string | undefined;
43
+ readonly name: string;
44
+ readonly trust: CliTrustRoot;
45
+ readonly channels: readonly string[];
46
+ readonly installerChannel: string;
47
+ readonly basePath: string;
48
+ readonly binaryName: string;
49
+ readonly installDir: string;
50
+ readonly maxManifestBytes: number;
51
+ readonly serviceName: string | undefined;
52
+ readonly onUnavailable: ((event: CliDistributionUnavailableEvent) => void) | undefined;
53
+ }
54
+ export declare function resolveDistributionConfig(options: CliDistributionRoutesOptions): ResolvedDistributionConfig;
55
+ export declare function assetMatchesUrl(entryUrl: string, asset: string): boolean;
56
+ //# sourceMappingURL=distribution-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"distribution-config.d.ts","sourceRoot":"","sources":["../../../src/tools/cli/distribution-config.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,KAAK,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AASrE,eAAO,MAAM,kBAAkB,QAAiC,CAAC;AAKjE,uFAAu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C9B,yGAAyG;IACzG,QAAQ,CAAC,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,+BAA+B,KAAK,IAAI,CAAC;CAC3E;AAED,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC,KAAK,EAAE,+BAA+B,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CACxF;AA4ED,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,4BAA4B,GACpC,0BAA0B,CAgD5B;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAexE"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Portable HTTP distribution routes for a published CLI channel (`stitchkit/cli/publish`).
3
+ *
4
+ * Serves signed channel manifests, immutable versioned manifests and binary assets, and the
5
+ * generated shell installer as portable `RawRoute[]` (compatible with `stitchkit/handler`,
6
+ * `stitchkit/server` and `stitchkit/node`). Every read verifies
7
+ * ancestor directory containment (`realpath` + `isWithinDir`), leaf `O_NOFOLLOW`, strict UTF-8
8
+ * JSON without `__proto__`, exact manifest identity and Ed25519 signature (`verdict === 'valid'`),
9
+ * and streams binaries directly from an open descriptor without `Bun.file`.
10
+ */
11
+ import type { RawRoute } from '../../server/types.js';
12
+ import { type CliDistributionRoutesOptions } from './distribution-config.js';
13
+ /**
14
+ * Create portable `RawRoute[]` handlers serving signed CLI channel manifests, immutable
15
+ * versioned manifests and binary assets, and `install.sh` (`GET` only, full-body descriptor
16
+ * streaming). Fails closed with `503 No verified CLI build is published` when unconfigured,
17
+ * missing, unsigned, or untrusted.
18
+ */
19
+ export declare function createCliDistributionRoutes(options: CliDistributionRoutesOptions): RawRoute[];
20
+ //# sourceMappingURL=distribution-routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"distribution-routes.d.ts","sourceRoot":"","sources":["../../../src/tools/cli/distribution-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAQH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAEL,KAAK,4BAA4B,EAKlC,MAAM,uBAAuB,CAAC;AAuS/B;;;;;GAKG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,4BAA4B,GACpC,QAAQ,EAAE,CAwCZ"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Git-backed CLI source verification and shipping-input versioning for `stitchkit/cli/publish`.
3
+ *
4
+ * Versions derived from shipping inputs pair the declared `major.minor` series in the CLI package
5
+ * manifest at `<commit>` with the full commit count touching `shippingPaths` up to `<commit>`.
6
+ * Every git invocation runs through `runNativeCommand` with a declared-only environment so parent
7
+ * hook variables (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`) cannot silently redirect checks.
8
+ */
9
+ /** Options for {@link deriveCliVersionFromShippingInputs}. */
10
+ export interface CliShippingVersionOptions {
11
+ /** Absolute path to the git repository root (worktree root or bare repository root). */
12
+ readonly repository: string;
13
+ /** Exact 40-lowercase-hex commit SHA whose shipping inputs determine the version. */
14
+ readonly commit: string;
15
+ /** Repository-relative POSIX path to the package manifest declaring `major.minor` (e.g. `'packages/cli/package.json'`). */
16
+ readonly packageJsonPath: string;
17
+ /** Non-empty list of repository-relative paths whose history determines the patch number. */
18
+ readonly shippingPaths: readonly string[];
19
+ /** End-to-end deadline across all git checks in milliseconds (default `30_000`). */
20
+ readonly timeoutMs?: number;
21
+ /** Optional cancellation signal bound to the git checks. */
22
+ readonly signal?: AbortSignal;
23
+ }
24
+ /** Options for {@link cliShippingInputsChanged}. */
25
+ export interface CliShippingInputsChangedOptions {
26
+ /** Absolute path to the git repository root (worktree root or bare repository root). */
27
+ readonly repository: string;
28
+ /** Earlier 40-lowercase-hex commit SHA. */
29
+ readonly previousCommit: string;
30
+ /** Later 40-lowercase-hex commit SHA. */
31
+ readonly nextCommit: string;
32
+ /** Non-empty list of repository-relative paths to compare between the two commits. */
33
+ readonly shippingPaths: readonly string[];
34
+ /** End-to-end deadline across all git checks in milliseconds (default `30_000`). */
35
+ readonly timeoutMs?: number;
36
+ /** Optional cancellation signal bound to the git checks. */
37
+ readonly signal?: AbortSignal;
38
+ }
39
+ /** Options for {@link assertCleanCliSource}. */
40
+ export interface CleanCliSourceOptions {
41
+ /** Absolute path to the git working tree root directory (bare repositories are refused). */
42
+ readonly repository: string;
43
+ /** When set, `HEAD` must resolve to this exact 40-lowercase-hex commit SHA. */
44
+ readonly expectedCommit?: string;
45
+ /**
46
+ * When omitted, any untracked file in the worktree is refused. When set to a non-empty list
47
+ * of repository-relative paths or `*` globs, untracked files are refused only under those
48
+ * paths (allowing sibling runtime state outside shipping inputs).
49
+ */
50
+ readonly untrackedPaths?: readonly string[];
51
+ /** When set, verifies `realpath(servingSource) === realpath(repository)`. */
52
+ readonly servingSource?: string;
53
+ /** End-to-end deadline across all git checks in milliseconds (default `30_000`). */
54
+ readonly timeoutMs?: number;
55
+ /** Optional cancellation signal bound to the git checks. */
56
+ readonly signal?: AbortSignal;
57
+ }
58
+ /**
59
+ * Derive a CLI semver string from `<commit>`: `major.minor` from `packageJsonPath` at `<commit>`
60
+ * paired with the full commit count touching `shippingPaths` up to `<commit>`. Accepts a git
61
+ * worktree root or bare repository root; refuses shallow repositories, non-commit SHAs,
62
+ * subdirectories and non-bare `.git` directories.
63
+ */
64
+ export declare function deriveCliVersionFromShippingInputs(options: CliShippingVersionOptions): Promise<string>;
65
+ /**
66
+ * Return `true` when any path in `shippingPaths` differs between `previousCommit` and
67
+ * `nextCommit`. Accepts a git worktree root or bare repository root, refuses non-commit SHAs,
68
+ * and uses `git diff --no-ext-diff --quiet`.
69
+ */
70
+ export declare function cliShippingInputsChanged(options: CliShippingInputsChangedOptions): Promise<boolean>;
71
+ /**
72
+ * Verify that `repository` is a clean git root matching `expectedCommit` (when set), with no
73
+ * tracked changes, no disallowed untracked files, and optional `servingSource` realpath identity.
74
+ * Returns the verified 40-lowercase-hex `HEAD` commit SHA.
75
+ */
76
+ export declare function assertCleanCliSource(options: CleanCliSourceOptions): Promise<string>;
77
+ //# sourceMappingURL=publication-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"publication-source.d.ts","sourceRoot":"","sources":["../../../src/tools/cli/publication-source.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAwBH,8DAA8D;AAC9D,MAAM,WAAW,yBAAyB;IACxC,wFAAwF;IACxF,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,qFAAqF;IACrF,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,2HAA2H;IAC3H,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC,6FAA6F;IAC7F,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,oFAAoF;IACpF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,oDAAoD;AACpD,MAAM,WAAW,+BAA+B;IAC9C,wFAAwF;IACxF,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,2CAA2C;IAC3C,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,yCAAyC;IACzC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,sFAAsF;IACtF,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,oFAAoF;IACpF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAED,gDAAgD;AAChD,MAAM,WAAW,qBAAqB;IACpC,4FAA4F;IAC5F,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,+EAA+E;IAC/E,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5C,6EAA6E;IAC7E,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,oFAAoF;IACpF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,4DAA4D;IAC5D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC/B;AAkLD;;;;;GAKG;AACH,wBAAsB,kCAAkC,CACtD,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,MAAM,CAAC,CAyCjB;AAED;;;;GAIG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,+BAA+B,GACvC,OAAO,CAAC,OAAO,CAAC,CA2BlB;AAED;;;;GAIG;AACH,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,CAmE1F"}
@@ -32,7 +32,7 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
32
32
  | `findOpenRouterModel` / `listOpenRouterModels` / `OpenRouterModelFilter` | functions / _type_ | query an `OpenRouterCatalogSnapshot` by exact `id` or `canonicalSlug`, or filter models by `tools`, `reasoning` (`reasoning`, `include_reasoning`, or declared efforts), `inputModalities`, `outputModalities`, `minContextLength` (via effective context `min(contextLength, topProviderContextLength)`), `maxPromptUsdPerMillion`, `maxCompletionUsdPerMillion`, `maxCacheWriteUsdPerMillion` (using the same ceiling semantics as `evaluateOpenRouterModelAdmission`), `freeOnly`, and `author` |
33
33
  | `createOpenRouterCatalogCache` / `OpenRouterCatalogCache` / `OpenRouterCatalogCacheOptions` / `OpenRouterCatalogCacheReadResult` / `OpenRouterCatalogStore` | function / _types_ | Web Fetch-clean cached OpenRouter catalog reader with single-flight coalescing, per-caller `AbortSignal` isolation, `freshMs` TTL, `retryBackoffMs` stale fallback, optional pluggable persistence (`store`), and `read`/`refresh`/`getModel`/`listModels`; `OpenRouterCatalogCacheReadResult` is a discriminated union on `status` (`'current' \| 'stale' \| 'unavailable'`) narrowing `snapshot`, `observedAt`, `models`, and `lastError` without casts (use `read()` for admission/billing decisions; `getModel`/`listModels` map `'unavailable'` to `undefined`/`[]`) |
34
34
  | `evaluateOpenRouterModelAdmission` / `OpenRouterAdmissionPolicySchema` / `OpenRouterAdmissionPolicy` / `OpenRouterModelAdmissionSchema` / `OpenRouterModelAdmission` / `OpenRouterAdmissionReasonSchema` / `OpenRouterAdmissionReason` | function / schemas / _types_ | decide one model from a stored snapshot: `admitted`, `unverified` (stale or future-dated snapshot, `'context-unknown'`, `'price-unknown'`, `'endpoints-unknown'`) or `rejected` with a reason (`requiredParameters`, `requiredInputModalities`, effective context `min(contextLength, topProviderContextLength)`, separated worst-case pricing ceilings `maxPromptUsdPerMillion` / `maxCompletionUsdPerMillion` / `maxCacheWriteUsdPerMillion` via `resolveOpenRouterModelCeiling`, live endpoint); `~`, `-latest`, `:batch`, `stealth/`, `openrouter/auto`, `aliasOf`, and `aliasTarget` models are always refused as `'floating-alias'`; the result is a schema, so a stored decision reads back |
35
- | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 is "not yet"; `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
35
+ | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 or absent `total_cost` returns `undefined` ("not yet", closed as `unknown` once `maxPendingAgeMs` passes in `reconcilePendingSpend`); `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
36
36
  | `openRouterModelCatalog` | function | complete tool-capable text catalog (`sort=top-weekly`) plus independent weekly popularity and available benchmark observations (optional static or async `apiKey` and `baseUrl` override); a `timeoutMs` that is not an integer from 1 to 2147483647 ms (the timer range) is refused when the catalog is created (`RangeError`) |
37
37
  | `OpenRouterModelCatalogOptions` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected `OpenRouterFetch` for catalog loading |
38
38
  | `OPENROUTER_API_BASE_URL` / `OpenRouterFetch` | const / _type_ | canonical default OpenRouter API v1 base URL (`https://openrouter.ai/api/v1`) and the one Web Fetch-compatible transport type (it receives the resolved `URL`) shared by `openRouterProvider`, catalog, spend and non-chat endpoint helpers |
@@ -14,9 +14,12 @@ Also read:
14
14
 
15
15
  ## `stitchkit/cli/publish`
16
16
 
17
- Build and release tooling, evolving. Publishes a CLI distribution into a local
18
- application-owned directory; the manifest, signatures, installer and updater it
19
- writes for stay in `stitchkit/cli` — [guide](../guide/cli.md#publishing-a-complete-version),
17
+ Build, source verification and distribution-route tooling, evolving. Publishes a
18
+ CLI distribution into a local application-owned directory, derives deterministic
19
+ versions from git shipping-input history, verifies clean source roots, and
20
+ serves verified channel manifests, immutable assets and `install.sh` over
21
+ `RawRoute[]`; the manifest, signatures, installer and updater it writes for stay
22
+ in `stitchkit/cli` — [guide](../guide/cli.md#publishing-a-complete-version),
20
23
  [ADR 0245](../decisions/0245-cli-publication-is-an-evolving-leaf.md).
21
24
 
22
25
  | Export | Kind | Summary |
@@ -25,5 +28,14 @@ writes for stay in `stitchkit/cli` — [guide](../guide/cli.md#publishing-a-comp
25
28
  | `CliPublicationOptions` | _type_ | identity, storage root, base URL, targets, limits, retention, the `admit` and `build` callbacks, optional signing and trust |
26
29
  | `CliPublicationPhase` | _type_ | the step `admit` is asked about — `prepare`, `build`, `commit` or `promote` |
27
30
  | `CliPublicationResult` | _type_ | `published` or `existing`, with the manifest ready to serve |
31
+ | `deriveCliVersionFromShippingInputs` | function | derive `major.minor.<count>` from `packageJsonPath` at `<commit>` and the full git commit count touching `shippingPaths`; accepts worktree or bare repository roots and refuses shallow clones, subdirectories, non-bare `.git` dirs and non-commit SHAs |
32
+ | `CliShippingVersionOptions` | _type_ | options for `deriveCliVersionFromShippingInputs` (`repository`, `commit`, `packageJsonPath`, `shippingPaths`, `timeoutMs`, `signal`) |
33
+ | `cliShippingInputsChanged` | function | return `true` when any path in `shippingPaths` differs between `previousCommit` and `nextCommit` using `git diff --no-ext-diff --quiet` |
34
+ | `CliShippingInputsChangedOptions` | _type_ | options for `cliShippingInputsChanged` (`repository`, `previousCommit`, `nextCommit`, `shippingPaths`, `timeoutMs`, `signal`) |
35
+ | `assertCleanCliSource` | function | verify a clean git root matching optional `expectedCommit`, optional `untrackedPaths` globs and optional `servingSource` realpath; returns verified 40-hex `HEAD` |
36
+ | `CleanCliSourceOptions` | _type_ | options for `assertCleanCliSource` (`repository`, `expectedCommit`, `untrackedPaths`, `servingSource`, `timeoutMs`, `signal`) |
37
+ | `createCliDistributionRoutes` | function | portable `RawRoute[]` (`GET` only) serving verified signed channel manifests (`no-store`), immutable versioned manifests and descriptor-streamed binary assets, and `install.sh`, failing closed with `503 No verified CLI build is published` |
38
+ | `CliDistributionRoutesOptions` | _type_ | options for `createCliDistributionRoutes` (`root`, `name`, `trust`, `channels`, `installerChannel`, `basePath`, `binaryName`, `installDir`, `maxManifestBytes`, `serviceName`, `onUnavailable`) |
39
+ | `CliDistributionUnavailableEvent` | _type_ | diagnostic event passed to `onUnavailable` with `route`, `channel`, optional `version`/`asset`, inline `reason`, optional `verdict` and `error` |
28
40
 
29
41
  ---
package/llms/cli.2.txt CHANGED
@@ -7,7 +7,7 @@
7
7
  Parts of this slice:
8
8
  - `llms/cli.txt`: Guide: CLI (docs/guide/cli.md)
9
9
  - `llms/cli.2.txt`: Guide: CLI (docs/guide/cli.md)
10
- - `llms/cli.3.txt`: API reference: `stitchkit/cli` (docs/api/reference.md)
10
+ - `llms/cli.3.txt`: Guide: CLI (docs/guide/cli.md) · API reference: `stitchkit/cli` (docs/api/reference.md)
11
11
 
12
12
  ==============================================================================
13
13
  # Guide: CLI (docs/guide/cli.md) (continued)
@@ -352,6 +352,89 @@ identity to recover; an error does not promise rollback. Optional `signing` and
352
352
  raw digest and size; the updater checks manifest authorship when given a trust
353
353
  root.
354
354
 
355
+ ### Versioning from shipping inputs and verifying clean source
356
+
357
+ When a CLI lives inside a larger repository, ordinary backend commits should not
358
+ force a new CLI version. `stitchkit/cli/publish` provides three git-backed
359
+ helpers (`deriveCliVersionFromShippingInputs`, `cliShippingInputsChanged`, and
360
+ `assertCleanCliSource`) built on `runNativeCommand` with a declared-only
361
+ environment (`GIT_TERMINAL_PROMPT=0`, `GIT_OPTIONAL_LOCKS=0`, ignoring inherited
362
+ `GIT_DIR` / `GIT_WORK_TREE`):
363
+
364
+ ```ts
365
+ import {
366
+ assertCleanCliSource,
367
+ cliShippingInputsChanged,
368
+ deriveCliVersionFromShippingInputs,
369
+ } from 'stitchkit/cli/publish'
370
+
371
+ const shippingPaths = ['packages/cli', 'packages/shared', 'bun.lock']
372
+ const head = await assertCleanCliSource({
373
+ repository: '/srv/myapp/source',
374
+ untrackedPaths: ['packages/cli', 'packages/shared', 'scripts/cli-publish*'],
375
+ })
376
+ const version = await deriveCliVersionFromShippingInputs({
377
+ repository: '/srv/myapp/source',
378
+ commit: head,
379
+ packageJsonPath: 'packages/cli/package.json',
380
+ shippingPaths,
381
+ })
382
+ const changed = await cliShippingInputsChanged({
383
+ repository: '/srv/myapp/source',
384
+ previousCommit,
385
+ nextCommit: head,
386
+ shippingPaths,
387
+ })
388
+ ```
389
+
390
+ `deriveCliVersionFromShippingInputs` reads `major.minor` from `packageJsonPath`
391
+ at `<commit>` and counts commits touching `shippingPaths` up to `<commit>`
392
+ (`major.minor.<count>`). Both `deriveCliVersionFromShippingInputs` and
393
+ `cliShippingInputsChanged` accept either a git worktree root or a bare
394
+ repository root (`realpath(--show-toplevel)` or `realpath(--absolute-git-dir)`
395
+ matching `realpath(repository)`), while `assertCleanCliSource` requires a
396
+ worktree root; subdirectories and non-bare `.git` directories are refused. All
397
+ three helpers require exact 40-hex commit objects (refusing tree, blob and
398
+ annotated-tag SHAs), full history for version counting (refusing shallow
399
+ clones), and safe repository-relative paths without `:` magic pathspecs.
400
+ `assertCleanCliSource` returns the verified 40-hex `HEAD` and checks tracked
401
+ changes plus either all untracked files (`--untracked-files=normal`) or only
402
+ untracked files matching `untrackedPaths`.
403
+
404
+ ### Serving a published CLI channel
405
+
406
+ `createCliDistributionRoutes` returns portable `RawRoute[]` (`GET` only) that
407
+ serve a directory published by `publishCli` under `<root>/channels/<channel>/`:
408
+
409
+ ```ts
410
+ import { createCliDistributionRoutes } from 'stitchkit/cli/publish'
411
+ import { createServer } from 'stitchkit/server'
412
+
413
+ const server = createServer({
414
+ rawRoutes: createCliDistributionRoutes({
415
+ root: process.env.CLI_DISTRIBUTION_DIR,
416
+ name: 'myapp',
417
+ trust: RELEASE_TRUST_ROOT,
418
+ onUnavailable: (event) => logger.warn(event, 'CLI distribution unavailable'),
419
+ }),
420
+ })
421
+ ```
422
+
423
+ Each configured channel mounts `${basePath}/channels/<channel>/manifest.json`
424
+ (`Cache-Control: no-store`, exact raw verified bytes) and
425
+ `${basePath}/channels/<channel>/:version/:asset` (immutable `manifest.json` or a
426
+ descriptor-streamed binary listed in the signed manifest with `Content-Length`
427
+ and `Content-Disposition`). `${basePath}/install.sh` renders `renderCliInstaller`
428
+ from the verified `installerChannel` manifest (`no-store`). Every read checks
429
+ canonical directory containment (`realpath` + `isWithinDir`), opens regular files
430
+ with `O_NOFOLLOW`, parses strict UTF-8 JSON without `__proto__`, verifies
431
+ `manifest.name` and Ed25519 signature strictly (`verifyCliManifest === 'valid'`),
432
+ and streams full asset bodies portably on both Bun and Node without `Bun.file`.
433
+ When `root` is `undefined`, `trust.keys` is empty, or the manifest is missing,
434
+ unsigned, tampered, oversized or has no assets, channel manifest and installer
435
+ routes fail closed with `503 No verified CLI build is published` (`no-store`),
436
+ and exceptions thrown by `onUnavailable` are isolated.
437
+
355
438
  ### Proving who built it — signing the manifest
356
439
 
357
440
  The asset digest proves the bytes that arrived are the bytes the manifest named.
@@ -864,65 +947,3 @@ public or local-operator surface, declare that explicitly with
864
947
  `access: { open: 'remote' | 'public' | 'local-operator', afterHandle? }`.
865
948
  A native-only CLI (only `commands`, no `services` or `runtimeTools`) takes no
866
949
  `access`.
867
-
868
- ## Typed context
869
-
870
- For a peer-free CLI, import `createCli` directly from `stitchkit/cli` and
871
- annotate the `context` factory's return type against your app's context shape
872
- — no optional peers are loaded:
873
-
874
- ```ts
875
- import { createCli } from 'stitchkit/cli'
876
-
877
- await createCli({
878
- name: 'myapp',
879
- version: '1.0.0',
880
- services,
881
- access: { gate: { beforeHandle: authHook } },
882
- context: (identity): { user: User | undefined } => ({ user: identity }),
883
- })
884
- ```
885
-
886
- If your application already installs `@modelcontextprotocol/server` and mounts
887
- MCP, peer-free agent tools (`mountAgentTools`), and CLI surfaces together, you
888
- can also pin the shared context type once via `createToolkit<AppContext>()`
889
- from `stitchkit/tools/toolkit` — the tool-side mirror of `createImplement`
890
- ([ADR 0017](../decisions/0017-typed-tool-context.md),
891
- [ADR 0284](../decisions/0284-the-tools-barrel-loads-no-optional-peer.md),
892
- [ADR 0338](../decisions/0338-toolkit-stays-free-of-ai-peer.md)). It stays free
893
- of the `ai` peer; callers needing an AI SDK `ToolSet` use `mountAgent` from
894
- `stitchkit/tools/agent`:
895
-
896
- ```ts
897
- import { createToolkit } from 'stitchkit/tools/toolkit'
898
-
899
- const tools = createToolkit<{ user: User }>()
900
- await tools.createCli({
901
- name: 'myapp',
902
- version: '1.0.0',
903
- services,
904
- access: { gate: { beforeHandle: authHook } },
905
- context: (identity) => ({ user: identity }), // checked against { user: User }
906
- })
907
- ```
908
-
909
- ## Remaining boundary
910
-
911
- File-upload (`multipart`) contract endpoints remain CLI-invisible, the same as
912
- on MCP/Agent: their wire body is not a JSON tool form. Model file-oriented
913
- application behavior as a managed pathless command, or binary-only behavior as
914
- a native command. Streaming (SSE) output is not yet piped to stdout.
915
-
916
- ## Active decisions
917
-
918
- The current CLI parsing, routing, view-checking and runner contract is governed
919
- by:
920
-
921
- - [ADR 0083](../decisions/0083-cli-composes-managed-and-native-commands.md) — composition of contract, runtime and native commands with lazy credential-free native startup.
922
- - [ADR 0289](../decisions/0289-a-managed-command-owns-its-terminal-result-and-a-stream-is-a-command.md) — managed `results` presentation/exit policies, `--schema` and streaming CLI commands.
923
- - [ADR 0295](../decisions/0295-quiet-suppresses-profile-selection-notices.md) — `--quiet` suppresses inferred-profile notices before and inside `createCli`.
924
- - [ADR 0296](../decisions/0296-framework-options-reserve-their-cli-spellings.md) — framework option spellings are reserved and cannot be declared as command names.
925
- - [ADR 0310](../decisions/0310-one-model-for-cli-invocation-and-json-schema-keywords.md) — single-pass `scanCliInvocation`, exhaustive JSON Schema keyword table, pre-call view column checks, shared runner and removal of the ADR 0296 transitional refusal:
926
- - **Boolean case policy:** inline boolean words (`true`/`1`/`yes`/`on`, `false`/`0`/`no`/`off`) and separate adjacent boolean tokens (`true`, `false`) are matched **case-insensitively** (`--quiet TRUE cmd` sets `quiet: true` and selects `cmd`); invalid inline values such as `--quiet=maybe` fail with exit code 2 before any profile notice is printed.
927
- - **Broken boolean boundary:** adjacent `--flag false` remains a value (`inspect --dry-run false` executes `inspect`), but a bare boolean framework flag separated from `true` or `false` by a stripped token (a command name or an application option — `--dry-run inspect false` or `inspect --dry-run --profile demo false`) is refused with exit code 2, zero handler calls, and a hint to pass `--flag=false` or `-- false`.
928
- - **Passthrough coercion:** untyped passthrough flags coerce only `true`/`false` and numbers (`--mode on` stays `"on"`).
package/llms/cli.3.txt CHANGED
@@ -6,7 +6,73 @@
6
6
  Parts of this slice:
7
7
  - `llms/cli.txt`: Guide: CLI (docs/guide/cli.md)
8
8
  - `llms/cli.2.txt`: Guide: CLI (docs/guide/cli.md)
9
- - `llms/cli.3.txt`: API reference: `stitchkit/cli` (docs/api/reference.md)
9
+ - `llms/cli.3.txt`: Guide: CLI (docs/guide/cli.md) · API reference: `stitchkit/cli` (docs/api/reference.md)
10
+
11
+ ==============================================================================
12
+ # Guide: CLI (docs/guide/cli.md) (continued)
13
+ ==============================================================================
14
+
15
+ ## Typed context
16
+
17
+ For a peer-free CLI, import `createCli` directly from `stitchkit/cli` and
18
+ annotate the `context` factory's return type against your app's context shape
19
+ — no optional peers are loaded:
20
+
21
+ ```ts
22
+ import { createCli } from 'stitchkit/cli'
23
+
24
+ await createCli({
25
+ name: 'myapp',
26
+ version: '1.0.0',
27
+ services,
28
+ access: { gate: { beforeHandle: authHook } },
29
+ context: (identity): { user: User | undefined } => ({ user: identity }),
30
+ })
31
+ ```
32
+
33
+ If your application already installs `@modelcontextprotocol/server` and mounts
34
+ MCP, peer-free agent tools (`mountAgentTools`), and CLI surfaces together, you
35
+ can also pin the shared context type once via `createToolkit<AppContext>()`
36
+ from `stitchkit/tools/toolkit` — the tool-side mirror of `createImplement`
37
+ ([ADR 0017](../decisions/0017-typed-tool-context.md),
38
+ [ADR 0284](../decisions/0284-the-tools-barrel-loads-no-optional-peer.md),
39
+ [ADR 0338](../decisions/0338-toolkit-stays-free-of-ai-peer.md)). It stays free
40
+ of the `ai` peer; callers needing an AI SDK `ToolSet` use `mountAgent` from
41
+ `stitchkit/tools/agent`:
42
+
43
+ ```ts
44
+ import { createToolkit } from 'stitchkit/tools/toolkit'
45
+
46
+ const tools = createToolkit<{ user: User }>()
47
+ await tools.createCli({
48
+ name: 'myapp',
49
+ version: '1.0.0',
50
+ services,
51
+ access: { gate: { beforeHandle: authHook } },
52
+ context: (identity) => ({ user: identity }), // checked against { user: User }
53
+ })
54
+ ```
55
+
56
+ ## Remaining boundary
57
+
58
+ File-upload (`multipart`) contract endpoints remain CLI-invisible, the same as
59
+ on MCP/Agent: their wire body is not a JSON tool form. Model file-oriented
60
+ application behavior as a managed pathless command, or binary-only behavior as
61
+ a native command. Streaming (SSE) output is not yet piped to stdout.
62
+
63
+ ## Active decisions
64
+
65
+ The current CLI parsing, routing, view-checking and runner contract is governed
66
+ by:
67
+
68
+ - [ADR 0083](../decisions/0083-cli-composes-managed-and-native-commands.md) — composition of contract, runtime and native commands with lazy credential-free native startup.
69
+ - [ADR 0289](../decisions/0289-a-managed-command-owns-its-terminal-result-and-a-stream-is-a-command.md) — managed `results` presentation/exit policies, `--schema` and streaming CLI commands.
70
+ - [ADR 0295](../decisions/0295-quiet-suppresses-profile-selection-notices.md) — `--quiet` suppresses inferred-profile notices before and inside `createCli`.
71
+ - [ADR 0296](../decisions/0296-framework-options-reserve-their-cli-spellings.md) — framework option spellings are reserved and cannot be declared as command names.
72
+ - [ADR 0310](../decisions/0310-one-model-for-cli-invocation-and-json-schema-keywords.md) — single-pass `scanCliInvocation`, exhaustive JSON Schema keyword table, pre-call view column checks, shared runner and removal of the ADR 0296 transitional refusal:
73
+ - **Boolean case policy:** inline boolean words (`true`/`1`/`yes`/`on`, `false`/`0`/`no`/`off`) and separate adjacent boolean tokens (`true`, `false`) are matched **case-insensitively** (`--quiet TRUE cmd` sets `quiet: true` and selects `cmd`); invalid inline values such as `--quiet=maybe` fail with exit code 2 before any profile notice is printed.
74
+ - **Broken boolean boundary:** adjacent `--flag false` remains a value (`inspect --dry-run false` executes `inspect`), but a bare boolean framework flag separated from `true` or `false` by a stripped token (a command name or an application option — `--dry-run inspect false` or `inspect --dry-run --profile demo false`) is refused with exit code 2, zero handler calls, and a hint to pass `--flag=false` or `-- false`.
75
+ - **Passthrough coercion:** untyped passthrough flags coerce only `true`/`false` and numbers (`--mode on` stays `"on"`).
10
76
 
11
77
  ==============================================================================
12
78
  # API reference: `stitchkit/cli` (docs/api/reference.md)
package/llms/cli.txt CHANGED
@@ -7,7 +7,7 @@
7
7
  Parts of this slice:
8
8
  - `llms/cli.txt`: Guide: CLI (docs/guide/cli.md)
9
9
  - `llms/cli.2.txt`: Guide: CLI (docs/guide/cli.md)
10
- - `llms/cli.3.txt`: API reference: `stitchkit/cli` (docs/api/reference.md)
10
+ - `llms/cli.3.txt`: Guide: CLI (docs/guide/cli.md) · API reference: `stitchkit/cli` (docs/api/reference.md)
11
11
 
12
12
  ==============================================================================
13
13
  # Guide: CLI (docs/guide/cli.md)
package/llms/files.txt CHANGED
@@ -29,7 +29,7 @@ available from `stitchkit/contract`.
29
29
  | `ManagedFileError` / `ManagedFileErrorCode` | class / _type_ | stable boundary failures; registered `FILE_*` mistakes are caller-safe while `FILE_IO_ERROR` remains internal |
30
30
  | `ManagedFileInspector` | _type_ | bounded-prefix read/write inspection callback with a finite cancellation signal that cannot own path or size |
31
31
  | `ManagedFileInspectionInput` / `ManagedFileInspection` | _type_ | inspector prefix/name/declared media/signal input and validated metadata-only result |
32
- | `writeFileAtomic` / `writeFileAtomicSync` / `WriteFileAtomicOptions` | function / _type_ | replace a file atomically: a random staging name created exclusively (never through a planted link), the mode set on the descriptor before the file is visible (default `0o600`, not masked by the umask), `fsync`, rename; a failure leaves the target and no staging file. The asynchronous form keeps the event loop running. A process killed before publication leaves its staging file; sweeping it is the caller's job |
32
+ | `writeFileAtomic` / `writeFileAtomicSync` / `WriteFileAtomicOptions` / `WriteFileAtomicOwner` | function / _type_ | replace a file atomically: a random staging name created exclusively with `O_NOFOLLOW` (never through a planted link), optional POSIX `owner` (`'preserve'` from an existing regular target via `lstat`, or explicit `{ uid, gid }`, applied via `fchown` after comparing real `fstat(fd)` and strictly before `fchmod`), the exact `mode` set on the descriptor before the file is visible (default `0o600`, not masked by the umask), `fsync`, rename; a failure leaves the target untouched, removes the staging file, and propagates the native OS error. The asynchronous form keeps the event loop running. A process killed before publication leaves its staging file; sweeping it is the caller's job |
33
33
  | `isAtomicStagingName` | function | true for a staging file name of an atomic write of this library (`.stitchkit-<24 lowercase hex>.tmp`, also used by the managed writer and the chunk spool); the form is a stable contract, and changing it is a breaking change ([ADR 0242](../decisions/0242-atomic-staging-name-is-a-public-contract.md)) |
34
34
  | `sweepAtomicStaging` / `SweepAtomicStagingOptions` | function / _type_ | remove abandoned staging files from one `directory`: only regular files matching `isAtomicStagingName` and older than the required `olderThanMs`, never following a symlink or entering a subdirectory; stops on `signal`; returns the removed names, `[]` for a `directory` that does not exist |
35
35
  | `withExclusiveLock` / `ExclusiveLockOptions` / `ExclusiveLock` / `ExclusiveLockOwner` | function / _type_ | run work under an exclusive lock between processes — a file recording its owner (pid, host, machine identity, time and nullable kernel process identity); waits up to `timeoutMs` (default 10 s) and stops on `signal`; a dead owner on this machine is taken over, a live, slow or foreign one never is; a lock recorded by this very process is held only while one of its descriptors is open on it, so the lock an earlier image of the same PID left (`bun --watch` restarts in place) is taken over at once; the lock is published with its owner already recorded (temporary file plus hard link), so a stalled holder is never displaced; a legacy empty lock file is taken by age only when `ownerlessGraceMs` is a number (default `null`: never; an abandoned empty reclaim guard is taken after 5 000 ms unless a value is set); exact `mode` is independent of umask; shared readers need a common group and traversable directories |
package/llms/process.txt CHANGED
@@ -50,14 +50,34 @@ try {
50
50
  await writeFileAtomic('/srv/app/state.json', '{"version":2}', {
51
51
  replace: true, durability: 'directory',
52
52
  })
53
+ // When a privileged process (e.g. root) updates a private config owned by a service user:
54
+ await writeFileAtomic('/etc/app/node.json', '{"version":2}', {
55
+ mode: 0o600, owner: 'preserve',
56
+ })
57
+ // Or set an explicit POSIX owner on creation or replacement:
58
+ await writeFileAtomic('/etc/app/node.json', '{"version":2}', {
59
+ mode: 0o600, owner: { uid: 1000, gid: 1000 },
60
+ })
53
61
  ```
54
62
 
55
63
  The defaults are `replace: true`, `durability: 'file'` and `mode: 0o600`: file fsync and atomic
56
64
  replacement. `durability: 'none'` skips every sync. `'directory'` runs the full sequence: write all
57
- bytes, exact descriptor chmod, file fsync, rename (replace) or link (create), remove the staging
58
- link, parent directory fsync. `writeFileAtomicSync` takes the same options and runs the same order.
59
- Create fails with the native `EEXIST` when the target exists, is a symlink, or a concurrent writer
60
- won. Never turn that refusal into a replace automatically.
65
+ bytes, optional descriptor `fchown`, exact descriptor `fchmod`, file fsync, rename (replace) or link
66
+ (create), remove the staging link, parent directory fsync. `writeFileAtomicSync` takes the same
67
+ options and runs the same order. Create fails with the native `EEXIST` when the target exists, is a
68
+ symlink, or a concurrent writer won. Never turn that refusal into a replace automatically.
69
+
70
+ `owner: 'preserve'` inspects an existing regular file at `target` with `lstat` (never following a
71
+ symlink; missing or non-regular targets keep the kernel default) and cannot be combined with
72
+ `replace: false`. `owner: { uid, gid }` validates numeric POSIX IDs (`0..4294967294`; `0xffff_ffff`
73
+ is refused because POSIX `fchown` treats `(uid_t)-1` as a no-op). Both forms compare against the
74
+ staged descriptor's actual `fstat(fd)` — never guessing from `process.getuid()`/`process.getgid()`
75
+ — call `fchown` strictly before `fchmod(mode)` and `fsync`, narrow the staging creation mode to
76
+ `mode & 0o700` while ownership is pending, remove the staging file on any error (including `EPERM`
77
+ and `EACCES`), and rethrow the original system error untouched. With `replace: false`,
78
+ `idempotent: true` and an explicit `owner`, an existing target satisfies the idempotent check only
79
+ when its bytes, mode and `(uid, gid)` all match (while a staging `fchown` failure such as `EPERM`
80
+ still fails before publication). Ownership options are refused explicitly on Windows.
61
81
 
62
82
  `AtomicFilePublicationError.published === true` tells a visible target from an unconfirmed
63
83
  acknowledgement. `phase` is `cleanup`, `directory-sync` or `directory-close`; the primary cause is
package/llms/spend.txt CHANGED
@@ -121,9 +121,15 @@ nor stored refuses the call.
121
121
 
122
122
  ## Afterwards
123
123
 
124
- - `reconcilePendingSpend({ store, reconcilers })` asks each provider for the cost of
125
- attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and settles
126
- rank-3 receipts. The store needs `pendingCosts`.
124
+ - `reconcilePendingSpend({ store, reconcilers, maxPendingAgeMs })` asks each provider for
125
+ the cost of attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
126
+ settles rank-3 receipts. Pass `maxPendingAgeMs` so an attempt whose reconciler still
127
+ returns `undefined` (for example a 404 or missing `total_cost`) after that age — measured
128
+ from `record.receipt.at`, or `record.attempt.startedAt` when no receipt exists — settles
129
+ as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` instead of staying
130
+ `pending` forever and filling `pendingCosts`; before `maxPendingAgeMs`, or when omitted,
131
+ `undefined` keeps the row `pending`, and reconciler failures stay `pending` for the next
132
+ pass. The store needs `pendingCosts`.
127
133
  - `closeOrphanedSpend({ store, olderThanMs })` closes attempts whose process never
128
134
  came back to them as `orphaned`, cost `unknown`. The store needs `openAttempts`.
129
135
 
@@ -189,7 +195,7 @@ Peer-free, server-only spend accounting for paid model APIs (→ [guide](../guid
189
195
  | `runWithSpendAttribution` / `getSpendAttribution` | function | the attribution of every gateway call in a call chain (AsyncLocalStorage); nested calls refine, `labels` merge |
190
196
  | `openAiCompatibleUsage` / `SpendFactsReader` | const / _type_ | reads `id`, `model` and `usage` (tokens, reasoning, cache, OpenRouter's `cost`) from a JSON body or the stream's events |
191
197
  | `createSpooledSpendStore` / `SpooledSpendStore` / `SpooledSpendStoreConfig` | function / _types_ | a ledger that survives its database: on disk first (`0o600`, bounded), delivered after; `recover()` replays in order, an attempt before its receipts — a receipt whose attempt is undelivered waits on disk with it, in the live path too; a record neither spooled nor stored refuses the call; `pendingCosts` and `openAttempts` pass through |
192
- | `mergeSpendReceipt` | function | the monotone merge a ledger applies: a higher rank adds what it knows, equal ranks resolve by `at`, a closed outcome never returns to `pending`, a reported cost is never erased, and an `orphaned` close never replaces a real one (a real one replaces it) |
193
- | `reconcilePendingSpend` / `SpendReconciler` / `ReconcilePendingSpendOptions` / `SpendReconcileResult` | function / _types_ | one pass over attempts whose cost is `pending`: each gateway's reconciler answers, rank-3 receipts are settled; `onError` sees a reconciler that threw, returned invalid facts, or failed receipt merging (while `store.settle` failures still reject) |
198
+ | `mergeSpendReceipt` | function | the monotone merge a ledger applies: a higher rank adds what it knows, equal ranks resolve by `at` (a factual cost breaks exact-timestamp ties), a closed outcome never returns to `pending`, a reported cost is never erased, a non-factual rank-3 reconciler receipt neither pollutes a factual cost with `failureCode`/`failureMessage` nor leaves those fields behind once a factual price arrives (while rank 1–2 transport failure codes stay intact), and an `orphaned` close never replaces a real one (a real one replaces it) |
199
+ | `reconcilePendingSpend` / `SpendReconciler` / `ReconcilePendingSpendOptions` / `SpendReconcileResult` | function / _types_ | one pass over attempts whose cost is `pending`: each gateway's reconciler answers, rank-3 receipts are settled; optional `maxPendingAgeMs` (positive safe integer validated upfront) settles attempts whose reconciler still returns `undefined` at or past that age since `record.receipt.at` (or `record.attempt.startedAt`) as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` (while reconciler throws and gateways without a reconciler stay `pending`); `onError` sees a reconciler that threw or returned invalid facts, an invalid record timestamp, or a receipt-merge failure (while broken `now()` clocks and `store.settle` failures still reject) |
194
200
  | `closeOrphanedSpend` | function | closes attempts left open longer than `olderThanMs` as `orphaned` with an `unknown` cost |
195
201
  | `SpendAttributionSchema` / `SpendAttribution` / `SpendAttemptSchema` / `SpendAttempt` / `SpendReceiptSchema` / `SpendReceipt` / `SpendRecordSchema` / `SpendRecord` / `SpendFactsSchema` / `SpendFacts` / `SpendOutcomeSchema` / `SpendOutcome` / `SpendCostStatusSchema` / `SpendCostStatus` / `SpendLedgerStore` / `SpendReceiptRank` | schemas / _types_ | the records: attribution (free strings: `scope`, `purpose`, `operation`, `labels`, run/invocation/step links), the attempt, the receipt (`rank`, `outcome`, `facts`), and the ledger the application implements |
@@ -74,7 +74,7 @@ own, recorded as an ADR.
74
74
  | `stitchkit/tools/invoker` | server | stable<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | peer-free `createToolInvoker` over the canonical contract tool runner |
75
75
  | `stitchkit/tools/connections` | server (Bun or Node) | evolving<br>_redefined in 3 of the 43 minors since 0.94.0, most recently 0.127.0_ | consume external MCP servers and a bounded OpenAPI subset — typed reauthorization, a per-request host fence and per-call credentials |
76
76
  | `stitchkit/cli` | server | stable<br>_redefined in 12 of the 43 minors since 0.94.0, most recently 0.128.0_ | `createCli` / `createCliInvoker` — runtime and strict NodeNext declarations without MCP SDK / `ai` |
77
- | `stitchkit/cli/publish` | build and release tooling (Bun or Node, POSIX) | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | `publishCli` — commit a verified CLI distribution and move its public manifest last; see [CLI guide](cli.md#publishing-a-complete-version) |
77
+ | `stitchkit/cli/publish` | build, release and server tooling (Bun or Node, POSIX) | evolving<br>_redefined in 0 of the 43 minors since 0.94.0_ | `publishCli`, shipping-input versioning (`deriveCliVersionFromShippingInputs`, `cliShippingInputsChanged`, `assertCleanCliSource`), and `createCliDistributionRoutes` (`RawRoute[]` channel manifest, asset and installer routes); see [CLI guide](cli.md#publishing-a-complete-version) |
78
78
  | `stitchkit/remote` | browser **and** server | stable<br>_redefined in 1 of the 43 minors since 0.94.0, most recently 0.104.0_ | peer-free `implementRemote` for thin HTTP proxy processes |
79
79
  | `stitchkit/process` | server (Bun or Node, POSIX) | evolving<br>_redefined in 4 of the 43 minors since 0.94.0, most recently 0.133.0_ | finite native commands, byte sinks, bounded capture, process-group cancellation and opt-in Linux/Darwin owner-loss cleanup; contract operations executed in one-call child processes |
80
80
  | `stitchkit/process/bootstrap` | bundled server entry (Bun, POSIX) | evolving<br>_redefined in 0 of the 4 minors since 0.133.0_ | narrow bootstrap that keeps the process runner lazy while carrying the package's own invocations — the owner-loss guard and the process root of launched work — in a single-file bundle |