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-5c4m8zdf.js → index-tjakdpf2.js} +45 -45
package/llms-full.txt CHANGED
@@ -65,7 +65,7 @@ own, recorded as an ADR.
65
65
  | `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 |
66
66
  | `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 |
67
67
  | `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` |
68
- | `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) |
68
+ | `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) |
69
69
  | `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 |
70
70
  | `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 |
71
71
  | `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 |
@@ -10797,14 +10797,34 @@ try {
10797
10797
  await writeFileAtomic('/srv/app/state.json', '{"version":2}', {
10798
10798
  replace: true, durability: 'directory',
10799
10799
  })
10800
+ // When a privileged process (e.g. root) updates a private config owned by a service user:
10801
+ await writeFileAtomic('/etc/app/node.json', '{"version":2}', {
10802
+ mode: 0o600, owner: 'preserve',
10803
+ })
10804
+ // Or set an explicit POSIX owner on creation or replacement:
10805
+ await writeFileAtomic('/etc/app/node.json', '{"version":2}', {
10806
+ mode: 0o600, owner: { uid: 1000, gid: 1000 },
10807
+ })
10800
10808
  ```
10801
10809
 
10802
10810
  The defaults are `replace: true`, `durability: 'file'` and `mode: 0o600`: file fsync and atomic
10803
10811
  replacement. `durability: 'none'` skips every sync. `'directory'` runs the full sequence: write all
10804
- bytes, exact descriptor chmod, file fsync, rename (replace) or link (create), remove the staging
10805
- link, parent directory fsync. `writeFileAtomicSync` takes the same options and runs the same order.
10806
- Create fails with the native `EEXIST` when the target exists, is a symlink, or a concurrent writer
10807
- won. Never turn that refusal into a replace automatically.
10812
+ bytes, optional descriptor `fchown`, exact descriptor `fchmod`, file fsync, rename (replace) or link
10813
+ (create), remove the staging link, parent directory fsync. `writeFileAtomicSync` takes the same
10814
+ options and runs the same order. Create fails with the native `EEXIST` when the target exists, is a
10815
+ symlink, or a concurrent writer won. Never turn that refusal into a replace automatically.
10816
+
10817
+ `owner: 'preserve'` inspects an existing regular file at `target` with `lstat` (never following a
10818
+ symlink; missing or non-regular targets keep the kernel default) and cannot be combined with
10819
+ `replace: false`. `owner: { uid, gid }` validates numeric POSIX IDs (`0..4294967294`; `0xffff_ffff`
10820
+ is refused because POSIX `fchown` treats `(uid_t)-1` as a no-op). Both forms compare against the
10821
+ staged descriptor's actual `fstat(fd)` — never guessing from `process.getuid()`/`process.getgid()`
10822
+ — call `fchown` strictly before `fchmod(mode)` and `fsync`, narrow the staging creation mode to
10823
+ `mode & 0o700` while ownership is pending, remove the staging file on any error (including `EPERM`
10824
+ and `EACCES`), and rethrow the original system error untouched. With `replace: false`,
10825
+ `idempotent: true` and an explicit `owner`, an existing target satisfies the idempotent check only
10826
+ when its bytes, mode and `(uid, gid)` all match (while a staging `fchown` failure such as `EPERM`
10827
+ still fails before publication). Ownership options are refused explicitly on Windows.
10808
10828
 
10809
10829
  `AtomicFilePublicationError.published === true` tells a visible target from an unconfirmed
10810
10830
  acknowledgement. `phase` is `cleanup`, `directory-sync` or `directory-close`; the primary cause is
@@ -13644,6 +13664,89 @@ identity to recover; an error does not promise rollback. Optional `signing` and
13644
13664
  raw digest and size; the updater checks manifest authorship when given a trust
13645
13665
  root.
13646
13666
 
13667
+ ### Versioning from shipping inputs and verifying clean source
13668
+
13669
+ When a CLI lives inside a larger repository, ordinary backend commits should not
13670
+ force a new CLI version. `stitchkit/cli/publish` provides three git-backed
13671
+ helpers (`deriveCliVersionFromShippingInputs`, `cliShippingInputsChanged`, and
13672
+ `assertCleanCliSource`) built on `runNativeCommand` with a declared-only
13673
+ environment (`GIT_TERMINAL_PROMPT=0`, `GIT_OPTIONAL_LOCKS=0`, ignoring inherited
13674
+ `GIT_DIR` / `GIT_WORK_TREE`):
13675
+
13676
+ ```ts
13677
+ import {
13678
+ assertCleanCliSource,
13679
+ cliShippingInputsChanged,
13680
+ deriveCliVersionFromShippingInputs,
13681
+ } from 'stitchkit/cli/publish'
13682
+
13683
+ const shippingPaths = ['packages/cli', 'packages/shared', 'bun.lock']
13684
+ const head = await assertCleanCliSource({
13685
+ repository: '/srv/myapp/source',
13686
+ untrackedPaths: ['packages/cli', 'packages/shared', 'scripts/cli-publish*'],
13687
+ })
13688
+ const version = await deriveCliVersionFromShippingInputs({
13689
+ repository: '/srv/myapp/source',
13690
+ commit: head,
13691
+ packageJsonPath: 'packages/cli/package.json',
13692
+ shippingPaths,
13693
+ })
13694
+ const changed = await cliShippingInputsChanged({
13695
+ repository: '/srv/myapp/source',
13696
+ previousCommit,
13697
+ nextCommit: head,
13698
+ shippingPaths,
13699
+ })
13700
+ ```
13701
+
13702
+ `deriveCliVersionFromShippingInputs` reads `major.minor` from `packageJsonPath`
13703
+ at `<commit>` and counts commits touching `shippingPaths` up to `<commit>`
13704
+ (`major.minor.<count>`). Both `deriveCliVersionFromShippingInputs` and
13705
+ `cliShippingInputsChanged` accept either a git worktree root or a bare
13706
+ repository root (`realpath(--show-toplevel)` or `realpath(--absolute-git-dir)`
13707
+ matching `realpath(repository)`), while `assertCleanCliSource` requires a
13708
+ worktree root; subdirectories and non-bare `.git` directories are refused. All
13709
+ three helpers require exact 40-hex commit objects (refusing tree, blob and
13710
+ annotated-tag SHAs), full history for version counting (refusing shallow
13711
+ clones), and safe repository-relative paths without `:` magic pathspecs.
13712
+ `assertCleanCliSource` returns the verified 40-hex `HEAD` and checks tracked
13713
+ changes plus either all untracked files (`--untracked-files=normal`) or only
13714
+ untracked files matching `untrackedPaths`.
13715
+
13716
+ ### Serving a published CLI channel
13717
+
13718
+ `createCliDistributionRoutes` returns portable `RawRoute[]` (`GET` only) that
13719
+ serve a directory published by `publishCli` under `<root>/channels/<channel>/`:
13720
+
13721
+ ```ts
13722
+ import { createCliDistributionRoutes } from 'stitchkit/cli/publish'
13723
+ import { createServer } from 'stitchkit/server'
13724
+
13725
+ const server = createServer({
13726
+ rawRoutes: createCliDistributionRoutes({
13727
+ root: process.env.CLI_DISTRIBUTION_DIR,
13728
+ name: 'myapp',
13729
+ trust: RELEASE_TRUST_ROOT,
13730
+ onUnavailable: (event) => logger.warn(event, 'CLI distribution unavailable'),
13731
+ }),
13732
+ })
13733
+ ```
13734
+
13735
+ Each configured channel mounts `${basePath}/channels/<channel>/manifest.json`
13736
+ (`Cache-Control: no-store`, exact raw verified bytes) and
13737
+ `${basePath}/channels/<channel>/:version/:asset` (immutable `manifest.json` or a
13738
+ descriptor-streamed binary listed in the signed manifest with `Content-Length`
13739
+ and `Content-Disposition`). `${basePath}/install.sh` renders `renderCliInstaller`
13740
+ from the verified `installerChannel` manifest (`no-store`). Every read checks
13741
+ canonical directory containment (`realpath` + `isWithinDir`), opens regular files
13742
+ with `O_NOFOLLOW`, parses strict UTF-8 JSON without `__proto__`, verifies
13743
+ `manifest.name` and Ed25519 signature strictly (`verifyCliManifest === 'valid'`),
13744
+ and streams full asset bodies portably on both Bun and Node without `Bun.file`.
13745
+ When `root` is `undefined`, `trust.keys` is empty, or the manifest is missing,
13746
+ unsigned, tampered, oversized or has no assets, channel manifest and installer
13747
+ routes fail closed with `503 No verified CLI build is published` (`no-store`),
13748
+ and exceptions thrown by `onUnavailable` are isolated.
13749
+
13647
13750
  ### Proving who built it — signing the manifest
13648
13751
 
13649
13752
  The asset digest proves the bytes that arrived are the bytes the manifest named.
@@ -17889,9 +17992,15 @@ nor stored refuses the call.
17889
17992
 
17890
17993
  ## Afterwards
17891
17994
 
17892
- - `reconcilePendingSpend({ store, reconcilers })` asks each provider for the cost of
17893
- attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and settles
17894
- rank-3 receipts. The store needs `pendingCosts`.
17995
+ - `reconcilePendingSpend({ store, reconcilers, maxPendingAgeMs })` asks each provider for
17996
+ the cost of attempts still `pending` (OpenRouter: `GET /api/v1/generation?id=`) and
17997
+ settles rank-3 receipts. Pass `maxPendingAgeMs` so an attempt whose reconciler still
17998
+ returns `undefined` (for example a 404 or missing `total_cost`) after that age — measured
17999
+ from `record.receipt.at`, or `record.attempt.startedAt` when no receipt exists — settles
18000
+ as `costStatus: 'unknown'` with `failureCode: 'price-never-reported'` instead of staying
18001
+ `pending` forever and filling `pendingCosts`; before `maxPendingAgeMs`, or when omitted,
18002
+ `undefined` keeps the row `pending`, and reconciler failures stay `pending` for the next
18003
+ pass. The store needs `pendingCosts`.
17895
18004
  - `closeOrphanedSpend({ store, olderThanMs })` closes attempts whose process never
17896
18005
  came back to them as `orphaned`, cost `unknown`. The store needs `openAttempts`.
17897
18006
 
@@ -30268,7 +30377,7 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
30268
30377
  | `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` |
30269
30378
  | `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`/`[]`) |
30270
30379
  | `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 |
30271
- | `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) |
30380
+ | `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) |
30272
30381
  | `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`) |
30273
30382
  | `OpenRouterModelCatalogOptions` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected `OpenRouterFetch` for catalog loading |
30274
30383
  | `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 |
@@ -31234,7 +31343,7 @@ available from `stitchkit/contract`.
31234
31343
  | `ManagedFileError` / `ManagedFileErrorCode` | class / _type_ | stable boundary failures; registered `FILE_*` mistakes are caller-safe while `FILE_IO_ERROR` remains internal |
31235
31344
  | `ManagedFileInspector` | _type_ | bounded-prefix read/write inspection callback with a finite cancellation signal that cannot own path or size |
31236
31345
  | `ManagedFileInspectionInput` / `ManagedFileInspection` | _type_ | inspector prefix/name/declared media/signal input and validated metadata-only result |
31237
- | `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 |
31346
+ | `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 |
31238
31347
  | `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)) |
31239
31348
  | `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 |
31240
31349
  | `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 |
@@ -31274,8 +31383,8 @@ Peer-free, server-only spend accounting for paid model APIs (→ [guide](../guid
31274
31383
  | `runWithSpendAttribution` / `getSpendAttribution` | function | the attribution of every gateway call in a call chain (AsyncLocalStorage); nested calls refine, `labels` merge |
31275
31384
  | `openAiCompatibleUsage` / `SpendFactsReader` | const / _type_ | reads `id`, `model` and `usage` (tokens, reasoning, cache, OpenRouter's `cost`) from a JSON body or the stream's events |
31276
31385
  | `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 |
31277
- | `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) |
31278
- | `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) |
31386
+ | `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) |
31387
+ | `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) |
31279
31388
  | `closeOrphanedSpend` | function | closes attempts left open longer than `olderThanMs` as `orphaned` with an `unknown` cost |
31280
31389
  | `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 |
31281
31390
 
@@ -31973,9 +32082,12 @@ SDK nor the `ai` peer.
31973
32082
 
31974
32083
  ## `stitchkit/cli/publish`
31975
32084
 
31976
- Build and release tooling, evolving. Publishes a CLI distribution into a local
31977
- application-owned directory; the manifest, signatures, installer and updater it
31978
- writes for stay in `stitchkit/cli` — [guide](../guide/cli.md#publishing-a-complete-version),
32085
+ Build, source verification and distribution-route tooling, evolving. Publishes a
32086
+ CLI distribution into a local application-owned directory, derives deterministic
32087
+ versions from git shipping-input history, verifies clean source roots, and
32088
+ serves verified channel manifests, immutable assets and `install.sh` over
32089
+ `RawRoute[]`; the manifest, signatures, installer and updater it writes for stay
32090
+ in `stitchkit/cli` — [guide](../guide/cli.md#publishing-a-complete-version),
31979
32091
  [ADR 0245](../decisions/0245-cli-publication-is-an-evolving-leaf.md).
31980
32092
 
31981
32093
  | Export | Kind | Summary |
@@ -31984,6 +32096,15 @@ writes for stay in `stitchkit/cli` — [guide](../guide/cli.md#publishing-a-comp
31984
32096
  | `CliPublicationOptions` | _type_ | identity, storage root, base URL, targets, limits, retention, the `admit` and `build` callbacks, optional signing and trust |
31985
32097
  | `CliPublicationPhase` | _type_ | the step `admit` is asked about — `prepare`, `build`, `commit` or `promote` |
31986
32098
  | `CliPublicationResult` | _type_ | `published` or `existing`, with the manifest ready to serve |
32099
+ | `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 |
32100
+ | `CliShippingVersionOptions` | _type_ | options for `deriveCliVersionFromShippingInputs` (`repository`, `commit`, `packageJsonPath`, `shippingPaths`, `timeoutMs`, `signal`) |
32101
+ | `cliShippingInputsChanged` | function | return `true` when any path in `shippingPaths` differs between `previousCommit` and `nextCommit` using `git diff --no-ext-diff --quiet` |
32102
+ | `CliShippingInputsChangedOptions` | _type_ | options for `cliShippingInputsChanged` (`repository`, `previousCommit`, `nextCommit`, `shippingPaths`, `timeoutMs`, `signal`) |
32103
+ | `assertCleanCliSource` | function | verify a clean git root matching optional `expectedCommit`, optional `untrackedPaths` globs and optional `servingSource` realpath; returns verified 40-hex `HEAD` |
32104
+ | `CleanCliSourceOptions` | _type_ | options for `assertCleanCliSource` (`repository`, `expectedCommit`, `untrackedPaths`, `servingSource`, `timeoutMs`, `signal`) |
32105
+ | `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` |
32106
+ | `CliDistributionRoutesOptions` | _type_ | options for `createCliDistributionRoutes` (`root`, `name`, `trust`, `channels`, `installerChannel`, `basePath`, `binaryName`, `installDir`, `maxManifestBytes`, `serviceName`, `onUnavailable`) |
32107
+ | `CliDistributionUnavailableEvent` | _type_ | diagnostic event passed to `onUnavailable` with `route`, `channel`, optional `version`/`asset`, inline `reason`, optional `verdict` and `error` |
31987
32108
 
31988
32109
  ---
31989
32110
 
package/llms.txt CHANGED
@@ -9,7 +9,7 @@ Build with stitchkit: define a contract once, then `implement` it and serve it (
9
9
  Load the slice for each entrypoint your code imports — `import … from 'stitchkit/server'` → `llms/server.txt`; the root `stitchkit` import → `llms/stitchkit.txt`. A slice holds that entrypoint's API reference section and the guide pages whose home it is; every guide lives in exactly one slice, and a slice that needs another's guide names it under "Also read". Each file is at most 50.0 KB; a longer one continues in numbered parts, each naming the next at its top. Moving across versions: load `llms/upgrading.txt` and the range slices it lists between your version and the target. `llms-full.txt` inlines everything; it is far larger than a context window, so do not read it whole.
10
10
 
11
11
  ## Entrypoint slices
12
- - **stitchkit**: [llms/stitchkit.txt](llms/stitchkit.txt) 44.4 KB → [llms/stitchkit.2.txt](llms/stitchkit.2.txt) 47.2 KB → [llms/stitchkit.3.txt](llms/stitchkit.3.txt) 29.4 KB
12
+ - **stitchkit**: [llms/stitchkit.txt](llms/stitchkit.txt) 44.6 KB → [llms/stitchkit.2.txt](llms/stitchkit.2.txt) 47.2 KB → [llms/stitchkit.3.txt](llms/stitchkit.3.txt) 29.4 KB
13
13
  - **stitchkit/live**: [llms/live.txt](llms/live.txt) 22.9 KB
14
14
  - **stitchkit/react**: [llms/react.txt](llms/react.txt) 8.7 KB
15
15
  - **stitchkit/react/keyboard**: [llms/react-keyboard.txt](llms/react-keyboard.txt) 22.7 KB
@@ -21,8 +21,8 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
21
21
  - **stitchkit/tools/contract**: [llms/tools-contract.txt](llms/tools-contract.txt) 0.2 KB
22
22
  - **stitchkit/tools/invoker**: [llms/tools-invoker.txt](llms/tools-invoker.txt) 0.2 KB
23
23
  - **stitchkit/tools/connections**: [llms/tools-connections.txt](llms/tools-connections.txt) 4.9 KB
24
- - **stitchkit/cli**: [llms/cli.txt](llms/cli.txt) 42.0 KB → [llms/cli.2.txt](llms/cli.2.txt) 46.9 KB → [llms/cli.3.txt](llms/cli.3.txt) 12.4 KB
25
- - **stitchkit/cli/publish**: [llms/cli-publish.txt](llms/cli-publish.txt) 1.5 KB
24
+ - **stitchkit/cli**: [llms/cli.txt](llms/cli.txt) 42.0 KB → [llms/cli.2.txt](llms/cli.2.txt) 47.0 KB → [llms/cli.3.txt](llms/cli.3.txt) 16.2 KB
25
+ - **stitchkit/cli/publish**: [llms/cli-publish.txt](llms/cli-publish.txt) 3.6 KB
26
26
  - **stitchkit/remote**: [llms/remote.txt](llms/remote.txt) 1.0 KB
27
27
  - **stitchkit/contract**: [llms/contract.txt](llms/contract.txt) 36.5 KB
28
28
  - **stitchkit/primitives**: [llms/primitives.txt](llms/primitives.txt) 15.2 KB
@@ -34,7 +34,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
34
34
  - **stitchkit/agent-runtime/harness**: [llms/agent-runtime-harness.txt](llms/agent-runtime-harness.txt) 13.7 KB
35
35
  - **stitchkit/agent-runtime/coding-tools**: [llms/agent-runtime-coding-tools.txt](llms/agent-runtime-coding-tools.txt) 5.0 KB
36
36
  - **stitchkit/agent-runtime/browser**: [llms/agent-runtime-browser.txt](llms/agent-runtime-browser.txt) 5.4 KB
37
- - **stitchkit/agent-runtime/openrouter**: [llms/agent-runtime-openrouter.txt](llms/agent-runtime-openrouter.txt) 14.9 KB
37
+ - **stitchkit/agent-runtime/openrouter**: [llms/agent-runtime-openrouter.txt](llms/agent-runtime-openrouter.txt) 15.0 KB
38
38
  - **stitchkit/agent-runtime/openai**: [llms/agent-runtime-openai.txt](llms/agent-runtime-openai.txt) 2.3 KB
39
39
  - **stitchkit/agent-runtime/anthropic**: [llms/agent-runtime-anthropic.txt](llms/agent-runtime-anthropic.txt) 2.9 KB
40
40
  - **stitchkit/agent-executor**: [llms/agent-executor.txt](llms/agent-executor.txt) 13.5 KB
@@ -54,9 +54,9 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
54
54
  - **stitchkit/application/diagnostic-journal**: [llms/application-diagnostic-journal.txt](llms/application-diagnostic-journal.txt) 1.8 KB
55
55
  - **stitchkit/testing**: [llms/testing.txt](llms/testing.txt) 34.1 KB
56
56
  - **stitchkit/agent-runtime/sandbox**: [llms/agent-runtime-sandbox.txt](llms/agent-runtime-sandbox.txt) 17.1 KB
57
- - **stitchkit/spend**: [llms/spend.txt](llms/spend.txt) 11.0 KB
57
+ - **stitchkit/spend**: [llms/spend.txt](llms/spend.txt) 12.2 KB
58
58
  - **stitchkit/spend/testing**: [llms/spend-testing.txt](llms/spend-testing.txt) 1.2 KB
59
- - **stitchkit/files**: [llms/files.txt](llms/files.txt) 11.4 KB
59
+ - **stitchkit/files**: [llms/files.txt](llms/files.txt) 11.7 KB
60
60
  - **stitchkit/service-host**: [llms/service-host.txt](llms/service-host.txt) 10.3 KB
61
61
  - **stitchkit/service-host/macos**: [llms/service-host-macos.txt](llms/service-host-macos.txt) 6.2 KB
62
62
  - **stitchkit/service-host/work**: [llms/service-host-work.txt](llms/service-host-work.txt) 4.1 KB
@@ -83,7 +83,7 @@ Load the slice for each entrypoint your code imports — `import … from 'stitc
83
83
  - **stitchkit/agent-runtime/react**: [llms/agent-runtime-react.txt](llms/agent-runtime-react.txt) 1.0 KB
84
84
  - **stitchkit/agent-runtime/realtime**: [llms/agent-runtime-realtime.txt](llms/agent-runtime-realtime.txt) 2.6 KB
85
85
  - **stitchkit/agent-runtime/ai-sdk**: [llms/agent-runtime-ai-sdk.txt](llms/agent-runtime-ai-sdk.txt) 1.6 KB
86
- - **stitchkit/process**: [llms/process.txt](llms/process.txt) 42.0 KB → [llms/process.2.txt](llms/process.2.txt) 31.1 KB
86
+ - **stitchkit/process**: [llms/process.txt](llms/process.txt) 43.5 KB → [llms/process.2.txt](llms/process.2.txt) 31.1 KB
87
87
  - **stitchkit/process/bootstrap**: [llms/process-bootstrap.txt](llms/process-bootstrap.txt) 1.0 KB
88
88
  - **stitchkit/files/packaging**: [llms/files-packaging.txt](llms/files-packaging.txt) 5.7 KB
89
89
  - **stitchkit/http**: [llms/http.txt](llms/http.txt) 3.0 KB
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stitchkit",
3
- "version": "0.136.4",
3
+ "version": "0.136.6",
4
4
  "description": "Contract-first backend framework — one defineContract() into an HTTP API, MCP tools, AI-agent tools and a typed client. Bun and Node.",
5
5
  "keywords": [
6
6
  "bun",
@@ -1,221 +0,0 @@
1
- import {
2
- AtomicFilePublicationError2,
3
- assertDirectoryDurability,
4
- syncDirectory,
5
- publishAtomicFile,
6
- publishAtomicFileSync
7
- } from "./index-2c5w2d1d.js";
8
- import {
9
- closeAfter,
10
- closeAfterSync,
11
- readBoundedFile,
12
- readBoundedFileSync
13
- } from "./index-s2e3h616.js";
14
- import {
15
- stagingPath
16
- } from "./index-psye60qn.js";
17
- import {
18
- errnoOf
19
- } from "./index-jj9228tt.js";
20
-
21
- // src/internal/atomic-file.ts
22
- import { closeSync, fchmodSync, fsyncSync, openSync, unlinkSync, writeSync } from "node:fs";
23
- import { open, unlink } from "node:fs/promises";
24
- import { dirname } from "node:path";
25
- var DEFAULT_MODE = 384;
26
- function bytesOf(data) {
27
- return typeof data === "string" ? new TextEncoder().encode(data) : data;
28
- }
29
- function assertWriteOptions(options) {
30
- if (options.idempotent === true && options.replace !== false) {
31
- throw new TypeError('writeFileAtomic option "idempotent: true" requires "replace: false"');
32
- }
33
- }
34
- function bytesEqual(left, right) {
35
- if (left.byteLength !== right.byteLength)
36
- return false;
37
- for (let index = 0;index < left.byteLength; index += 1) {
38
- if (left[index] !== right[index])
39
- return false;
40
- }
41
- return true;
42
- }
43
- function modeMatches(actualMode, expectedMode) {
44
- if (process.platform === "win32")
45
- return true;
46
- return actualMode !== undefined && (actualMode & 4095) === (expectedMode & 4095);
47
- }
48
- function syncDirectorySync(dir) {
49
- assertDirectoryDurability();
50
- const descriptor = openSync(dir, "r");
51
- closeAfterSync(() => closeSync(descriptor), () => fsyncSync(descriptor));
52
- }
53
- async function writeAllBytes(file, bytes) {
54
- for (let offset = 0;offset < bytes.byteLength; ) {
55
- const { bytesWritten } = await file.write(bytes, offset, bytes.byteLength - offset);
56
- if (bytesWritten === 0)
57
- throw new Error("zero-byte atomic-file write");
58
- offset += bytesWritten;
59
- }
60
- }
61
- async function writeFileAtomic2(target, data, options = {}) {
62
- return writeAtomicFileData(target, data, options);
63
- }
64
- function isMissing(error) {
65
- return errnoOf(error) === "ENOENT";
66
- }
67
- async function publishMaybeIdempotent(staged, target, mode, options, expectedBytes, io) {
68
- const publishOptions = {
69
- replace: options.replace ?? true,
70
- durability: options.durability ?? "file"
71
- };
72
- try {
73
- await io.publish(staged, target, publishOptions);
74
- return;
75
- } catch (error) {
76
- if (options.idempotent !== true || errnoOf(error) !== "EEXIST" || expectedBytes === undefined) {
77
- throw error;
78
- }
79
- const readExisting = io.readExisting ?? ((path, maxBytes) => readBoundedFile(path, maxBytes, { rejectSymlinks: true }));
80
- let existing;
81
- try {
82
- existing = await readExisting(target, expectedBytes.byteLength);
83
- } catch (readError) {
84
- if (isMissing(readError)) {
85
- await io.publish(staged, target, publishOptions);
86
- return;
87
- }
88
- throw error;
89
- }
90
- if (!modeMatches(existing.mode, mode) || !bytesEqual(existing.bytes, expectedBytes)) {
91
- throw error;
92
- }
93
- try {
94
- await io.unlink(staged);
95
- } catch (cleanup) {
96
- if (!isMissing(cleanup))
97
- throw new AtomicFilePublicationError2("cleanup", cleanup);
98
- }
99
- if (publishOptions.durability === "directory") {
100
- try {
101
- const syncDir = io.syncDir ?? syncDirectory;
102
- await syncDir(dirname(target));
103
- } catch (syncError) {
104
- throw new AtomicFilePublicationError2("directory-sync", syncError);
105
- }
106
- }
107
- }
108
- }
109
- async function writeAtomicFileStaged(target, stage, options, io = { open, unlink, publish: publishAtomicFile }) {
110
- assertWriteOptions(options);
111
- const mode = options.mode ?? DEFAULT_MODE;
112
- const staged = stagingPath(target);
113
- const file = await io.open(staged, "wx", mode);
114
- try {
115
- const value = await closeAfter(file, async () => {
116
- const filled = await stage.fill(file);
117
- await file.chmod(mode);
118
- if (options.durability !== "none")
119
- await file.sync();
120
- return filled;
121
- });
122
- await publishMaybeIdempotent(staged, target, mode, options, stage.expectedBytes, io);
123
- return value;
124
- } catch (error) {
125
- await io.unlink(staged).catch((cleanup) => {
126
- if (!isMissing(cleanup))
127
- stage.onCleanupError?.(cleanup);
128
- });
129
- throw error;
130
- }
131
- }
132
- async function writeAtomicFileData(target, data, options, io) {
133
- const bytes = bytesOf(data);
134
- await writeAtomicFileStaged(target, { fill: (file) => writeAllBytes(file, bytes), expectedBytes: bytes }, options, io);
135
- }
136
- var nativeSync = {
137
- open(path, flags, mode) {
138
- const descriptor = openSync(path, flags, mode);
139
- return {
140
- write: (bytes, offset, length) => writeSync(descriptor, bytes, offset, length),
141
- chmod: (bits) => fchmodSync(descriptor, bits),
142
- sync: () => fsyncSync(descriptor),
143
- close: () => closeSync(descriptor)
144
- };
145
- },
146
- unlink: unlinkSync,
147
- publish: publishAtomicFileSync
148
- };
149
- function publishMaybeIdempotentSync(staged, target, mode, options, expectedBytes, io) {
150
- const publishOptions = {
151
- replace: options.replace ?? true,
152
- durability: options.durability ?? "file"
153
- };
154
- try {
155
- io.publish(staged, target, publishOptions);
156
- return;
157
- } catch (error) {
158
- if (options.idempotent !== true || errnoOf(error) !== "EEXIST") {
159
- throw error;
160
- }
161
- const readExisting = io.readExisting ?? ((path, maxBytes) => readBoundedFileSync(path, maxBytes, { rejectSymlinks: true }));
162
- let existing;
163
- try {
164
- existing = readExisting(target, expectedBytes.byteLength);
165
- } catch (readError) {
166
- if (isMissing(readError)) {
167
- io.publish(staged, target, publishOptions);
168
- return;
169
- }
170
- throw error;
171
- }
172
- if (!modeMatches(existing.mode, mode) || !bytesEqual(existing.bytes, expectedBytes)) {
173
- throw error;
174
- }
175
- try {
176
- io.unlink(staged);
177
- } catch (cleanup) {
178
- if (!isMissing(cleanup))
179
- throw new AtomicFilePublicationError2("cleanup", cleanup);
180
- }
181
- if (publishOptions.durability === "directory") {
182
- try {
183
- const syncDir = io.syncDir ?? syncDirectorySync;
184
- syncDir(dirname(target));
185
- } catch (syncError) {
186
- throw new AtomicFilePublicationError2("directory-sync", syncError);
187
- }
188
- }
189
- }
190
- }
191
- function writeAtomicFileDataSync(target, data, options, io = nativeSync) {
192
- assertWriteOptions(options);
193
- const mode = options.mode ?? DEFAULT_MODE;
194
- const bytes = bytesOf(data);
195
- const staged = stagingPath(target);
196
- const file = io.open(staged, "wx", mode);
197
- try {
198
- closeAfterSync(() => file.close(), () => {
199
- for (let offset = 0;offset < bytes.byteLength; ) {
200
- const written = file.write(bytes, offset, bytes.byteLength - offset);
201
- if (written === 0)
202
- throw new Error("zero-byte atomic-file write");
203
- offset += written;
204
- }
205
- file.chmod(mode);
206
- if (options.durability !== "none")
207
- file.sync();
208
- });
209
- publishMaybeIdempotentSync(staged, target, mode, options, bytes, io);
210
- } catch (error) {
211
- try {
212
- io.unlink(staged);
213
- } catch {}
214
- throw error;
215
- }
216
- }
217
- function writeFileAtomicSync2(target, data, options = {}) {
218
- writeAtomicFileDataSync(target, data, options);
219
- }
220
-
221
- export { writeAllBytes, writeFileAtomic2, writeAtomicFileStaged, writeAtomicFileData, writeFileAtomicSync2 };
@@ -337,6 +337,51 @@ function waitForCommandClose(closed, timeoutMs) {
337
337
  return raceAbort(closed, deadline.signal).finally(() => deadline.cancel());
338
338
  }
339
339
 
340
+ // src/process/cleanup.ts
341
+ async function cleanupNativeCommand(input) {
342
+ const signalled = Promise.resolve().then(input.signal);
343
+ const teardown = () => input.transport?.destroy();
344
+ const destroyed = signalled.then(teardown, teardown);
345
+ const awaitRelease = async () => {
346
+ if (!input.transport)
347
+ return;
348
+ try {
349
+ await waitForCommandClose(input.transport.released, input.timeoutMs);
350
+ } catch (cause) {
351
+ throw new Error(`Command handles remained open: ${[...input.transport.pendingHandles].join(", ")}`, { cause });
352
+ }
353
+ };
354
+ const released = signalled.then(awaitRelease, () => {
355
+ return;
356
+ });
357
+ const stopped = async () => {
358
+ const failed = { kind: "error", cause: input.error };
359
+ if (!input.transport)
360
+ return failed;
361
+ await signalled.catch(() => {
362
+ return;
363
+ });
364
+ const leader = await waitForCommandClose(input.transport.leader, input.timeoutMs).catch(() => {
365
+ return;
366
+ });
367
+ return leader?.kind === "exit" ? {
368
+ kind: "stopped",
369
+ cause: input.error,
370
+ exitCode: leader.exitCode,
371
+ signal: leader.signal
372
+ } : failed;
373
+ };
374
+ const cleanup = await Promise.allSettled([
375
+ input.event ? input.settle(input.event) : stopped().then(input.settle),
376
+ destroyed,
377
+ signalled,
378
+ released
379
+ ]);
380
+ const failures = cleanup.flatMap((item) => item.status === "rejected" && item.reason !== input.error ? [item.reason] : []);
381
+ if (failures.length)
382
+ throw commandCleanupError(new AggregateError([input.error, ...failures], "Command failed and cleanup failed"));
383
+ }
384
+
340
385
  // src/process/command-lifetime.ts
341
386
  class CommandStopped extends DOMException {
342
387
  constructor() {
@@ -384,51 +429,6 @@ function createCommandLifetime(input) {
384
429
  };
385
430
  }
386
431
 
387
- // src/process/cleanup.ts
388
- async function cleanupNativeCommand(input) {
389
- const signalled = Promise.resolve().then(input.signal);
390
- const teardown = () => input.transport?.destroy();
391
- const destroyed = signalled.then(teardown, teardown);
392
- const awaitRelease = async () => {
393
- if (!input.transport)
394
- return;
395
- try {
396
- await waitForCommandClose(input.transport.released, input.timeoutMs);
397
- } catch (cause) {
398
- throw new Error(`Command handles remained open: ${[...input.transport.pendingHandles].join(", ")}`, { cause });
399
- }
400
- };
401
- const released = signalled.then(awaitRelease, () => {
402
- return;
403
- });
404
- const stopped = async () => {
405
- const failed = { kind: "error", cause: input.error };
406
- if (!input.transport)
407
- return failed;
408
- await signalled.catch(() => {
409
- return;
410
- });
411
- const leader = await waitForCommandClose(input.transport.leader, input.timeoutMs).catch(() => {
412
- return;
413
- });
414
- return leader?.kind === "exit" ? {
415
- kind: "stopped",
416
- cause: input.error,
417
- exitCode: leader.exitCode,
418
- signal: leader.signal
419
- } : failed;
420
- };
421
- const cleanup = await Promise.allSettled([
422
- input.event ? input.settle(input.event) : stopped().then(input.settle),
423
- destroyed,
424
- signalled,
425
- released
426
- ]);
427
- const failures = cleanup.flatMap((item) => item.status === "rejected" && item.reason !== input.error ? [item.reason] : []);
428
- if (failures.length)
429
- throw commandCleanupError(new AggregateError([input.error, ...failures], "Command failed and cleanup failed"));
430
- }
431
-
432
432
  // src/process/launch.ts
433
433
  import { Readable as Readable2 } from "node:stream";
434
434