@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366

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 (212) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +88 -14
  16. package/dist/bridge/bridge.service.js +406 -345
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +62 -4
  83. package/dist/runtime/host-runtime-lease.js +235 -168
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  92. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  93. package/dist/runtime/runner-settings.d.ts +104 -0
  94. package/dist/runtime/runner-settings.js +236 -0
  95. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  96. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  97. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  98. package/dist/sandbox/host-capacity-broker.js +27 -6
  99. package/dist/sandbox/managed-branch.d.ts +13 -0
  100. package/dist/sandbox/managed-branch.js +90 -0
  101. package/dist/sandbox/provider-auth/codex.js +11 -11
  102. package/dist/sandbox/runtime.js +2 -6
  103. package/dist/session/architect-waits.d.ts +2 -0
  104. package/dist/session/architect-waits.js +138 -0
  105. package/dist/session/managed-attempt-tools.d.ts +0 -7
  106. package/dist/session/managed-attempt-tools.js +58 -91
  107. package/dist/session/managed-build-coordinator.d.ts +16 -0
  108. package/dist/session/managed-build-coordinator.js +10 -0
  109. package/dist/session/managed-build-receipt.d.ts +5 -0
  110. package/dist/session/managed-build-receipt.js +8 -3
  111. package/dist/session/managed-command-host-load.d.ts +2 -0
  112. package/dist/session/managed-command-host-load.js +2 -1
  113. package/dist/session/phase-completion.artifacts.js +2 -1
  114. package/dist/session/phase-completion.d.ts +8 -0
  115. package/dist/session/phase-completion.js +1 -0
  116. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  117. package/dist/session/phase-completion.mcp-args.js +156 -0
  118. package/dist/session/phase-completion.runtime.d.ts +0 -8
  119. package/dist/session/phase-completion.runtime.js +43 -197
  120. package/dist/session/phase-completion.schemas.js +25 -23
  121. package/dist/session/phase-completion.validation.js +3 -1
  122. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  123. package/dist/session/pre-publication-native-postgres.js +111 -0
  124. package/dist/session/pre-publication-pass.d.ts +61 -0
  125. package/dist/session/pre-publication-pass.js +148 -0
  126. package/dist/session/pre-publication-process.js +10 -10
  127. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  128. package/dist/session/pre-publication-step-execution.js +6 -5
  129. package/dist/session/pre-publication-validation.d.ts +30 -14
  130. package/dist/session/pre-publication-validation.js +207 -134
  131. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  132. package/dist/session/provider-cli/claude-background-work.js +181 -0
  133. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  134. package/dist/session/provider-cli/host-build-lock.js +30 -0
  135. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  136. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  138. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  140. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  141. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  142. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  143. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  145. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  146. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  147. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  148. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  149. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  151. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  153. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  155. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  156. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  157. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  158. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  159. package/dist/session/provider-cli/provider-output-state.js +6 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  161. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  162. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  163. package/dist/session/qa-sidecar-validation.js +28 -0
  164. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  165. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  166. package/dist/session/session-redaction.js +31 -181
  167. package/dist/session/session.base.d.ts +6 -1
  168. package/dist/session/session.service.d.ts +9 -2
  169. package/dist/session/session.service.js +169 -66
  170. package/dist/session/session.types.js +4 -4
  171. package/dist/session/sidecar-json-shape.d.ts +31 -0
  172. package/dist/session/sidecar-json-shape.js +217 -0
  173. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  174. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  175. package/dist/shared/fs/file-identity.d.ts +10 -0
  176. package/dist/shared/fs/file-identity.js +15 -0
  177. package/dist/shared/fs/replace-file.d.ts +7 -0
  178. package/dist/shared/fs/replace-file.js +33 -0
  179. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  180. package/dist/shared/process/host-process-recovery.js +23 -3
  181. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  182. package/dist/shared/process/host-process-supervisor.js +66 -14
  183. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  184. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  185. package/dist/shared/process/windows-launch.d.ts +18 -0
  186. package/dist/shared/process/windows-launch.js +68 -0
  187. package/dist/shared/provider-capabilities.js +14 -7
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/dist/worktree/orphan-relink.d.ts +19 -0
  191. package/dist/worktree/orphan-relink.js +106 -0
  192. package/dist/worktree/wip-git.d.ts +33 -0
  193. package/dist/worktree/wip-git.js +122 -0
  194. package/dist/worktree/wip-refs.d.ts +62 -0
  195. package/dist/worktree/wip-refs.js +119 -0
  196. package/dist/worktree/wip-restore.d.ts +38 -0
  197. package/dist/worktree/wip-restore.js +190 -0
  198. package/dist/worktree/wip-snapshot.d.ts +50 -0
  199. package/dist/worktree/wip-snapshot.js +268 -0
  200. package/dist/worktree/worktree-inputs.d.ts +8 -0
  201. package/dist/worktree/worktree-inputs.js +134 -0
  202. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  203. package/dist/worktree/worktree-origin-sync.js +127 -0
  204. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  205. package/dist/worktree/worktree-wip-events.js +98 -0
  206. package/dist/worktree/worktree-wip.d.ts +50 -0
  207. package/dist/worktree/worktree-wip.js +185 -0
  208. package/dist/worktree/worktree.base.d.ts +7 -1
  209. package/dist/worktree/worktree.service.d.ts +27 -5
  210. package/dist/worktree/worktree.service.js +110 -181
  211. package/dist/worktree/worktree.types.d.ts +31 -0
  212. package/package.json +2 -2
@@ -2,25 +2,34 @@ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
- import { GitWorktreeService } from "../worktree/worktree.service.js";
5
+ import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
- import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
7
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
9
10
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
11
  export class BridgeSessionService {
11
12
  worktrees;
12
13
  providerCli;
13
14
  hostRuntime;
15
+ workspaceFingerprint;
14
16
  constructor(worktrees = process.env.FORGE_SANDBOX_ID
15
17
  ? new SandboxWorkspaceService()
16
- : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
18
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime, workspaceFingerprint = readWorkspaceRuntimeFingerprint) {
17
19
  this.worktrees = worktrees;
18
20
  this.providerCli = providerCli;
19
21
  this.hostRuntime = hostRuntime;
22
+ this.workspaceFingerprint = workspaceFingerprint;
20
23
  }
21
24
  setHostRequirementsCheck(check) {
22
25
  this.hostRuntime?.setRequirementsCheck?.(check);
23
26
  }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
32
+ }
24
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
25
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
26
35
  }
@@ -181,6 +190,7 @@ export class BridgeSessionService {
181
190
  let worktree = null;
182
191
  let hostSingletonKeys = null;
183
192
  let hostLease = null;
193
+ let succeeded = false;
184
194
  try {
185
195
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
186
196
  const capacity = this.hostRuntime.snapshot?.() ?? null;
@@ -256,6 +266,7 @@ export class BridgeSessionService {
256
266
  warmPathOverrides: dispatch.warmPathOverrides,
257
267
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
258
268
  preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
269
+ sessionId: dispatch.session.id,
259
270
  hostLoadOwner: {
260
271
  dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
261
272
  priority: runtimeAdmissionPriority(dispatch),
@@ -276,6 +287,7 @@ export class BridgeSessionService {
276
287
  : `Prepared worktree ${worktree.branchName}.`,
277
288
  eventType: dispatch.session.resumedFromSessionId ? "worktree_reattached" : "worktree_prepared"
278
289
  });
290
+ await emitWorktreePreparedEvents(worktree, emit);
279
291
  if ((worktree.hydratedPriorPhaseArtifactCount ?? 0) > 0) {
280
292
  await emit({
281
293
  role: "runner",
@@ -338,6 +350,92 @@ export class BridgeSessionService {
338
350
  });
339
351
  }
340
352
  }
353
+ // The stack was built and launched from this workspace state. Pre-publication
354
+ // validation restarts it when the provider has changed the source since.
355
+ let refreshRuntimeEnvironment;
356
+ const hostRuntime = this.hostRuntime;
357
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
358
+ && hostLease.executionClass === "managed_runtime"
359
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
360
+ const worktreePath = worktree.worktreePath;
361
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
362
+ const fencingToken = dispatch.lease.fencingToken;
363
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
364
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
365
+ .catch(() => null);
366
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
367
+ let restartPending = false;
368
+ refreshRuntimeEnvironment = async (refreshSignal) => {
369
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
370
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
371
+ return null;
372
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
373
+ // only when both states were read: an unreadable baseline is not a workspace change.
374
+ const comparable = launchFingerprint !== null && current !== null;
375
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
376
+ const causes = [
377
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
378
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
379
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
380
+ ];
381
+ const reason = causes[0] ?? "workspace_changed";
382
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
383
+ await emitLifecycle({
384
+ role: "runner",
385
+ kind: "checkpoint",
386
+ content: reason === "workspace_changed"
387
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
388
+ : reason === "previous_restart_incomplete"
389
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
390
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
391
+ eventType: "host_runtime_restart_started",
392
+ data: JSON.stringify({
393
+ reason,
394
+ causes,
395
+ changes,
396
+ head_sha: current?.headSha ?? null,
397
+ merge_in_progress: Boolean(current?.mergeHead),
398
+ }),
399
+ });
400
+ restartPending = true;
401
+ let restarted;
402
+ try {
403
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
404
+ await emitLifecycle({
405
+ role: "runner",
406
+ kind: "checkpoint",
407
+ content: checkpoint.message,
408
+ eventType: checkpoint.code,
409
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
410
+ });
411
+ });
412
+ }
413
+ catch (error) {
414
+ await emitLifecycle({
415
+ role: "runner",
416
+ kind: "error",
417
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
418
+ eventType: "host_runtime_restart_failed",
419
+ data: JSON.stringify({ reason, causes, changes }),
420
+ }).catch(() => undefined);
421
+ throw error;
422
+ }
423
+ hostLease = restarted;
424
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
425
+ // keep the pre-restart reading, which is null when it could not be collected; a null
426
+ // baseline never matches, so every later pass would restart and rotate ports again.
427
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
428
+ restartPending = false;
429
+ await emitLifecycle({
430
+ role: "runner",
431
+ kind: "checkpoint",
432
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
433
+ eventType: "host_runtime_restarted",
434
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
435
+ });
436
+ return { environment: restarted.environment, reason, changes };
437
+ };
438
+ }
341
439
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
342
440
  const providerEnvironment = {
343
441
  runtimeEnvironment: hostLease?.environment,
@@ -359,15 +457,16 @@ export class BridgeSessionService {
359
457
  });
360
458
  throwIfAborted(signal);
361
459
  const draftArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
362
- return redactRunOnceResultPacket({
363
- schemaVersion: 2,
364
- exitCode: 0,
365
- summary: run.summary,
460
+ // Redaction can throw (a secret in a structural field); only a returned result is a success.
461
+ const draftResult = redactRunOnceResultPacket({
462
+ schemaVersion: 2, exitCode: 0, summary: run.summary,
366
463
  events,
367
464
  spec: run.spec ?? null,
368
465
  artifact: run.artifact ?? null,
369
466
  artifacts: draftArtifacts
370
467
  }, redactionSecrets);
468
+ succeeded = true;
469
+ return draftResult;
371
470
  }
372
471
  throwIfAborted(signal);
373
472
  const lane = dispatch.execution.lane.trim().toLowerCase();
@@ -384,6 +483,9 @@ export class BridgeSessionService {
384
483
  processRunner: hostLease && dispatch.sandbox
385
484
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
386
485
  : undefined,
486
+ ...(refreshRuntimeEnvironment && hostLease
487
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
488
+ : {}),
387
489
  emit,
388
490
  signal
389
491
  };
@@ -410,10 +512,8 @@ export class BridgeSessionService {
410
512
  }
411
513
  throwIfAborted(signal);
412
514
  const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
413
- return redactRunOnceResultPacket({
414
- schemaVersion: 2,
415
- exitCode: 0,
416
- summary: run.summary,
515
+ const result = redactRunOnceResultPacket({
516
+ schemaVersion: 2, exitCode: 0, summary: run.summary,
417
517
  resultCommitSha: run.resultCommitSha ?? null,
418
518
  publishedCommitSha: run.publishedCommitSha ?? null,
419
519
  events,
@@ -421,72 +521,79 @@ export class BridgeSessionService {
421
521
  artifact: run.artifact ?? null,
422
522
  artifacts: phaseArtifacts
423
523
  }, redactionSecrets);
524
+ succeeded = true;
525
+ return result;
424
526
  }
425
527
  finally {
426
- if (hostLease && dispatch.sandbox) {
427
- const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
428
- if (providerMemory) {
429
- await emitLifecycle({
430
- role: "runner",
431
- kind: "checkpoint",
432
- content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
433
- eventType: "sandbox_peak_memory_observed",
434
- occurredAt: providerMemory.observedAt,
435
- data: JSON.stringify({
436
- peakMemoryBytes: providerMemory.peakMemoryBytes,
437
- sampleCount: providerMemory.sampleCount,
438
- source: providerMemory.source,
439
- containers: [{
440
- role: "agent",
441
- peakMemoryBytes: providerMemory.peakMemoryBytes,
442
- }],
443
- }),
444
- }).catch(() => undefined);
445
- }
446
- const teardownAt = new Date().toISOString();
528
+ await this.releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle);
529
+ if (worktree) {
530
+ await settleWorktree(this.worktrees, worktree, sessionWipOutcome(signal, events, succeeded), signal, emitLifecycle);
531
+ }
532
+ }
533
+ }
534
+ /** Reports the provider's peak memory and releases the attempt's host runtime lease. */
535
+ async releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle) {
536
+ if (hostLease && dispatch.sandbox) {
537
+ const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
538
+ if (providerMemory) {
447
539
  await emitLifecycle({
448
540
  role: "runner",
449
541
  kind: "checkpoint",
450
- content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
451
- eventType: "sandbox_teardown_started",
452
- occurredAt: teardownAt,
542
+ content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
543
+ eventType: "sandbox_peak_memory_observed",
544
+ occurredAt: providerMemory.observedAt,
545
+ data: JSON.stringify({
546
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
547
+ sampleCount: providerMemory.sampleCount,
548
+ source: providerMemory.source,
549
+ containers: [{
550
+ role: "agent",
551
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
552
+ }],
553
+ }),
453
554
  }).catch(() => undefined);
454
- try {
455
- const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
456
- if (!released) {
457
- await emitLifecycle({
458
- role: "runner",
459
- kind: "error",
460
- content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
461
- eventType: "teardown_failed",
462
- occurredAt: new Date().toISOString(),
463
- }).catch(() => undefined);
464
- }
465
- else {
466
- await emitLifecycle({
467
- role: "runner",
468
- kind: "checkpoint",
469
- content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
470
- eventType: "sandbox_teardown_completed",
471
- occurredAt: released.releasedAt,
472
- }).catch(() => undefined);
473
- }
474
- }
475
- catch (error) {
555
+ }
556
+ const teardownAt = new Date().toISOString();
557
+ await emitLifecycle({
558
+ role: "runner",
559
+ kind: "checkpoint",
560
+ content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
561
+ eventType: "sandbox_teardown_started",
562
+ occurredAt: teardownAt,
563
+ }).catch(() => undefined);
564
+ try {
565
+ const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
566
+ if (!released) {
476
567
  await emitLifecycle({
477
568
  role: "runner",
478
569
  kind: "error",
479
- content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
570
+ content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
480
571
  eventType: "teardown_failed",
481
572
  occurredAt: new Date().toISOString(),
482
573
  }).catch(() => undefined);
483
574
  }
575
+ else {
576
+ await emitLifecycle({
577
+ role: "runner",
578
+ kind: "checkpoint",
579
+ content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
580
+ eventType: "sandbox_teardown_completed",
581
+ occurredAt: released.releasedAt,
582
+ }).catch(() => undefined);
583
+ }
484
584
  }
485
- if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
486
- await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
585
+ catch (error) {
586
+ await emitLifecycle({
587
+ role: "runner",
588
+ kind: "error",
589
+ content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
590
+ eventType: "teardown_failed",
591
+ occurredAt: new Date().toISOString(),
592
+ }).catch(() => undefined);
487
593
  }
488
- if (worktree && !isPauseCancellation(signal))
489
- await this.worktrees.release(worktree);
594
+ }
595
+ if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
596
+ await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
490
597
  }
491
598
  }
492
599
  }
@@ -496,10 +603,6 @@ function failureMessage(error) {
496
603
  function formatMemoryBytes(bytes) {
497
604
  return `${(bytes / (1024 ** 2)).toFixed(bytes >= 1024 ** 3 ? 0 : 1)} MiB`;
498
605
  }
499
- function isPauseCancellation(signal) {
500
- return signal?.aborted === true
501
- && String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
502
- }
503
606
  function readinessProbeDispatch(request) {
504
607
  return {
505
608
  schemaVersion: 2,
@@ -469,7 +469,7 @@ function unvalidatedFailureFactsForCode(code, source) {
469
469
  if (code === "bridge.unavailable") {
470
470
  return facts(code, "transport", "offer", source, "retryable", "retry_dispatch");
471
471
  }
472
- if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet"].includes(code)) {
472
+ if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet", "runner_yielding", "runner_settings_pending", "runner_settings_apply_failed", "runner_tier_light", "runner_project_not_allowed"].includes(code)) {
473
473
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
474
474
  }
475
475
  if (["bridge.lease_retry_exhausted", "bridge.capacity_wait_exhausted"].includes(code)) {
@@ -481,7 +481,7 @@ function unvalidatedFailureFactsForCode(code, source) {
481
481
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
482
482
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
483
  }
484
- if (code === "comment_repair_changed_files_mismatch") {
484
+ if (["comment_repair_changed_files_mismatch", "runner_result_sidecar_malformed"].includes(code)) {
485
485
  return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
486
  }
487
487
  if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
@@ -496,7 +496,7 @@ function unvalidatedFailureFactsForCode(code, source) {
496
496
  if (code === "provider_configuration_invalid") {
497
497
  return facts(code, "provider", "prepare", source, "non_retryable", "fix_environment");
498
498
  }
499
- if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
499
+ if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_contract_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
500
500
  return facts(code, "resource", "prepare", source, "retryable", "retry_dispatch");
501
501
  }
502
502
  if (code === "host_runtime_project_start_failed") {
@@ -525,7 +525,7 @@ function unvalidatedFailureFactsForCode(code, source) {
525
525
  if (code === "provider_completion_tool_missing") {
526
526
  return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
527
527
  }
528
- if (code === "provider_terminated_at_turn_ceiling") {
528
+ if (["provider_terminated_at_turn_ceiling", "provider_turn_ended_with_background_work"].includes(code)) {
529
529
  return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
530
530
  }
531
531
  if (code === "provider_context_window_exhausted") {
@@ -0,0 +1,31 @@
1
+ export declare const maximumIntegrityJsonBytes: number;
2
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
3
+ export declare class JsonShapeError extends Error {
4
+ readonly reason: string;
5
+ constructor(reason: string);
6
+ }
7
+ export declare const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
8
+ /**
9
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
10
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
11
+ */
12
+ export declare function inspectJsonText(value: string, onString?: (decoded: string) => void): void;
13
+ export declare function decodeJsonStringToken(value: string, openingQuoteIndex: number): {
14
+ readonly decoded: string;
15
+ readonly nextIndex: number;
16
+ };
17
+ /**
18
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
19
+ * plain text that does not start like JSON, or binary content that is not named *.json.
20
+ */
21
+ export declare function sidecarJsonShapeProblem(content: Uint8Array, path: string, onString?: (decoded: string) => void): string | null;
22
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
23
+ export declare function sidecarJsonRepairInstruction(path: string, reason: string): string;
24
+ /**
25
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
26
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
27
+ */
28
+ export declare function decodeJsonEscapesLeniently(value: string): string;
29
+ export declare function looksLikeJson(value: string, path: string): boolean;
30
+ export declare function isJsonWhitespace(code: number): boolean;
31
+ export declare function isJsonPunctuation(code: number): boolean;
@@ -0,0 +1,217 @@
1
+ import { TextDecoder } from "node:util";
2
+ // One set of JSON shape rules for result sidecars. The end-of-run secret check and the QA gate
3
+ // tools that record sidecars during the run both use it, so the agent is told about a malformed
4
+ // sidecar while it can still rewrite the file, and the end-of-run check never disagrees with it.
5
+ //
6
+ // Content sniffing is deliberate: any sidecar whose text starts like JSON ("{", "[" or '"') is
7
+ // held to strict JSON, whatever its file name, so JSON escapes cannot hide secret material from
8
+ // the byte scan. Only a parseable document can be checked token by token.
9
+ export const maximumIntegrityJsonBytes = 8 * 1024 * 1024;
10
+ const maximumIntegrityJsonDepth = 128;
11
+ const maximumIntegrityJsonTokens = 262_144;
12
+ const jsonEscapePattern = /\\(?:u([0-9a-fA-F]{4})|(["\\/bfnrt]))/gu;
13
+ const simpleJsonEscapes = {
14
+ "\"": "\"", "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t",
15
+ };
16
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
17
+ export class JsonShapeError extends Error {
18
+ reason;
19
+ constructor(reason) {
20
+ super(reason);
21
+ this.reason = reason;
22
+ this.name = "JsonShapeError";
23
+ }
24
+ }
25
+ export const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
26
+ /**
27
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
28
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
29
+ */
30
+ export function inspectJsonText(value, onString) {
31
+ if (Buffer.byteLength(value, "utf8") > maximumIntegrityJsonBytes)
32
+ throw new JsonShapeError(oversizedJsonReason);
33
+ if (value.trim().length === 0)
34
+ throw new JsonShapeError("the file is empty");
35
+ const containers = [];
36
+ let tokenCount = 0;
37
+ let index = 0;
38
+ while (index < value.length) {
39
+ const code = value.charCodeAt(index);
40
+ if (isJsonWhitespace(code) || code === 0x2c || code === 0x3a) {
41
+ index += 1;
42
+ continue;
43
+ }
44
+ tokenCount += 1;
45
+ if (tokenCount > maximumIntegrityJsonTokens) {
46
+ throw new JsonShapeError(`it has more than ${maximumIntegrityJsonTokens} JSON tokens`);
47
+ }
48
+ index = inspectJsonToken(value, index, containers, onString);
49
+ }
50
+ if (containers.length !== 0)
51
+ throw new JsonShapeError("a bracket or brace is never closed");
52
+ assertJsonParses(value);
53
+ }
54
+ function inspectJsonToken(value, index, containers, onString) {
55
+ const code = value.charCodeAt(index);
56
+ if (code === 0x22) {
57
+ const token = decodeJsonStringToken(value, index);
58
+ onString?.(token.decoded);
59
+ return token.nextIndex;
60
+ }
61
+ if (code === 0x7b || code === 0x5b) {
62
+ containers.push(code);
63
+ if (containers.length > maximumIntegrityJsonDepth) {
64
+ throw new JsonShapeError(`it nests deeper than ${maximumIntegrityJsonDepth} levels`);
65
+ }
66
+ return index + 1;
67
+ }
68
+ if (code === 0x7d || code === 0x5d) {
69
+ if (containers.pop() !== (code === 0x7d ? 0x7b : 0x5b)) {
70
+ throw new JsonShapeError(`an unmatched closing bracket or brace ${locationOf(value, index)}`);
71
+ }
72
+ return index + 1;
73
+ }
74
+ let end = index + 1;
75
+ while (end < value.length && !isJsonWhitespace(value.charCodeAt(end)) && !isJsonPunctuation(value.charCodeAt(end))) {
76
+ end += 1;
77
+ }
78
+ return end;
79
+ }
80
+ function assertJsonParses(value) {
81
+ try {
82
+ JSON.parse(value);
83
+ }
84
+ catch (error) {
85
+ // The parser's message can quote the offending text; keep only its position.
86
+ const message = error instanceof Error ? error.message : "";
87
+ const position = /\bposition (\d+)/u.exec(message);
88
+ const location = position ? ` ${locationOf(value, Number(position[1]))}` : "";
89
+ throw new JsonShapeError(message.includes("after JSON")
90
+ ? `unexpected text after the JSON value${location}`
91
+ : `invalid JSON syntax${location}`);
92
+ }
93
+ }
94
+ export function decodeJsonStringToken(value, openingQuoteIndex) {
95
+ const chunks = [];
96
+ let segmentStart = openingQuoteIndex + 1;
97
+ let index = segmentStart;
98
+ while (index < value.length) {
99
+ const code = value.charCodeAt(index);
100
+ if (code === 0x22) {
101
+ chunks.push(value.slice(segmentStart, index));
102
+ const decoded = chunks.join("");
103
+ if (!isWellFormedUnicode(decoded)) {
104
+ throw new JsonShapeError(`a string has an unpaired Unicode surrogate ${locationOf(value, openingQuoteIndex)}`);
105
+ }
106
+ return { decoded, nextIndex: index + 1 };
107
+ }
108
+ if (code < 0x20) {
109
+ throw new JsonShapeError(`a string contains a raw control character ${locationOf(value, index)}`);
110
+ }
111
+ if (code !== 0x5c) {
112
+ index += 1;
113
+ continue;
114
+ }
115
+ chunks.push(value.slice(segmentStart, index));
116
+ const escape = decodeJsonEscape(value, index);
117
+ chunks.push(escape.decoded);
118
+ index = escape.nextIndex;
119
+ segmentStart = index;
120
+ }
121
+ throw new JsonShapeError(`a string is never closed ${locationOf(value, openingQuoteIndex)}`);
122
+ }
123
+ function decodeJsonEscape(value, backslashIndex) {
124
+ const escaped = value[backslashIndex + 1];
125
+ const simple = escaped === undefined ? undefined : simpleJsonEscapes[escaped];
126
+ if (simple !== undefined)
127
+ return { decoded: simple, nextIndex: backslashIndex + 2 };
128
+ const hex = value.slice(backslashIndex + 2, backslashIndex + 6);
129
+ if (escaped !== "u" || !/^[0-9a-fA-F]{4}$/u.test(hex)) {
130
+ throw new JsonShapeError(`a string has an invalid escape sequence ${locationOf(value, backslashIndex)}`);
131
+ }
132
+ return { decoded: String.fromCharCode(Number.parseInt(hex, 16)), nextIndex: backslashIndex + 6 };
133
+ }
134
+ /**
135
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
136
+ * plain text that does not start like JSON, or binary content that is not named *.json.
137
+ */
138
+ export function sidecarJsonShapeProblem(content, path, onString) {
139
+ let decoded;
140
+ try {
141
+ decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content);
142
+ }
143
+ catch {
144
+ // Sniff the bytes anyway (invalid sequences decode to U+FFFD, which is not whitespace), so a
145
+ // file that starts like JSON cannot dodge the strict check with a stray invalid byte.
146
+ return looksLikeJson(Buffer.from(content).toString("utf8"), path) ? "the file is not valid UTF-8" : null;
147
+ }
148
+ if (!looksLikeJson(decoded, path))
149
+ return null;
150
+ if (content.length >= 3 && content[0] === 0xef && content[1] === 0xbb && content[2] === 0xbf) {
151
+ return "the file starts with a UTF-8 byte-order mark";
152
+ }
153
+ try {
154
+ inspectJsonText(decoded, onString);
155
+ return null;
156
+ }
157
+ catch (error) {
158
+ if (error instanceof JsonShapeError)
159
+ return error.reason;
160
+ throw error;
161
+ }
162
+ }
163
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
164
+ export function sidecarJsonRepairInstruction(path, reason) {
165
+ const fix = isJsonFileName(path)
166
+ ? "Rewrite it as valid JSON (UTF-8, no byte-order mark), or save plain-text output under a name that does not end in .json"
167
+ : "Rewrite it as valid JSON, or as plain text that does not start with \"[\", \"{\" or a double quote (for example, put a title line first)";
168
+ return `${path} looks like JSON but is not valid JSON (${reason}). Forge rejects sidecars it cannot fully inspect. `
169
+ + `${fix}, then resubmit with the file's new bytes and content_hash.`;
170
+ }
171
+ /**
172
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
173
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
174
+ */
175
+ export function decodeJsonEscapesLeniently(value) {
176
+ return value.replace(jsonEscapePattern, (_match, hex, simple) => hex !== undefined ? String.fromCharCode(Number.parseInt(hex, 16)) : simpleJsonEscapes[simple ?? ""] ?? "");
177
+ }
178
+ export function looksLikeJson(value, path) {
179
+ if (isJsonFileName(path))
180
+ return true;
181
+ const candidate = value.trimStart().replace(/^\uFEFF/u, "").trimStart();
182
+ return candidate.startsWith("{") || candidate.startsWith("[") || candidate.startsWith("\"");
183
+ }
184
+ function isJsonFileName(path) {
185
+ return path.toLowerCase().endsWith(".json");
186
+ }
187
+ function locationOf(value, index) {
188
+ let line = 1;
189
+ let lineStart = 0;
190
+ for (let cursor = value.indexOf("\n"); cursor >= 0 && cursor < index; cursor = value.indexOf("\n", cursor + 1)) {
191
+ line += 1;
192
+ lineStart = cursor + 1;
193
+ }
194
+ return `at line ${line}, column ${index - lineStart + 1}`;
195
+ }
196
+ function isWellFormedUnicode(value) {
197
+ for (let index = 0; index < value.length; index += 1) {
198
+ const code = value.charCodeAt(index);
199
+ if (code >= 0xd800 && code <= 0xdbff) {
200
+ const next = value.charCodeAt(index + 1);
201
+ if (!(next >= 0xdc00 && next <= 0xdfff))
202
+ return false;
203
+ index += 1;
204
+ }
205
+ else if (code >= 0xdc00 && code <= 0xdfff) {
206
+ return false;
207
+ }
208
+ }
209
+ return true;
210
+ }
211
+ export function isJsonWhitespace(code) {
212
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
213
+ }
214
+ export function isJsonPunctuation(code) {
215
+ return code === 0x7b || code === 0x7d || code === 0x5b || code === 0x5d
216
+ || code === 0x2c || code === 0x3a || code === 0x22;
217
+ }