@namzu/sdk 74.1.0 → 75.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/bridge/acp/server.d.ts +2 -0
  3. package/dist/bridge/acp/server.d.ts.map +1 -1
  4. package/dist/bridge/acp/server.js +9 -1
  5. package/dist/bridge/acp/server.js.map +1 -1
  6. package/dist/connector/mcp/adapter.d.ts +1 -1
  7. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  8. package/dist/connector/mcp/adapter.js +3 -2
  9. package/dist/connector/mcp/adapter.js.map +1 -1
  10. package/dist/connector/mcp/client.d.ts +4 -25
  11. package/dist/connector/mcp/client.d.ts.map +1 -1
  12. package/dist/connector/mcp/client.js +32 -32
  13. package/dist/connector/mcp/client.js.map +1 -1
  14. package/dist/provider/errors.d.ts.map +1 -1
  15. package/dist/provider/errors.js +13 -18
  16. package/dist/provider/errors.js.map +1 -1
  17. package/dist/provider/stream-request-timeout.d.ts +9 -0
  18. package/dist/provider/stream-request-timeout.d.ts.map +1 -0
  19. package/dist/provider/stream-request-timeout.js +34 -0
  20. package/dist/provider/stream-request-timeout.js.map +1 -0
  21. package/dist/public-runtime.d.ts +1 -0
  22. package/dist/public-runtime.d.ts.map +1 -1
  23. package/dist/public-runtime.js +1 -0
  24. package/dist/public-runtime.js.map +1 -1
  25. package/dist/public-tools.d.ts +1 -1
  26. package/dist/public-tools.d.ts.map +1 -1
  27. package/dist/public-tools.js +1 -1
  28. package/dist/public-tools.js.map +1 -1
  29. package/dist/runtime/query/executor.d.ts +3 -0
  30. package/dist/runtime/query/executor.d.ts.map +1 -1
  31. package/dist/runtime/query/executor.js +15 -3
  32. package/dist/runtime/query/executor.js.map +1 -1
  33. package/dist/runtime/query/file-evidence-replay.d.ts +1 -0
  34. package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
  35. package/dist/runtime/query/file-evidence-replay.js +64 -21
  36. package/dist/runtime/query/file-evidence-replay.js.map +1 -1
  37. package/dist/runtime/query/file-evidence-seed.d.ts +7 -0
  38. package/dist/runtime/query/file-evidence-seed.d.ts.map +1 -1
  39. package/dist/runtime/query/file-evidence-seed.js +12 -1
  40. package/dist/runtime/query/file-evidence-seed.js.map +1 -1
  41. package/dist/runtime/query/index.d.ts +2 -0
  42. package/dist/runtime/query/index.d.ts.map +1 -1
  43. package/dist/runtime/query/index.js +5 -2
  44. package/dist/runtime/query/index.js.map +1 -1
  45. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  46. package/dist/runtime/query/path-escalation.js +4 -3
  47. package/dist/runtime/query/path-escalation.js.map +1 -1
  48. package/dist/runtime/query/tooling.d.ts +2 -0
  49. package/dist/runtime/query/tooling.d.ts.map +1 -1
  50. package/dist/runtime/query/tooling.js +1 -0
  51. package/dist/runtime/query/tooling.js.map +1 -1
  52. package/dist/sandbox/provider/local.d.ts.map +1 -1
  53. package/dist/sandbox/provider/local.js +45 -18
  54. package/dist/sandbox/provider/local.js.map +1 -1
  55. package/dist/schedules/cron.js +1 -1
  56. package/dist/schedules/cron.js.map +1 -1
  57. package/dist/schedules/describe.js +1 -1
  58. package/dist/schedules/describe.js.map +1 -1
  59. package/dist/schedules/next-fire.d.ts +2 -2
  60. package/dist/schedules/next-fire.d.ts.map +1 -1
  61. package/dist/schedules/next-fire.js +7 -4
  62. package/dist/schedules/next-fire.js.map +1 -1
  63. package/dist/schedules/spec.d.ts.map +1 -1
  64. package/dist/schedules/spec.js +23 -7
  65. package/dist/schedules/spec.js.map +1 -1
  66. package/dist/schedules/types.d.ts +2 -0
  67. package/dist/schedules/types.d.ts.map +1 -1
  68. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  69. package/dist/store/session-index/sqlite.js +7 -3
  70. package/dist/store/session-index/sqlite.js.map +1 -1
  71. package/dist/store/session-log/core.d.ts.map +1 -1
  72. package/dist/store/session-log/core.js +88 -24
  73. package/dist/store/session-log/core.js.map +1 -1
  74. package/dist/store/session-log/disk.js +1 -1
  75. package/dist/store/session-log/disk.js.map +1 -1
  76. package/dist/tools/builtins/code-analysis.d.ts.map +1 -1
  77. package/dist/tools/builtins/code-analysis.js +4 -1
  78. package/dist/tools/builtins/code-analysis.js.map +1 -1
  79. package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
  80. package/dist/tools/builtins/edit-apply.js +24 -10
  81. package/dist/tools/builtins/edit-apply.js.map +1 -1
  82. package/dist/tools/builtins/edit.d.ts.map +1 -1
  83. package/dist/tools/builtins/edit.js +31 -15
  84. package/dist/tools/builtins/edit.js.map +1 -1
  85. package/dist/tools/builtins/file-text.d.ts +3 -0
  86. package/dist/tools/builtins/file-text.d.ts.map +1 -0
  87. package/dist/tools/builtins/file-text.js +14 -0
  88. package/dist/tools/builtins/file-text.js.map +1 -0
  89. package/dist/tools/builtins/glob.d.ts.map +1 -1
  90. package/dist/tools/builtins/glob.js +7 -2
  91. package/dist/tools/builtins/glob.js.map +1 -1
  92. package/dist/tools/builtins/grep.d.ts.map +1 -1
  93. package/dist/tools/builtins/grep.js +8 -5
  94. package/dist/tools/builtins/grep.js.map +1 -1
  95. package/dist/tools/builtins/ls.d.ts.map +1 -1
  96. package/dist/tools/builtins/ls.js +2 -1
  97. package/dist/tools/builtins/ls.js.map +1 -1
  98. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -1
  99. package/dist/tools/builtins/notebook-edit.js +19 -10
  100. package/dist/tools/builtins/notebook-edit.js.map +1 -1
  101. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  102. package/dist/tools/builtins/read-file.js +48 -24
  103. package/dist/tools/builtins/read-file.js.map +1 -1
  104. package/dist/tools/builtins/read-regular-file.d.ts +5 -0
  105. package/dist/tools/builtins/read-regular-file.d.ts.map +1 -0
  106. package/dist/tools/builtins/read-regular-file.js +23 -0
  107. package/dist/tools/builtins/read-regular-file.js.map +1 -0
  108. package/dist/tools/builtins/search-support.d.ts +2 -0
  109. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  110. package/dist/tools/builtins/search-support.js +14 -0
  111. package/dist/tools/builtins/search-support.js.map +1 -1
  112. package/dist/tools/builtins/stale-before-review.d.ts.map +1 -1
  113. package/dist/tools/builtins/stale-before-review.js +8 -5
  114. package/dist/tools/builtins/stale-before-review.js.map +1 -1
  115. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  116. package/dist/tools/builtins/write-file.js +17 -13
  117. package/dist/tools/builtins/write-file.js.map +1 -1
  118. package/dist/tools/paths.d.ts +9 -0
  119. package/dist/tools/paths.d.ts.map +1 -1
  120. package/dist/tools/paths.js +39 -9
  121. package/dist/tools/paths.js.map +1 -1
  122. package/dist/tools/posix-path.d.ts +2 -14
  123. package/dist/tools/posix-path.d.ts.map +1 -1
  124. package/dist/tools/posix-path.js +7 -0
  125. package/dist/tools/posix-path.js.map +1 -1
  126. package/dist/types/code-analysis/index.d.ts +1 -1
  127. package/dist/types/code-analysis/index.d.ts.map +1 -1
  128. package/dist/types/provider/errors.d.ts.map +1 -1
  129. package/dist/types/provider/errors.js +3 -5
  130. package/dist/types/provider/errors.js.map +1 -1
  131. package/dist/types/tool/index.d.ts +2 -0
  132. package/dist/types/tool/index.d.ts.map +1 -1
  133. package/dist/types/tool/index.js.map +1 -1
  134. package/package.json +1 -1
  135. package/src/bridge/acp/server.ts +16 -7
  136. package/src/connector/mcp/adapter.ts +4 -3
  137. package/src/connector/mcp/client.ts +33 -32
  138. package/src/provider/errors.ts +12 -19
  139. package/src/provider/stream-request-timeout.ts +34 -0
  140. package/src/public-runtime.ts +1 -0
  141. package/src/public-tools.ts +1 -0
  142. package/src/runtime/query/executor.ts +29 -3
  143. package/src/runtime/query/file-evidence-replay.ts +73 -19
  144. package/src/runtime/query/file-evidence-seed.ts +16 -0
  145. package/src/runtime/query/index.ts +9 -1
  146. package/src/runtime/query/path-escalation.ts +4 -3
  147. package/src/runtime/query/tooling.ts +3 -0
  148. package/src/sandbox/provider/local.ts +53 -25
  149. package/src/schedules/cron.ts +1 -1
  150. package/src/schedules/describe.ts +1 -1
  151. package/src/schedules/next-fire.ts +7 -4
  152. package/src/schedules/spec.ts +36 -7
  153. package/src/schedules/types.ts +2 -0
  154. package/src/store/session-index/sqlite.ts +8 -4
  155. package/src/store/session-log/core.ts +96 -25
  156. package/src/store/session-log/disk.ts +1 -1
  157. package/src/tools/builtins/code-analysis.ts +6 -1
  158. package/src/tools/builtins/edit-apply.ts +25 -10
  159. package/src/tools/builtins/edit.ts +31 -15
  160. package/src/tools/builtins/file-text.ts +14 -0
  161. package/src/tools/builtins/glob.ts +6 -1
  162. package/src/tools/builtins/grep.ts +7 -5
  163. package/src/tools/builtins/ls.ts +2 -1
  164. package/src/tools/builtins/notebook-edit.ts +18 -11
  165. package/src/tools/builtins/read-file.ts +52 -27
  166. package/src/tools/builtins/read-regular-file.ts +25 -0
  167. package/src/tools/builtins/search-support.ts +13 -0
  168. package/src/tools/builtins/stale-before-review.ts +8 -6
  169. package/src/tools/builtins/write-file.ts +18 -12
  170. package/src/tools/paths.ts +49 -7
  171. package/src/tools/posix-path.ts +9 -0
  172. package/src/types/code-analysis/index.ts +1 -1
  173. package/src/types/provider/errors.ts +3 -5
  174. package/src/types/tool/index.ts +2 -0
@@ -6,6 +6,7 @@ import { ReadFileTool } from '../../tools/builtins/read-file.js'
6
6
  import {
7
7
  LINE_NUMBER_WIDTH,
8
8
  type ReadWindowRequest,
9
+ linePrefix,
9
10
  renderNumberedRead,
10
11
  resolveReadWindow,
11
12
  } from '../../tools/builtins/read-render.js'
@@ -498,6 +499,29 @@ export function replayObservationLedger(
498
499
  keyOf: FileKeyResolver,
499
500
  attributions: PathAttributions = createPathAttributions(),
500
501
  ): LedgerReplayReport {
502
+ const { claims, budget } = replayClaims(messages, keyOf, attributions, false)
503
+ return commit(tracker, claims, budget)
504
+ }
505
+
506
+ export function replayComparisonClaims(
507
+ messages: readonly Message[],
508
+ keyOf: FileKeyResolver,
509
+ attributions: PathAttributions,
510
+ ): ReadonlyMap<string, string> {
511
+ const { claims } = replayClaims(messages, keyOf, attributions, true)
512
+ const bodies = new Map<string, string>()
513
+ for (const [key, claim] of claims) {
514
+ if (claim.kind === 'content') bodies.set(key, claim.body)
515
+ }
516
+ return bodies
517
+ }
518
+
519
+ function replayClaims(
520
+ messages: readonly Message[],
521
+ keyOf: FileKeyResolver,
522
+ attributions: PathAttributions,
523
+ compareReads: boolean,
524
+ ): { claims: Map<string, Claim>; budget: ReplayBudget } {
501
525
  const history = indexVisibleHistory(messages, keyOf)
502
526
  const budget = createReplayBudget()
503
527
  const claims = new Map<string, Claim>()
@@ -517,14 +541,15 @@ export function replayObservationLedger(
517
541
  // be the one showing a body this walk is holding to be something else,
518
542
  // and skipping the read past would keep a claim that very observation
519
543
  // withdrew. Both get the same answer.
520
- if (receipt === null) return commit(tracker, new Map(), budget)
544
+ if (receipt === null) return { claims: new Map(), budget }
521
545
  const answered = receipt !== undefined && receipt.role === 'tool' && !receipt.isError
522
546
  if (name === 'read') {
523
547
  // A read that never came back, or came back refused, saw no body: it
524
548
  // can neither confirm what this pass holds nor contradict it. And a
525
549
  // read changes no file, so a claim left standing across one is still a
526
550
  // claim about the same bytes.
527
- if (answered) observeRead(history, call, claims, withBody, budget)
551
+ if (answered) observeRead(history, call, claims, withBody, budget, compareReads)
552
+ limitBodies(claims, withBody)
528
553
  continue
529
554
  }
530
555
  // One id claimed by two calls hides which of them ran. On a path this
@@ -532,7 +557,7 @@ export function replayObservationLedger(
532
557
  // have replaced a body claimed somewhere else in this walk, and there
533
558
  // is no way to tell where — so the pass establishes nothing at all
534
559
  // rather than carry a body something unseen may have moved past.
535
- if (history.calls.get(call.id) === null) return commit(tracker, new Map(), budget)
560
+ if (history.calls.get(call.id) === null) return { claims: new Map(), budget }
536
561
  // Attribution before outcome, for every mutation the walk reaches. A call
537
562
  // the transcript never answered — the unknown-outcome result the kernel's
538
563
  // own repair writes for one included — is precisely the call whose effect
@@ -546,28 +571,26 @@ export function replayObservationLedger(
546
571
  // is still the one thing that stops the pass, because then there is no
547
572
  // path to withdraw.
548
573
  const key = mutatedKey(history, call, attributions)
549
- if (key === undefined) return commit(tracker, new Map(), budget)
574
+ if (key === undefined) return { claims: new Map(), budget }
550
575
  const claim: Claim = answered
551
576
  ? mutate(history, call, name, key, claims.get(key), budget)
552
577
  : { kind: 'seen' }
553
578
  claims.set(key, claim)
554
579
  withBody.delete(key)
555
580
  if (claim.kind === 'content') withBody.add(key)
556
- // Oldest body first, matching what the projection keeps. An evicted
557
- // path is one this pass stops vouching for: it was mutated here, and
558
- // what it holds is past what the pass can carry, so it reaches the
559
- // ledger as the nothing every unrebuilt path reaches it as.
560
- if (withBody.size > MAX_WITNESSED_PATHS) {
561
- const oldest = withBody.values().next().value as string
562
- withBody.delete(oldest)
563
- // Setting an existing key leaves it where it is, so the order the
564
- // ledger is written in stays the order the calls arrived in.
565
- claims.set(oldest, { kind: 'seen' })
566
- }
581
+ limitBodies(claims, withBody)
567
582
  }
568
583
  }
569
584
 
570
- return commit(tracker, claims, budget)
585
+ return { claims, budget }
586
+ }
587
+
588
+ /** Evict the oldest body while retaining its path attribution. */
589
+ function limitBodies(claims: Map<string, Claim>, withBody: Set<string>): void {
590
+ if (withBody.size <= MAX_WITNESSED_PATHS) return
591
+ const oldest = withBody.values().next().value as string
592
+ withBody.delete(oldest)
593
+ claims.set(oldest, { kind: 'seen' })
571
594
  }
572
595
 
573
596
  /** Apply a walk's surviving claims to the ledger, in the order they were made. */
@@ -673,28 +696,40 @@ function observeRead(
673
696
  claims: Map<string, Claim>,
674
697
  withBody: Set<string>,
675
698
  budget: ReplayBudget,
699
+ compareReads: boolean,
676
700
  ): void {
677
701
  const read = readWindow(history, call)
678
702
  if (!read) return
679
703
  const claim = claims.get(read.key)
680
- if (!claim || claim.kind !== 'content') return
704
+ if (!compareReads && (!claim || claim.kind !== 'content')) return
681
705
  const shown = history.results.get(call.id)?.content
682
706
  if (visibleCall(history, call.id, 'read') && typeof shown === 'string') {
683
707
  // A whole-file rendering is the body plus a number on every line, so one
684
708
  // shorter than the body it would render cannot be equal to it. The cheap
685
709
  // half of the comparison, taken before anything is measured.
686
710
  const units =
687
- shown.length < claim.body.length ? undefined : wholeFileRenderUnits(claim.body, read.window)
711
+ claim?.kind === 'content' && shown.length >= claim.body.length
712
+ ? wholeFileRenderUnits(claim.body, read.window)
713
+ : undefined
688
714
  // The rendering is content this pass materialises, so it is charged like
689
715
  // every other body — and charged for what it will actually come to,
690
716
  // worked out from the body and the window while the string does not exist
691
717
  // yet. Charging the RECEIPT's length was charging one number and building
692
718
  // another: a receipt that had been rewritten short could have the pass
693
719
  // build a rendering the ceiling had never been asked about.
694
- if (units !== undefined && spend(budget, units)) {
720
+ if (claim?.kind === 'content' && units !== undefined && spend(budget, units)) {
695
721
  const rendered = renderNumberedRead(claim.body, read.window)
696
722
  if (!rendered.partial && rendered.output === shown) return
697
723
  }
724
+ if (compareReads && spend(budget, shown.length)) {
725
+ const body = comparisonReadBody(shown, read.window)
726
+ if (body !== undefined) {
727
+ claims.set(read.key, { kind: 'content', body, steps: [] })
728
+ withBody.delete(read.key)
729
+ withBody.add(read.key)
730
+ return
731
+ }
732
+ }
698
733
  }
699
734
  claims.set(read.key, { kind: 'seen' })
700
735
  // Off the held list as well as out of the claim. A withdrawn path is one
@@ -705,6 +740,25 @@ function observeRead(
705
740
  withBody.delete(read.key)
706
741
  }
707
742
 
743
+ /**
744
+ * Recover a comparison baseline from a complete, unmodified numbered receipt.
745
+ * Numbered reads omit the final newline. This approximation is only used to
746
+ * request a fresh read and must never establish a mutation witness.
747
+ */
748
+ function comparisonReadBody(shown: string, window: ReadWindowRequest): string | undefined {
749
+ if (shown === 'Warning: the file exists but is empty.') return ''
750
+ const rows = shown.split('\n')
751
+ const lines: string[] = []
752
+ for (const [index, row] of rows.entries()) {
753
+ const prefix = linePrefix(index + 1)
754
+ if (!row.startsWith(prefix)) return undefined
755
+ lines.push(row.slice(prefix.length))
756
+ }
757
+ const body = `${lines.join('\n')}\n`
758
+ const rendered = renderNumberedRead(body, window)
759
+ return !rendered.partial && rendered.output === shown ? body : undefined
760
+ }
761
+
708
762
  /**
709
763
  * What `read` would return for this whole body, in UTF-16 units, without
710
764
  * building it — and `undefined` for a window that would leave a line out.
@@ -7,6 +7,7 @@ import {
7
7
  type PathAttributions,
8
8
  collectObservedPaths,
9
9
  createPathAttributions,
10
+ replayComparisonClaims,
10
11
  replayObservationLedger,
11
12
  } from './file-evidence-replay.js'
12
13
 
@@ -92,6 +93,21 @@ export async function seedObservationLedger(
92
93
  return keyOf ? replayObservationLedger(messages, tracker, keyOf, attributions) : NOTHING
93
94
  }
94
95
 
96
+ /**
97
+ * Recover bounded file bodies for change notices when a conversation is reopened.
98
+ * Includes complete numbered reads and edits replayed over them. Bodies recovered
99
+ * from reads have an ambiguous final newline and are suitable only for comparison.
100
+ * No file content is read from disk and no mutation witness is established.
101
+ */
102
+ export async function replayFileComparisonBodies(
103
+ messages: readonly Message[],
104
+ context: ObservationSeedContext,
105
+ ): Promise<ReadonlyMap<string, string>> {
106
+ const attributions = createPathAttributions()
107
+ const keyOf = await resolveObservedFileKeys(messages, context, attributions)
108
+ return keyOf ? replayComparisonClaims(messages, keyOf, attributions) : new Map()
109
+ }
110
+
95
111
  /**
96
112
  * The tools' key for every path this history names, or `undefined` when the
97
113
  * pass should not run at all.
@@ -46,6 +46,7 @@ import { createStructuredOutputTool } from '../../tools/builtins/structuredOutpu
46
46
  import {
47
47
  HAND_BACK_GUIDANCE,
48
48
  HAND_BACK_GUIDANCE_CONTRIBUTION_ID,
49
+ HAND_BACK_TOOL_NAME,
49
50
  buildHandBackTool,
50
51
  } from '../../tools/hand-back/index.js'
51
52
  import { buildTaskTools } from '../../tools/task/index.js'
@@ -620,6 +621,8 @@ export interface QueryParams {
620
621
  * `ToolContext.additionalDirectories`.
621
622
  */
622
623
  additionalDirectories?: readonly string[]
624
+ /** Host-owned absolute file paths available to read, write and edit, including in a sandbox. */
625
+ allowedFiles?: readonly string[]
623
626
  /**
624
627
  * What a file tool's path outside `workingDirectory` and
625
628
  * `additionalDirectories` becomes, on a turn with no sandbox.
@@ -1715,6 +1718,7 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
1715
1718
  ...(params.additionalDirectories?.length
1716
1719
  ? { additionalDirectories: params.additionalDirectories }
1717
1720
  : {}),
1721
+ ...(params.allowedFiles?.length ? { allowedFiles: params.allowedFiles } : {}),
1718
1722
  ...(scratchpadDirectory ? { scratchpadDirectory } : {}),
1719
1723
  ...(params.outsideRootAccess ? { outsideRootAccess: params.outsideRootAccess } : {}),
1720
1724
  ...(params.outsideRootRefusal ? { outsideRootRefusal: params.outsideRootRefusal } : {}),
@@ -1930,7 +1934,11 @@ export async function* query(params: QueryParams): AsyncGenerator<SessionEvent,
1930
1934
  // The turn's own registry when the host passed none, so a hook's
1931
1935
  // annotation has somewhere to land.
1932
1936
  const promptContributions = params.promptContributions ?? new PromptContributionRegistry()
1933
- if (turnConfig.handBack === true) {
1937
+ if (
1938
+ turnConfig.handBack === true &&
1939
+ runtimeToolOverrides?.[HAND_BACK_TOOL_NAME] !== 'disabled' &&
1940
+ (effectiveAllowedTools?.includes(HAND_BACK_TOOL_NAME) ?? true)
1941
+ ) {
1934
1942
  promptContributions.replace({
1935
1943
  id: HAND_BACK_GUIDANCE_CONTRIBUTION_ID,
1936
1944
  placement: 'static',
@@ -31,7 +31,7 @@ import {
31
31
  topLevelEntryChange,
32
32
  } from '../../authorization/top-level-entries.js'
33
33
  import { resolveNamzuHome } from '../../session/home.js'
34
- import { canonicalize, pathOutsideRoots } from '../../tools/paths.js'
34
+ import { canonicalize, expandHomePath, pathOutsideRoots } from '../../tools/paths.js'
35
35
 
36
36
  /** What the escalation records carry. */
37
37
  export interface PathEscalations {
@@ -274,8 +274,9 @@ export async function declaredWriteEscalation(
274
274
  ): Promise<string | undefined> {
275
275
  const [first] = roots
276
276
  if (first === undefined || value === '') return undefined
277
- const absolute = resolve(resolve(first), value)
278
- if (await isProtectedWrite(value, absolute, roots)) return absolute
277
+ const spelled = expandHomePath(value)
278
+ const absolute = resolve(first, spelled)
279
+ if (await isProtectedWrite(spelled, absolute, roots)) return absolute
279
280
  return topLevel ? topLevelEntryChange(absolute, 'write', homedir()) : undefined
280
281
  }
281
282
 
@@ -33,6 +33,8 @@ export interface ToolingBootstrapConfig {
33
33
  workingDirectory: string
34
34
  /** See `QueryParams.additionalDirectories`. */
35
35
  additionalDirectories?: readonly string[]
36
+ /** Host-owned absolute file paths available to read, write and edit, including in a sandbox. */
37
+ allowedFiles?: readonly string[]
36
38
  /** See `ToolExecutorConfig.scratchpadDirectory`. */
37
39
  scratchpadDirectory?: string
38
40
  /** See `QueryParams.outsideRootAccess`. */
@@ -119,6 +121,7 @@ export class ToolingBootstrap {
119
121
  ...(config.additionalDirectories?.length
120
122
  ? { additionalDirectories: config.additionalDirectories }
121
123
  : {}),
124
+ ...(config.allowedFiles?.length ? { allowedFiles: config.allowedFiles } : {}),
122
125
  ...(config.scratchpadDirectory ? { scratchpadDirectory: config.scratchpadDirectory } : {}),
123
126
  ...(config.outsideRootAccess ? { outsideRootAccess: config.outsideRootAccess } : {}),
124
127
  ...(config.outsideRootRefusal ? { outsideRootRefusal: config.outsideRootRefusal } : {}),
@@ -664,6 +664,7 @@ class LocalSandbox implements Sandbox {
664
664
  environment: SandboxEnvironment,
665
665
  private readonly wrapperCommand: string | undefined,
666
666
  private readonly removeRootOnDestroy: boolean,
667
+ private readonly seatbeltTempDir: string | undefined,
667
668
  config: SandboxCreateConfig,
668
669
  log: Logger,
669
670
  ) {
@@ -706,7 +707,7 @@ class LocalSandbox implements Sandbox {
706
707
  this._status = 'busy'
707
708
  const startTime = Date.now()
708
709
 
709
- const env = buildSafeEnv(this.config.env, opts?.env)
710
+ const env = this.buildSpawnEnv(opts?.env)
710
711
  const timeout = opts?.timeout ?? this.config.timeoutMs ?? SANDBOX_DEFAULT_TIMEOUT_MS
711
712
 
712
713
  const cwd = opts?.cwd ? await resolveWithinAnyReal(this.roots, opts.cwd) : this.rootDir
@@ -871,9 +872,12 @@ class LocalSandbox implements Sandbox {
871
872
  // A generated temp root belongs to this allocation. A working-directory
872
873
  // root belongs to the caller. Conflating those lifetimes turns normal run
873
874
  // teardown into recursive deletion of the project the turn just edited.
874
- if (this.removeRootOnDestroy) {
875
- await rm(this.rootDir, { recursive: true, force: true })
876
- }
875
+ await Promise.all([
876
+ this.removeRootOnDestroy ? rm(this.rootDir, { recursive: true, force: true }) : undefined,
877
+ this.seatbeltTempDir === undefined
878
+ ? undefined
879
+ : rm(this.seatbeltTempDir, { recursive: true, force: true }),
880
+ ])
877
881
 
878
882
  this.log.info('Sandbox destroyed', { 'namzu.sandbox.id': this.id })
879
883
  }
@@ -896,7 +900,7 @@ class LocalSandbox implements Sandbox {
896
900
  const { spawnCommand, spawnArgs, bwrapInfoFd, bwrapBlockFd } = this.buildSpawnArgs(command, [
897
901
  ...args,
898
902
  ])
899
- const env = buildSafeEnv(this.config.env, opts?.env)
903
+ const env = this.buildSpawnEnv(opts?.env)
900
904
  const child = spawn(spawnCommand, spawnArgs, {
901
905
  cwd,
902
906
  env,
@@ -943,6 +947,13 @@ class LocalSandbox implements Sandbox {
943
947
  }
944
948
  }
945
949
 
950
+ private buildSpawnEnv(overrides?: Record<string, string>): Record<string, string> {
951
+ const env = buildSafeEnv(this.config.env, overrides)
952
+ const tempDir = this.environment === 'linux-bwrap' ? '/tmp' : this.seatbeltTempDir
953
+ if (tempDir !== undefined) env.TMPDIR ??= tempDir
954
+ return env
955
+ }
956
+
946
957
  private buildSpawnArgs(
947
958
  command: string,
948
959
  args: string[],
@@ -952,15 +963,17 @@ class LocalSandbox implements Sandbox {
952
963
  bwrapInfoFd?: number
953
964
  bwrapBlockFd?: number
954
965
  } {
966
+ const additionalDirectories =
967
+ this.seatbeltTempDir === undefined
968
+ ? this.additionalDirectories
969
+ : [...this.additionalDirectories, this.seatbeltTempDir]
955
970
  const built = buildLimitedSpawn({
956
971
  environment: this.environment,
957
972
  ...(this.wrapperCommand !== undefined ? { wrapperCommand: this.wrapperCommand } : {}),
958
973
  command,
959
974
  args,
960
975
  rootDir: this.rootDir,
961
- ...(this.additionalDirectories.length > 0
962
- ? { additionalDirectories: this.additionalDirectories }
963
- : {}),
976
+ additionalDirectories,
964
977
  ...(this.config.memoryLimitMb !== undefined
965
978
  ? { memoryLimitMb: this.config.memoryLimitMb }
966
979
  : {}),
@@ -1278,24 +1291,39 @@ export class LocalSandboxProvider implements SandboxProvider {
1278
1291
  rootDir = canonicalizePath(rawDir)
1279
1292
  removeRootOnDestroy = true
1280
1293
  }
1281
- if (config?.signal?.aborted) {
1282
- if (removeRootOnDestroy) await rm(rootDir, { recursive: true, force: true })
1283
- throw config.signal.reason
1284
- }
1294
+ let seatbeltTempDir: string | undefined
1295
+ try {
1296
+ config?.signal?.throwIfAborted()
1297
+ if (this.environment === 'macos-seatbelt') {
1298
+ // Keep scratch outside caller-owned workspaces, which may be read-only
1299
+ // on the host and outlive this sandbox.
1300
+ seatbeltTempDir = canonicalizePath(await createTempDir('namzu-seatbelt-'))
1301
+ }
1302
+ config?.signal?.throwIfAborted()
1285
1303
 
1286
- this.log.info('Creating sandbox', {
1287
- 'namzu.sandbox.id': id,
1288
- 'namzu.sandbox.root_dir': rootDir,
1289
- })
1304
+ this.log.info('Creating sandbox', {
1305
+ 'namzu.sandbox.id': id,
1306
+ 'namzu.sandbox.root_dir': rootDir,
1307
+ })
1290
1308
 
1291
- return new LocalSandbox(
1292
- id,
1293
- rootDir,
1294
- this.environment,
1295
- this.wrapperCommand,
1296
- removeRootOnDestroy,
1297
- config ?? {},
1298
- this.log,
1299
- )
1309
+ return new LocalSandbox(
1310
+ id,
1311
+ rootDir,
1312
+ this.environment,
1313
+ this.wrapperCommand,
1314
+ removeRootOnDestroy,
1315
+ seatbeltTempDir,
1316
+ config ?? {},
1317
+ this.log,
1318
+ )
1319
+ } catch (error) {
1320
+ await Promise.all([
1321
+ removeRootOnDestroy ? rm(rootDir, { recursive: true, force: true }) : undefined,
1322
+ seatbeltTempDir === undefined
1323
+ ? undefined
1324
+ : rm(seatbeltTempDir, { recursive: true, force: true }),
1325
+ ])
1326
+ throw error
1327
+ }
1300
1328
  }
1301
1329
  }
@@ -129,7 +129,7 @@ function parseField(text: string, field: FieldSpec): number[] {
129
129
  } else {
130
130
  lo = parseValue(rangeText, field)
131
131
  // `5/15` means "from 5, every 15", as in Vixie cron.
132
- hi = stepText !== undefined ? (field.label === 'day of week' ? 6 : field.max) : lo
132
+ hi = stepText !== undefined ? field.max : lo
133
133
  }
134
134
  for (let v = lo; v <= hi; v += step) values.add(v)
135
135
  }
@@ -119,7 +119,7 @@ export function describeSchedule(
119
119
  spec: ScheduleSpec,
120
120
  options: DescribeScheduleOptions = {},
121
121
  ): string {
122
- const tz = options.tz ?? 'UTC'
122
+ const tz = options.tz ?? (spec.kind === 'at' ? spec.tz : undefined) ?? 'UTC'
123
123
  switch (spec.kind) {
124
124
  case 'at':
125
125
  return `once at ${formatWall(Date.parse(spec.at), tz)} (${tz})`
@@ -107,8 +107,8 @@ function validEvery(spec: { everyMs: number; anchorAt: string }): number {
107
107
 
108
108
  /**
109
109
  * The first instant strictly after `afterExclusive` at which `spec` fires,
110
- * or `null` when there is none (a past `at`, or a cron expression with no
111
- * occurrence in the next five years).
110
+ * or `null` when there is none within the supported date range (or, for cron,
111
+ * within the next five years).
112
112
  */
113
113
  export function nextFireTime(spec: ScheduleSpec, afterExclusive: Date): Date | null {
114
114
  const after = afterExclusive.getTime()
@@ -123,7 +123,8 @@ export function nextFireTime(spec: ScheduleSpec, afterExclusive: Date): Date | n
123
123
  case 'every': {
124
124
  const anchor = validEvery(spec)
125
125
  const k = after < anchor ? 1 : Math.floor((after - anchor) / spec.everyMs) + 1
126
- return new Date(anchor + Math.max(1, k) * spec.everyMs)
126
+ const next = new Date(anchor + Math.max(1, k) * spec.everyMs)
127
+ return Number.isFinite(next.getTime()) ? next : null
127
128
  }
128
129
  case 'cron': {
129
130
  const expr = cronOf(spec.expr)
@@ -259,7 +260,9 @@ export function assertSpecFires(spec: ScheduleSpec, now: Date): void {
259
260
  throw new ScheduleValidationError(
260
261
  spec.kind === 'at'
261
262
  ? `${spec.at} is in the past`
262
- : `"${spec.kind === 'cron' ? spec.expr : ''}" never fires in the next five years`,
263
+ : spec.kind === 'every'
264
+ ? 'the next interval is outside the supported date range'
265
+ : `"${spec.expr}" never fires in the next five years`,
263
266
  spec.kind === 'cron' ? spec.expr : spec.kind === 'at' ? spec.at : undefined,
264
267
  )
265
268
  }
@@ -71,6 +71,9 @@ function formatInterval(ms: number): string {
71
71
 
72
72
  function everySpec(text: string, now: Date): ScheduleSpec {
73
73
  const ms = parseDuration(text)
74
+ if (!Number.isSafeInteger(ms)) {
75
+ throw new ScheduleValidationError(`every ${text} is outside the supported date range`, text)
76
+ }
74
77
  if (ms < MINUTE) {
75
78
  throw new ScheduleValidationError(
76
79
  `every ${text} is shorter than the minimum interval; the nearest allowed is every 1m`,
@@ -89,6 +92,22 @@ function everySpec(text: string, now: Date): ScheduleSpec {
89
92
  return { kind: 'every', everyMs: ms, anchorAt: anchor.toISOString() }
90
93
  }
91
94
 
95
+ function validateCivilTime(
96
+ wall: number,
97
+ y: number,
98
+ mo: number,
99
+ d: number,
100
+ h: number,
101
+ mi: number,
102
+ s: number,
103
+ token: string,
104
+ ): void {
105
+ const c = civil(wall)
106
+ if (c.year !== y || c.month !== mo || c.day !== d || h > 23 || mi > 59 || s > 59) {
107
+ throw new ScheduleValidationError(`"${token}" is not a real date and time`, token)
108
+ }
109
+ }
110
+
92
111
  /** Resolve a local `YYYY-MM-DD HH:MM` in `tz` to one instant (the earlier of two). */
93
112
  function localToInstant(
94
113
  y: number,
@@ -100,10 +119,7 @@ function localToInstant(
100
119
  token: string,
101
120
  ): number {
102
121
  const wall = Date.UTC(y, mo - 1, d, h, mi)
103
- const c = civil(wall)
104
- if (c.year !== y || c.month !== mo || c.day !== d || h > 23 || mi > 59) {
105
- throw new ScheduleValidationError(`"${token}" is not a real date and time`, token)
106
- }
122
+ validateCivilTime(wall, y, mo, d, h, mi, 0, token)
107
123
  const instants = instantsForWall(wall, tz)
108
124
  if (instants.length === 0) {
109
125
  throw new ScheduleValidationError(
@@ -116,8 +132,18 @@ function localToInstant(
116
132
 
117
133
  function atSpec(text: string, now: Date, tz: string): ScheduleSpec {
118
134
  const t = text.trim()
119
- // An instant with its own offset: taken as written.
120
- if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/i.test(t)) {
135
+ const offset =
136
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})$/i.exec(
137
+ t,
138
+ )
139
+ if (offset) {
140
+ const [, year, month, day, hour, minute, second = '0'] = offset
141
+ const y = Number(year)
142
+ const mo = Number(month)
143
+ const d = Number(day)
144
+ // setUTCFullYear keeps years 0000–0099 literal.
145
+ const wall = new Date(0).setUTCFullYear(y, mo - 1, d)
146
+ validateCivilTime(wall, y, mo, d, Number(hour), Number(minute), Number(second), t)
121
147
  const at = Date.parse(t)
122
148
  if (!Number.isFinite(at)) throw new ScheduleValidationError(`"${t}" is not a date`, t)
123
149
  return { kind: 'at', at: new Date(at).toISOString() }
@@ -181,7 +207,10 @@ export function parseScheduleSpec(input: string, options: ParseScheduleOptions =
181
207
  text.slice(3).trim(),
182
208
  )
183
209
  }
184
- spec = { kind: 'at', at: new Date(now.getTime() + ms).toISOString() }
210
+ const at = new Date(now.getTime() + ms)
211
+ if (!Number.isFinite(at.getTime()))
212
+ throw new ScheduleValidationError(`${text} is outside the supported date range`, text)
213
+ spec = { kind: 'at', at: at.toISOString() }
185
214
  } else if (lower.startsWith('at ')) {
186
215
  spec = atSpec(text.slice(3), now, tz)
187
216
  } else if (/^\d{4}-\d{2}-\d{2}T/i.test(text)) {
@@ -12,6 +12,8 @@
12
12
  /** A single instant (ISO-8601 UTC). */
13
13
  export interface ScheduleAtSpec {
14
14
  readonly kind: 'at'
15
+ /** Display zone for a one-time job, when saved by the caller. */
16
+ readonly tz?: string
15
17
  readonly at: string
16
18
  }
17
19
 
@@ -943,13 +943,17 @@ export class SqliteSessionIndex extends SessionIndexBase {
943
943
 
944
944
  async listChildren(sessionId: SessionId): Promise<ChildSessionSummary[]> {
945
945
  await this.settledFor(sessionId)
946
- return this.#all(
946
+ const rows = this.#all(
947
947
  'SELECT * FROM children WHERE session_id = ? ORDER BY spawned_at, child_id',
948
948
  sessionId,
949
- ).map((row) => {
949
+ )
950
+ const children: ChildSessionSummary[] = []
951
+ for (const row of rows) {
950
952
  const child = childRow(row)
951
- return childView(child, this.readSession(child.childId))
952
- })
953
+ await this.settledFor(child.childId)
954
+ children.push(childView(child, this.readSession(child.childId)))
955
+ }
956
+ return children
953
957
  }
954
958
 
955
959
  async listPendingDecisions(