@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0f8fb73715e8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +183 -4
- package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
- package/dist/bridge/bridge-chat-giphy-look.js +55 -0
- package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
- package/dist/bridge/bridge-chat-provider-command.js +230 -0
- package/dist/bridge/bridge-chat.types.d.ts +20 -0
- package/dist/bridge/bridge-chat.types.js +28 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +15 -0
- package/dist/bridge/bridge-state-io.js +68 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +102 -14
- package/dist/bridge/bridge.service.js +499 -471
- package/dist/bridge/bridge.types.d.ts +37 -0
- package/dist/bridge/bridge.types.js +2 -1
- package/dist/bridge/default-session-service.d.ts +13 -0
- package/dist/bridge/default-session-service.js +22 -0
- package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
- package/dist/bridge/dispatch-offer-policy.js +58 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +31 -1
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/bridge/windows-bash-resolution.d.ts +31 -0
- package/dist/bridge/windows-bash-resolution.js +153 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -0
- package/dist/cleanup/forge-owned-paths.d.ts +11 -0
- package/dist/cleanup/forge-owned-paths.js +62 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +75 -13
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +161 -228
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +18 -1
- package/dist/cli/local-config.js +67 -5
- package/dist/cli/provider-cli-advertising.d.ts +24 -0
- package/dist/cli/provider-cli-advertising.js +88 -0
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-listener-inspector.d.ts +26 -0
- package/dist/runtime/host-listener-inspector.js +84 -3
- package/dist/runtime/host-load-admission.d.ts +72 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-capacity.d.ts +198 -0
- package/dist/runtime/host-load-capacity.js +353 -0
- package/dist/runtime/host-load-child-environment.d.ts +40 -0
- package/dist/runtime/host-load-child-environment.js +110 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +82 -0
- package/dist/runtime/host-load-governor-config.js +104 -0
- package/dist/runtime/host-load-governor.d.ts +273 -0
- package/dist/runtime/host-load-governor.js +831 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
- package/dist/runtime/host-load-live-test-slots.js +193 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +92 -2
- package/dist/runtime/host-load-sampler.js +166 -8
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +107 -0
- package/dist/runtime/host-load-step-run.js +158 -0
- package/dist/runtime/host-load-test-slot.d.ts +46 -0
- package/dist/runtime/host-load-test-slot.js +100 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +15 -0
- package/dist/runtime/host-runtime-contract.js +39 -6
- package/dist/runtime/host-runtime-lease.d.ts +101 -6
- package/dist/runtime/host-runtime-lease.js +408 -294
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- package/dist/runtime/host-runtime-promotion.d.ts +101 -2
- package/dist/runtime/host-runtime-promotion.js +355 -14
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
- package/dist/runtime/prepared-runtime-identity.js +130 -9
- package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
- package/dist/runtime/prepared-runtime-readiness.js +89 -18
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.d.ts +11 -3
- package/dist/sandbox/runtime.js +53 -20
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox-input.d.ts +22 -0
- package/dist/sandbox/sandbox-input.js +49 -0
- package/dist/sandbox/workspace.service.js +15 -2
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -7
- package/dist/session/managed-attempt-tools.js +204 -141
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +7 -0
- package/dist/session/managed-build-receipt.js +11 -3
- package/dist/session/managed-command-environment.d.ts +8 -0
- package/dist/session/managed-command-environment.js +28 -0
- package/dist/session/managed-command-host-load.d.ts +52 -0
- package/dist/session/managed-command-host-load.js +87 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
- package/dist/session/phase-completion.artifact-bundle.js +167 -0
- package/dist/session/phase-completion.artifacts.d.ts +9 -17
- package/dist/session/phase-completion.artifacts.js +158 -190
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +31 -2
- package/dist/session/phase-completion.helpers.js +18 -65
- package/dist/session/phase-completion.js +19 -32
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +195 -0
- package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
- package/dist/session/phase-completion.phase-aliases.js +43 -0
- package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
- package/dist/session/phase-completion.pr-review-schema.js +75 -0
- package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
- package/dist/session/phase-completion.pr-review-validation.js +212 -0
- package/dist/session/phase-completion.pr-review.d.ts +36 -0
- package/dist/session/phase-completion.pr-review.js +294 -0
- package/dist/session/phase-completion.prompts.d.ts +1 -1
- package/dist/session/phase-completion.prompts.js +20 -1
- package/dist/session/phase-completion.runtime.d.ts +13 -12
- package/dist/session/phase-completion.runtime.js +113 -214
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +219 -232
- package/dist/session/phase-completion.validation.d.ts +3 -3
- package/dist/session/phase-completion.validation.js +58 -94
- package/dist/session/pr-review-diff-base.d.ts +18 -0
- package/dist/session/pr-review-diff-base.js +44 -0
- package/dist/session/pr-review-placement.d.ts +50 -0
- package/dist/session/pr-review-placement.js +91 -0
- package/dist/session/pre-publication-change-set.d.ts +62 -0
- package/dist/session/pre-publication-change-set.js +166 -0
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +112 -0
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +32 -19
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +39 -22
- package/dist/session/pre-publication-validation.js +241 -207
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
- package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
- package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
- package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
- package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
- package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
- package/dist/session/provider-cli/pr-review-prompt.js +119 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +281 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
- package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +41 -432
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -3
- package/dist/session/provider-cli/provider-cli.prompts.js +183 -90
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +43 -1
- package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
- package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +18 -18
- package/dist/session/provider-cli/provider-cli.service.js +127 -317
- package/dist/session/provider-cli/provider-cli.types.d.ts +35 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +279 -0
- package/dist/session/session-host-project.d.ts +22 -0
- package/dist/session/session-host-project.js +98 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.parse-helpers.d.ts +10 -0
- package/dist/session/session.parse-helpers.js +84 -0
- package/dist/session/session.runtime-refresh.d.ts +46 -0
- package/dist/session/session.runtime-refresh.js +116 -0
- package/dist/session/session.service.d.ts +16 -2
- package/dist/session/session.service.js +208 -155
- package/dist/session/session.types.d.ts +8 -0
- package/dist/session/session.types.js +13 -83
- package/dist/session/session.types.pr-review.d.ts +48 -0
- package/dist/session/session.types.pr-review.js +51 -0
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.d.ts +2 -0
- package/dist/shared/provider-capabilities.js +23 -7
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.js +24 -0
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +58 -0
- package/dist/worktree/wip-git.js +182 -0
- package/dist/worktree/wip-refs.d.ts +85 -0
- package/dist/worktree/wip-refs.js +169 -0
- package/dist/worktree/wip-restore.d.ts +51 -0
- package/dist/worktree/wip-restore.js +324 -0
- package/dist/worktree/wip-snapshot.d.ts +53 -0
- package/dist/worktree/wip-snapshot.js +270 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +35 -0
- package/dist/worktree/worktree-origin-sync.js +128 -0
- package/dist/worktree/worktree-wip-events.d.ts +20 -0
- package/dist/worktree/worktree-wip-events.js +148 -0
- package/dist/worktree/worktree-wip.d.ts +57 -0
- package/dist/worktree/worktree-wip.js +200 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +58 -5
- package/dist/worktree/worktree.service.js +237 -161
- package/dist/worktree/worktree.types.d.ts +54 -0
- package/package.json +2 -2
- package/runtime/windows-listener-owner.ps1 +12 -1
|
@@ -87,18 +87,27 @@ export function parseChatTurnDispatchPacket(value, capability = unavailableBridg
|
|
|
87
87
|
leaseId,
|
|
88
88
|
fencingToken,
|
|
89
89
|
runnerInstanceId: requiredUuid(packet, "runnerInstanceId"),
|
|
90
|
-
providerKind:
|
|
90
|
+
providerKind: requiredProviderKind(packet),
|
|
91
91
|
model: requiredString(packet, "model").trim(),
|
|
92
92
|
messages,
|
|
93
93
|
contextRefs,
|
|
94
94
|
idempotencyKey: requiredString(packet, "idempotencyKey").trim(),
|
|
95
95
|
providerThreadId: optionalString(packet, "providerThreadId", bridgeChatMaxProviderThreadIdChars),
|
|
96
|
+
effort: optionalString(packet, "effort")?.toLowerCase() ?? null,
|
|
96
97
|
protocolVersion: bridgeChatProtocolVersion,
|
|
97
98
|
requestedCapabilities,
|
|
98
99
|
attachmentHandoffs,
|
|
99
100
|
actionBrokerGrants,
|
|
101
|
+
...giphyFramesPending(packet),
|
|
100
102
|
};
|
|
101
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* The provider kind of a saved provider selection: `codex:bridge` and `codex` are both `codex`.
|
|
106
|
+
* Forge stores the Chat role's provider with its auth-path suffix and may send it as is.
|
|
107
|
+
*/
|
|
108
|
+
export function chatProviderKind(provider) {
|
|
109
|
+
return (provider.split(":", 1)[0] ?? "").trim().toLowerCase();
|
|
110
|
+
}
|
|
102
111
|
export function isTerminalChatTurnCallbackKind(kind) {
|
|
103
112
|
return kind === "output_completed" || kind === "failed" || kind === "cancelled" || kind === "expired";
|
|
104
113
|
}
|
|
@@ -304,6 +313,13 @@ function requiredUuid(source, key) {
|
|
|
304
313
|
}
|
|
305
314
|
return value;
|
|
306
315
|
}
|
|
316
|
+
function requiredProviderKind(source) {
|
|
317
|
+
const kind = chatProviderKind(requiredString(source, "providerKind"));
|
|
318
|
+
if (kind.length === 0) {
|
|
319
|
+
throw new Error("providerKind must be a non-empty string.");
|
|
320
|
+
}
|
|
321
|
+
return kind;
|
|
322
|
+
}
|
|
307
323
|
function requiredString(source, key) {
|
|
308
324
|
const value = source[key];
|
|
309
325
|
if (typeof value !== "string" || value.trim().length === 0) {
|
|
@@ -318,6 +334,17 @@ function boundedRequiredString(source, key, maxLength) {
|
|
|
318
334
|
}
|
|
319
335
|
return clean;
|
|
320
336
|
}
|
|
337
|
+
function giphyFramesPending(packet) {
|
|
338
|
+
if (packet.giphyFramesPending === undefined || packet.giphyFramesPending === null)
|
|
339
|
+
return {};
|
|
340
|
+
const pending = requiredNonNegativeInteger(packet, "giphyFramesPending");
|
|
341
|
+
if (pending === 0)
|
|
342
|
+
return {};
|
|
343
|
+
// Without the cutoff the API would hand out nothing, so a packet without one asks for no frames.
|
|
344
|
+
if (packet.giphyFramesThroughSeq === undefined || packet.giphyFramesThroughSeq === null)
|
|
345
|
+
return {};
|
|
346
|
+
return { giphyFramesPending: pending, giphyFramesThroughSeq: requiredNonNegativeInteger(packet, "giphyFramesThroughSeq") };
|
|
347
|
+
}
|
|
321
348
|
function requiredNonNegativeInteger(source, key) {
|
|
322
349
|
const value = source[key];
|
|
323
350
|
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { type InFlightEntry } from "./in-flight-registry.js";
|
|
2
|
+
import { type BridgeStateLockOptions } from "./bridge-state-lock.js";
|
|
3
|
+
import { type UnpublishedMarker } from "./bridge-state-unpublished.js";
|
|
4
|
+
export { isProcessAlive } from "./bridge-state-io.js";
|
|
5
|
+
export declare const bridgeStateSchemaVersion = 1;
|
|
6
|
+
export declare const defaultStatePublishIntervalMs = 5000;
|
|
7
|
+
export interface BridgeStateFile {
|
|
8
|
+
readonly schemaVersion: typeof bridgeStateSchemaVersion;
|
|
9
|
+
readonly pid: number;
|
|
10
|
+
readonly runnerId: string;
|
|
11
|
+
readonly runnerInstanceId: string;
|
|
12
|
+
readonly version: string;
|
|
13
|
+
/** "running" while connect runs; "stopped" once it has shut down cleanly. */
|
|
14
|
+
readonly state: "running" | "stopped";
|
|
15
|
+
readonly startedAt: string;
|
|
16
|
+
readonly updatedAt: string;
|
|
17
|
+
readonly publishIntervalMs: number;
|
|
18
|
+
readonly connected: boolean;
|
|
19
|
+
/** Yield (local flag or Forge's toggle) that Forge has acknowledged: placement no longer picks this runner. */
|
|
20
|
+
readonly yielding: boolean;
|
|
21
|
+
/** Yield the bridge applies, acknowledged by Forge or not yet. */
|
|
22
|
+
readonly yieldApplied?: boolean;
|
|
23
|
+
/** Another live bridge process publishing to the same file, as last seen by this one. */
|
|
24
|
+
readonly conflict?: BridgeStateConflict | null;
|
|
25
|
+
/** Random per publisher: whose record this is, so a stopping bridge never finalizes another's. */
|
|
26
|
+
readonly publisherId?: string;
|
|
27
|
+
readonly inFlight: readonly InFlightEntry[];
|
|
28
|
+
}
|
|
29
|
+
export interface BridgeStateConflict {
|
|
30
|
+
readonly pid: number;
|
|
31
|
+
readonly runnerInstanceId: string;
|
|
32
|
+
readonly seenAt: string;
|
|
33
|
+
}
|
|
34
|
+
export type BridgeStateRead = {
|
|
35
|
+
readonly kind: "ok";
|
|
36
|
+
readonly state: BridgeStateFile;
|
|
37
|
+
/** Publishers that could not publish their latest state; present only when there are any. */
|
|
38
|
+
readonly unpublished?: readonly UnpublishedMarker[];
|
|
39
|
+
} | {
|
|
40
|
+
readonly kind: "missing";
|
|
41
|
+
} | {
|
|
42
|
+
readonly kind: "invalid";
|
|
43
|
+
readonly error: string;
|
|
44
|
+
};
|
|
45
|
+
export type BridgeIdleVerdict = "idle" | "busy" | "not_yielding" | "stale" | "unknown" | "not_running";
|
|
46
|
+
export declare const bridgeIdleExitCodes: Readonly<Record<BridgeIdleVerdict, number>>;
|
|
47
|
+
export interface BridgeIdleEvaluation {
|
|
48
|
+
readonly verdict: BridgeIdleVerdict;
|
|
49
|
+
readonly exitCode: number;
|
|
50
|
+
readonly reason: string;
|
|
51
|
+
readonly heartbeatAgeMs: number | null;
|
|
52
|
+
readonly staleAfterMs: number;
|
|
53
|
+
readonly pidAlive: boolean | null;
|
|
54
|
+
readonly state: BridgeStateFile | null;
|
|
55
|
+
}
|
|
56
|
+
/** `<config dir>/<config name>.state.json`, e.g. `~/.config/forge/bridge.state.json` beside `bridge.json`. */
|
|
57
|
+
export declare function bridgeStatePathFor(configPath: string): string;
|
|
58
|
+
/**
|
|
59
|
+
* Writes the state atomically: a temp file in the same folder, then a rename over the
|
|
60
|
+
* old one. On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an
|
|
61
|
+
* antivirus scanner has the target open, so it retries briefly.
|
|
62
|
+
*/
|
|
63
|
+
export declare function writeBridgeStateFile(statePath: string, state: BridgeStateFile): Promise<void>;
|
|
64
|
+
/** The record and any live publisher's unpublished marker: what `status --idle` evaluates. */
|
|
65
|
+
export declare function readBridgeStateFile(statePath: string): Promise<BridgeStateRead>;
|
|
66
|
+
/** The record alone, as a publisher reads it before writing the next one. */
|
|
67
|
+
export declare function readBridgeStateRecord(statePath: string): Promise<BridgeStateRead>;
|
|
68
|
+
/** Removes the record so readers report unknown. Only a publisher holding the lock, over its own record. */
|
|
69
|
+
export declare function removeBridgeStateFile(statePath: string): Promise<void>;
|
|
70
|
+
export declare function staleAfterMsFor(state: Pick<BridgeStateFile, "publishIntervalMs"> | null): number;
|
|
71
|
+
/**
|
|
72
|
+
* Idle only when a live bridge process published a fresh heartbeat with nothing in
|
|
73
|
+
* flight. A dead pid, a stale heartbeat, a clean stop or an unreadable file is never
|
|
74
|
+
* reported as idle: each has its own verdict and a non-zero exit code.
|
|
75
|
+
*/
|
|
76
|
+
export declare function evaluateBridgeIdle(read: BridgeStateRead, options: {
|
|
77
|
+
readonly now: number;
|
|
78
|
+
readonly pidAlive: (pid: number) => boolean;
|
|
79
|
+
readonly requireYield?: boolean;
|
|
80
|
+
}): BridgeIdleEvaluation;
|
|
81
|
+
export interface BridgeStateIdentity {
|
|
82
|
+
readonly runnerId: string;
|
|
83
|
+
readonly runnerInstanceId: string;
|
|
84
|
+
readonly version: string;
|
|
85
|
+
}
|
|
86
|
+
export interface BridgeStateSource {
|
|
87
|
+
inFlight(): readonly InFlightEntry[];
|
|
88
|
+
yielding(): boolean;
|
|
89
|
+
yieldApplied?(): boolean;
|
|
90
|
+
connected(): boolean;
|
|
91
|
+
}
|
|
92
|
+
export interface BridgeStatePublisherOptions {
|
|
93
|
+
readonly intervalMs?: number;
|
|
94
|
+
readonly now?: () => Date;
|
|
95
|
+
readonly pid?: number;
|
|
96
|
+
readonly write?: (statePath: string, state: BridgeStateFile) => Promise<void>;
|
|
97
|
+
readonly read?: (statePath: string) => Promise<BridgeStateRead>;
|
|
98
|
+
readonly pidAlive?: (pid: number) => boolean;
|
|
99
|
+
readonly log?: (message: string) => void;
|
|
100
|
+
/** Removes this publisher's own record after a write under the lock failed (fail closed). */
|
|
101
|
+
readonly invalidate?: (statePath: string) => Promise<void>;
|
|
102
|
+
/** Records that this publisher could not publish (fail closed without touching the shared record). */
|
|
103
|
+
readonly markUnpublished?: (statePath: string, marker: UnpublishedMarker) => Promise<void>;
|
|
104
|
+
readonly lock?: BridgeStateLockOptions;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Keeps the state file current while connect runs: on every in-flight change
|
|
108
|
+
* (coalesced) and on a heartbeat timer. Each publish reads the current record and
|
|
109
|
+
* writes the next one under the state file's lock. A failed publish removes the
|
|
110
|
+
* record, so readers report unknown instead of trusting the last one; failures are
|
|
111
|
+
* logged once per streak and never reach the bridge.
|
|
112
|
+
*/
|
|
113
|
+
export declare class BridgeStatePublisher {
|
|
114
|
+
private readonly statePath;
|
|
115
|
+
private readonly identity;
|
|
116
|
+
private readonly source;
|
|
117
|
+
private readonly options;
|
|
118
|
+
private readonly intervalMs;
|
|
119
|
+
private readonly now;
|
|
120
|
+
private readonly startedAt;
|
|
121
|
+
private readonly publisherId;
|
|
122
|
+
private timer;
|
|
123
|
+
private writing;
|
|
124
|
+
private dirty;
|
|
125
|
+
private stopped;
|
|
126
|
+
private failing;
|
|
127
|
+
private conflict;
|
|
128
|
+
private unpublishedSince;
|
|
129
|
+
private sweptExitedMarkers;
|
|
130
|
+
constructor(statePath: string, identity: BridgeStateIdentity, source: BridgeStateSource, options?: BridgeStatePublisherOptions);
|
|
131
|
+
start(): Promise<void>;
|
|
132
|
+
/** Publishes now, or right after the write in progress. */
|
|
133
|
+
publish(): Promise<void>;
|
|
134
|
+
/** Stops the heartbeat and records a clean stop, only over this publisher's own record. */
|
|
135
|
+
stop(): Promise<void>;
|
|
136
|
+
snapshot(state?: BridgeStateFile["state"]): BridgeStateFile;
|
|
137
|
+
private get pid();
|
|
138
|
+
private read;
|
|
139
|
+
private writeLoop;
|
|
140
|
+
/**
|
|
141
|
+
* Reads the record and writes the next one while holding the lock, so no other publisher
|
|
142
|
+
* writes in between: a second bridge always sees the first one's record (and publishes the
|
|
143
|
+
* conflict), and a stopping bridge's "stopped" record never lands over a newer bridge's.
|
|
144
|
+
*/
|
|
145
|
+
private publishRecord;
|
|
146
|
+
/**
|
|
147
|
+
* The last record may say idle while new work starts. This publisher's marker makes readers
|
|
148
|
+
* report unknown; while it holds the lock it also removes its own record, never another's.
|
|
149
|
+
*/
|
|
150
|
+
private failClosed;
|
|
151
|
+
private clearUnpublished;
|
|
152
|
+
private noteFailure;
|
|
153
|
+
private ownsRecord;
|
|
154
|
+
/**
|
|
155
|
+
* Two `connect` processes on one config would overwrite each other's record, and the
|
|
156
|
+
* last writer could be the idle one. Each remembers the other live, fresh writer it saw
|
|
157
|
+
* until that writer is gone or would read as stale, and publishes it as a conflict.
|
|
158
|
+
*/
|
|
159
|
+
private noteConflict;
|
|
160
|
+
}
|
|
161
|
+
export declare function formatAge(ms: number): string;
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { isInFlightEntry } from "./in-flight-registry.js";
|
|
5
|
+
import { withBridgeStateLock } from "./bridge-state-lock.js";
|
|
6
|
+
import { isProcessAlive, withFsRetry, writeJsonFileAtomically } from "./bridge-state-io.js";
|
|
7
|
+
import { readUnpublishedMarkers, removeExitedUnpublishedMarkers, removeUnpublishedMarker, writeUnpublishedMarker, } from "./bridge-state-unpublished.js";
|
|
8
|
+
export { isProcessAlive } from "./bridge-state-io.js";
|
|
9
|
+
// The running `forge-bridge connect` publishes whether it is idle to a small state
|
|
10
|
+
// file beside bridge.json (`bridge.state.json`), so a host can gate a bridge restart
|
|
11
|
+
// on it with `forge-bridge status --idle` (owner, 2026-11-19). The file carries the
|
|
12
|
+
// process id, the runner instance, a heartbeat refreshed every few seconds and the
|
|
13
|
+
// in-flight list. It is rewritten atomically (temp file and rename), so a reader sees
|
|
14
|
+
// either the previous or the next version, never a torn one. Every publisher reads the
|
|
15
|
+
// record and writes its own while holding the state lock (bridge-state-lock.ts), so two
|
|
16
|
+
// publishers never act on a record the other is replacing. A publisher that cannot publish
|
|
17
|
+
// leaves its own marker (bridge-state-unpublished.ts) instead of touching the shared record
|
|
18
|
+
// without the lock. Anything the bridge cannot publish or that a reader cannot fully parse
|
|
19
|
+
// reads as unknown, never as idle.
|
|
20
|
+
export const bridgeStateSchemaVersion = 1;
|
|
21
|
+
export const defaultStatePublishIntervalMs = 5_000;
|
|
22
|
+
const minimumStaleAfterMs = 30_000;
|
|
23
|
+
// Allows for a reader clock slightly ahead of or behind the writer's.
|
|
24
|
+
const futureHeartbeatToleranceMs = 60_000;
|
|
25
|
+
export const bridgeIdleExitCodes = {
|
|
26
|
+
idle: 0,
|
|
27
|
+
busy: 1,
|
|
28
|
+
stale: 3,
|
|
29
|
+
unknown: 3,
|
|
30
|
+
not_running: 4,
|
|
31
|
+
not_yielding: 5,
|
|
32
|
+
};
|
|
33
|
+
/** `<config dir>/<config name>.state.json`, e.g. `~/.config/forge/bridge.state.json` beside `bridge.json`. */
|
|
34
|
+
export function bridgeStatePathFor(configPath) {
|
|
35
|
+
const parsed = path.parse(path.resolve(configPath));
|
|
36
|
+
return path.join(parsed.dir, `${parsed.name}.state.json`);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Writes the state atomically: a temp file in the same folder, then a rename over the
|
|
40
|
+
* old one. On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an
|
|
41
|
+
* antivirus scanner has the target open, so it retries briefly.
|
|
42
|
+
*/
|
|
43
|
+
export async function writeBridgeStateFile(statePath, state) {
|
|
44
|
+
await writeJsonFileAtomically(statePath, state);
|
|
45
|
+
}
|
|
46
|
+
/** The record and any live publisher's unpublished marker: what `status --idle` evaluates. */
|
|
47
|
+
export async function readBridgeStateFile(statePath) {
|
|
48
|
+
const read = await readBridgeStateRecord(statePath);
|
|
49
|
+
if (read.kind !== "ok")
|
|
50
|
+
return read;
|
|
51
|
+
try {
|
|
52
|
+
const unpublished = await readUnpublishedMarkers(statePath);
|
|
53
|
+
return unpublished.length > 0 ? { ...read, unpublished } : read;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
return { kind: "invalid", error: error instanceof Error ? error.message : String(error) };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** The record alone, as a publisher reads it before writing the next one. */
|
|
60
|
+
export async function readBridgeStateRecord(statePath) {
|
|
61
|
+
let text;
|
|
62
|
+
try {
|
|
63
|
+
text = await withFsRetry(() => fs.readFile(statePath, "utf8"));
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === "ENOENT")
|
|
67
|
+
return { kind: "missing" };
|
|
68
|
+
return { kind: "invalid", error: error instanceof Error ? error.message : String(error) };
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const state = parseBridgeState(JSON.parse(text));
|
|
72
|
+
return state ? { kind: "ok", state } : { kind: "invalid", error: "The state file does not match schema version 1." };
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
return { kind: "invalid", error: error instanceof Error ? error.message : String(error) };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Removes the record so readers report unknown. Only a publisher holding the lock, over its own record. */
|
|
79
|
+
export async function removeBridgeStateFile(statePath) {
|
|
80
|
+
await withFsRetry(() => fs.rm(statePath, { force: true }));
|
|
81
|
+
}
|
|
82
|
+
export function staleAfterMsFor(state) {
|
|
83
|
+
const interval = state && Number.isFinite(state.publishIntervalMs) ? state.publishIntervalMs : defaultStatePublishIntervalMs;
|
|
84
|
+
return Math.max(minimumStaleAfterMs, interval * 6);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Idle only when a live bridge process published a fresh heartbeat with nothing in
|
|
88
|
+
* flight. A dead pid, a stale heartbeat, a clean stop or an unreadable file is never
|
|
89
|
+
* reported as idle: each has its own verdict and a non-zero exit code.
|
|
90
|
+
*/
|
|
91
|
+
export function evaluateBridgeIdle(read, options) {
|
|
92
|
+
if (read.kind !== "ok") {
|
|
93
|
+
const reason = read.kind === "missing"
|
|
94
|
+
? "No bridge state file. Either `forge-bridge connect` has not run with this config, the running bridge predates idle reporting, or it could not publish its state; idle cannot be determined."
|
|
95
|
+
: `The bridge state file is unreadable (${read.error}); idle cannot be determined.`;
|
|
96
|
+
return { verdict: "unknown", exitCode: bridgeIdleExitCodes.unknown, reason, heartbeatAgeMs: null, staleAfterMs: staleAfterMsFor(null), pidAlive: null, state: null };
|
|
97
|
+
}
|
|
98
|
+
const state = read.state;
|
|
99
|
+
const staleAfterMs = staleAfterMsFor(state);
|
|
100
|
+
const heartbeatAgeMs = options.now - Date.parse(state.updatedAt);
|
|
101
|
+
const pidAlive = options.pidAlive(state.pid);
|
|
102
|
+
const result = (verdict, reason) => ({ verdict, exitCode: bridgeIdleExitCodes[verdict], reason, heartbeatAgeMs, staleAfterMs, pidAlive, state });
|
|
103
|
+
// Ahead of every other check: the record on disk may be another bridge's, or this one's last idle.
|
|
104
|
+
// Held back unless the marker is provably stale: an unreadable age never lets it lapse.
|
|
105
|
+
const unpublished = (read.unpublished ?? []).find(marker => options.pidAlive(marker.pid)
|
|
106
|
+
&& !(options.now - Date.parse(marker.updatedAt) > staleAfterMsFor(marker)));
|
|
107
|
+
if (unpublished) {
|
|
108
|
+
return result("unknown", `Bridge process ${unpublished.pid} could not publish its state since ${unpublished.since} (${unpublished.error}); the state file may be out of date, so idle cannot be determined.`);
|
|
109
|
+
}
|
|
110
|
+
if (!pidAlive) {
|
|
111
|
+
return result("not_running", `Bridge process ${state.pid} is not running (last heartbeat ${state.updatedAt}${state.state === "stopped" ? ", stopped cleanly" : ", it did not stop cleanly"}). There is no bridge to interrupt, but this is not an idle report.`);
|
|
112
|
+
}
|
|
113
|
+
if (state.conflict && options.pidAlive(state.conflict.pid)) {
|
|
114
|
+
return result("unknown", `Two bridge processes publish to this state file (pid ${state.pid} and pid ${state.conflict.pid}, both using this bridge config); idle cannot be determined. Stop the extra \`forge-bridge connect\`.`);
|
|
115
|
+
}
|
|
116
|
+
if (state.state === "stopped") {
|
|
117
|
+
return result("unknown", `Bridge process ${state.pid} reported a clean stop but is still running; it is shutting down. Check again shortly.`);
|
|
118
|
+
}
|
|
119
|
+
if (!Number.isFinite(heartbeatAgeMs) || heartbeatAgeMs > staleAfterMs || heartbeatAgeMs < -futureHeartbeatToleranceMs) {
|
|
120
|
+
return result("stale", `The heartbeat is stale (${formatAge(heartbeatAgeMs)} old, limit ${formatAge(staleAfterMs)}) although process ${state.pid} exists. The bridge may be hung, or the pid was reused; do not treat it as idle.`);
|
|
121
|
+
}
|
|
122
|
+
if (state.inFlight.length > 0) {
|
|
123
|
+
return result("busy", `${state.inFlight.length} in-flight item(s); restarting the bridge now would kill them.`);
|
|
124
|
+
}
|
|
125
|
+
if (options.requireYield && !state.yielding) {
|
|
126
|
+
return result("not_yielding", "No in-flight work, but the bridge does not report yield, so Forge can start new work before the restart.");
|
|
127
|
+
}
|
|
128
|
+
return result("idle", "No in-flight work.");
|
|
129
|
+
}
|
|
130
|
+
// Published when the bridge cannot read its own ledgers: the file must not claim idle.
|
|
131
|
+
const unreadableInFlight = { kind: "unknown", ids: {}, phase: "in_flight_unreadable", since: null, phaseSince: null };
|
|
132
|
+
/**
|
|
133
|
+
* Keeps the state file current while connect runs: on every in-flight change
|
|
134
|
+
* (coalesced) and on a heartbeat timer. Each publish reads the current record and
|
|
135
|
+
* writes the next one under the state file's lock. A failed publish removes the
|
|
136
|
+
* record, so readers report unknown instead of trusting the last one; failures are
|
|
137
|
+
* logged once per streak and never reach the bridge.
|
|
138
|
+
*/
|
|
139
|
+
export class BridgeStatePublisher {
|
|
140
|
+
statePath;
|
|
141
|
+
identity;
|
|
142
|
+
source;
|
|
143
|
+
options;
|
|
144
|
+
intervalMs;
|
|
145
|
+
now;
|
|
146
|
+
startedAt;
|
|
147
|
+
publisherId = randomUUID();
|
|
148
|
+
timer = null;
|
|
149
|
+
writing = null;
|
|
150
|
+
dirty = false;
|
|
151
|
+
stopped = false;
|
|
152
|
+
failing = false;
|
|
153
|
+
conflict = null;
|
|
154
|
+
unpublishedSince = null;
|
|
155
|
+
sweptExitedMarkers = false;
|
|
156
|
+
constructor(statePath, identity, source, options = {}) {
|
|
157
|
+
this.statePath = statePath;
|
|
158
|
+
this.identity = identity;
|
|
159
|
+
this.source = source;
|
|
160
|
+
this.options = options;
|
|
161
|
+
this.intervalMs = Math.max(250, options.intervalMs ?? defaultStatePublishIntervalMs);
|
|
162
|
+
this.now = options.now ?? (() => new Date());
|
|
163
|
+
this.startedAt = this.now().toISOString();
|
|
164
|
+
}
|
|
165
|
+
start() {
|
|
166
|
+
this.timer = setInterval(() => void this.publish(), this.intervalMs);
|
|
167
|
+
this.timer.unref?.();
|
|
168
|
+
return this.publish();
|
|
169
|
+
}
|
|
170
|
+
/** Publishes now, or right after the write in progress. */
|
|
171
|
+
publish() {
|
|
172
|
+
if (this.stopped)
|
|
173
|
+
return Promise.resolve();
|
|
174
|
+
if (this.writing) {
|
|
175
|
+
this.dirty = true;
|
|
176
|
+
return this.writing;
|
|
177
|
+
}
|
|
178
|
+
this.writing = this.writeLoop().finally(() => {
|
|
179
|
+
this.writing = null;
|
|
180
|
+
});
|
|
181
|
+
return this.writing;
|
|
182
|
+
}
|
|
183
|
+
/** Stops the heartbeat and records a clean stop, only over this publisher's own record. */
|
|
184
|
+
async stop() {
|
|
185
|
+
if (this.timer)
|
|
186
|
+
clearInterval(this.timer);
|
|
187
|
+
this.timer = null;
|
|
188
|
+
// No running write may land after the stop record.
|
|
189
|
+
this.stopped = true;
|
|
190
|
+
await this.writing?.catch(() => undefined);
|
|
191
|
+
await this.publishRecord("stopped");
|
|
192
|
+
// Stopped: nothing of this publisher's is left to hold readers back.
|
|
193
|
+
await removeUnpublishedMarker(this.statePath, this.publisherId).catch(() => undefined);
|
|
194
|
+
}
|
|
195
|
+
snapshot(state = "running") {
|
|
196
|
+
return {
|
|
197
|
+
schemaVersion: bridgeStateSchemaVersion,
|
|
198
|
+
pid: this.pid,
|
|
199
|
+
runnerId: this.identity.runnerId,
|
|
200
|
+
runnerInstanceId: this.identity.runnerInstanceId,
|
|
201
|
+
version: this.identity.version,
|
|
202
|
+
state,
|
|
203
|
+
startedAt: this.startedAt,
|
|
204
|
+
updatedAt: this.now().toISOString(),
|
|
205
|
+
publishIntervalMs: this.intervalMs,
|
|
206
|
+
connected: safely(() => this.source.connected(), false),
|
|
207
|
+
yielding: safely(() => this.source.yielding(), false),
|
|
208
|
+
yieldApplied: safely(() => this.source.yieldApplied?.() ?? this.source.yielding(), false),
|
|
209
|
+
conflict: this.conflict,
|
|
210
|
+
publisherId: this.publisherId,
|
|
211
|
+
inFlight: safely(() => [...this.source.inFlight()], [unreadableInFlight]),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
get pid() {
|
|
215
|
+
return this.options.pid ?? process.pid;
|
|
216
|
+
}
|
|
217
|
+
async read() {
|
|
218
|
+
return await (this.options.read ?? readBridgeStateRecord)(this.statePath).catch(() => null);
|
|
219
|
+
}
|
|
220
|
+
async writeLoop() {
|
|
221
|
+
do {
|
|
222
|
+
this.dirty = false;
|
|
223
|
+
await this.publishRecord("running");
|
|
224
|
+
} while (this.dirty && !this.stopped);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Reads the record and writes the next one while holding the lock, so no other publisher
|
|
228
|
+
* writes in between: a second bridge always sees the first one's record (and publishes the
|
|
229
|
+
* conflict), and a stopping bridge's "stopped" record never lands over a newer bridge's.
|
|
230
|
+
*/
|
|
231
|
+
async publishRecord(state) {
|
|
232
|
+
let failure = null;
|
|
233
|
+
try {
|
|
234
|
+
await withBridgeStateLock(this.statePath, async () => {
|
|
235
|
+
const current = await this.read();
|
|
236
|
+
if (state === "stopped" && !this.ownsRecord(current))
|
|
237
|
+
return;
|
|
238
|
+
if (state === "running")
|
|
239
|
+
this.noteConflict(current);
|
|
240
|
+
try {
|
|
241
|
+
await (this.options.write ?? writeBridgeStateFile)(this.statePath, this.snapshot(state));
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
failure = await this.failClosed(state, error, this.ownsRecord(current));
|
|
245
|
+
}
|
|
246
|
+
}, this.options.lock);
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
// No lock, so the record may be a newer bridge's: leave it, and mark this publisher instead.
|
|
250
|
+
failure ??= await this.failClosed(state, error, false);
|
|
251
|
+
}
|
|
252
|
+
if (failure) {
|
|
253
|
+
this.noteFailure(failure);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
await this.clearUnpublished();
|
|
257
|
+
if (this.failing)
|
|
258
|
+
this.options.log?.(`Bridge state file ${this.statePath} is being written again.`);
|
|
259
|
+
this.failing = false;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* The last record may say idle while new work starts. This publisher's marker makes readers
|
|
263
|
+
* report unknown; while it holds the lock it also removes its own record, never another's.
|
|
264
|
+
*/
|
|
265
|
+
async failClosed(state, error, ownRecordUnderLock) {
|
|
266
|
+
// A stop that can't be recorded leaves the running record: its pid exits with this process.
|
|
267
|
+
if (state !== "running")
|
|
268
|
+
return { error, invalidated: false };
|
|
269
|
+
const now = this.now().toISOString();
|
|
270
|
+
this.unpublishedSince ??= now;
|
|
271
|
+
const marker = {
|
|
272
|
+
schemaVersion: 1, pid: this.pid, publisherId: this.publisherId, runnerInstanceId: this.identity.runnerInstanceId,
|
|
273
|
+
since: this.unpublishedSince, updatedAt: now, publishIntervalMs: this.intervalMs,
|
|
274
|
+
error: error instanceof Error ? error.message : String(error),
|
|
275
|
+
};
|
|
276
|
+
const marked = await (this.options.markUnpublished ?? writeUnpublishedMarker)(this.statePath, marker).then(() => true, () => false);
|
|
277
|
+
const removed = ownRecordUnderLock
|
|
278
|
+
&& await (this.options.invalidate ?? removeBridgeStateFile)(this.statePath).then(() => true, () => false);
|
|
279
|
+
return { error, invalidated: marked || removed };
|
|
280
|
+
}
|
|
281
|
+
async clearUnpublished() {
|
|
282
|
+
if (this.unpublishedSince === null && this.sweptExitedMarkers)
|
|
283
|
+
return;
|
|
284
|
+
if (this.unpublishedSince !== null) {
|
|
285
|
+
await removeUnpublishedMarker(this.statePath, this.publisherId).catch(() => undefined);
|
|
286
|
+
this.unpublishedSince = null;
|
|
287
|
+
}
|
|
288
|
+
if (!this.sweptExitedMarkers) {
|
|
289
|
+
// Left by bridges that exited while they could not publish.
|
|
290
|
+
await removeExitedUnpublishedMarkers(this.statePath, this.options.pidAlive);
|
|
291
|
+
this.sweptExitedMarkers = true;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
noteFailure({ error, invalidated }) {
|
|
295
|
+
if (!this.failing) {
|
|
296
|
+
const outcome = invalidated
|
|
297
|
+
? "forge-bridge status --idle reports unknown until a publish succeeds"
|
|
298
|
+
: "nor could it mark itself unpublished, so forge-bridge status --idle may read the last record until it goes stale";
|
|
299
|
+
this.options.log?.(`Bridge state file ${this.statePath} could not be written; ${outcome}: ${error instanceof Error ? error.message : String(error)}`);
|
|
300
|
+
}
|
|
301
|
+
this.failing = true;
|
|
302
|
+
}
|
|
303
|
+
ownsRecord(current) {
|
|
304
|
+
return current?.kind === "ok" && current.state.publisherId === this.publisherId;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Two `connect` processes on one config would overwrite each other's record, and the
|
|
308
|
+
* last writer could be the idle one. Each remembers the other live, fresh writer it saw
|
|
309
|
+
* until that writer is gone or would read as stale, and publishes it as a conflict.
|
|
310
|
+
*/
|
|
311
|
+
noteConflict(current) {
|
|
312
|
+
const pidAlive = this.options.pidAlive ?? isProcessAlive;
|
|
313
|
+
const now = this.now().getTime();
|
|
314
|
+
const other = current?.kind === "ok" ? current.state : null;
|
|
315
|
+
if (other && other.pid !== this.pid && other.state === "running" && pidAlive(other.pid)
|
|
316
|
+
&& now - Date.parse(other.updatedAt) <= staleAfterMsFor(other)) {
|
|
317
|
+
if (this.conflict?.pid !== other.pid) {
|
|
318
|
+
this.options.log?.(`Another bridge process (pid ${other.pid}, instance ${other.runnerInstanceId}) publishes to ${this.statePath}; forge-bridge status --idle reports unknown until one of them stops.`);
|
|
319
|
+
}
|
|
320
|
+
this.conflict = { pid: other.pid, runnerInstanceId: other.runnerInstanceId, seenAt: new Date(now).toISOString() };
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (this.conflict && (!pidAlive(this.conflict.pid) || now - Date.parse(this.conflict.seenAt) > staleAfterMsFor(null))) {
|
|
324
|
+
this.conflict = null;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
export function formatAge(ms) {
|
|
329
|
+
if (!Number.isFinite(ms))
|
|
330
|
+
return "unknown";
|
|
331
|
+
const seconds = Math.round(Math.abs(ms) / 1000);
|
|
332
|
+
const text = seconds < 120 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
|
|
333
|
+
return ms < 0 ? `-${text}` : text;
|
|
334
|
+
}
|
|
335
|
+
// Every field a reader relies on, with its type: an incomplete or partly written record is
|
|
336
|
+
// invalid (unknown), never a record that happens to lack the fields that would make it busy.
|
|
337
|
+
const requiredStateChecks = [
|
|
338
|
+
state => state.schemaVersion === bridgeStateSchemaVersion,
|
|
339
|
+
state => Number.isInteger(state.pid) && state.pid > 0,
|
|
340
|
+
state => typeof state.runnerId === "string",
|
|
341
|
+
state => typeof state.runnerInstanceId === "string" && state.runnerInstanceId.length > 0,
|
|
342
|
+
state => typeof state.version === "string",
|
|
343
|
+
state => state.state === "running" || state.state === "stopped",
|
|
344
|
+
state => isTimestamp(state.startedAt),
|
|
345
|
+
state => isTimestamp(state.updatedAt),
|
|
346
|
+
state => typeof state.publishIntervalMs === "number" && Number.isFinite(state.publishIntervalMs) && state.publishIntervalMs > 0,
|
|
347
|
+
state => typeof state.connected === "boolean",
|
|
348
|
+
state => typeof state.yielding === "boolean",
|
|
349
|
+
state => state.yieldApplied === undefined || typeof state.yieldApplied === "boolean",
|
|
350
|
+
state => state.publisherId === undefined || (typeof state.publisherId === "string" && state.publisherId.length > 0),
|
|
351
|
+
state => state.conflict === undefined || state.conflict === null || isConflict(state.conflict),
|
|
352
|
+
state => Array.isArray(state.inFlight) && state.inFlight.every(isInFlightEntry),
|
|
353
|
+
];
|
|
354
|
+
function parseBridgeState(value) {
|
|
355
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
356
|
+
return null;
|
|
357
|
+
const state = value;
|
|
358
|
+
return requiredStateChecks.every(check => check(state)) ? state : null;
|
|
359
|
+
}
|
|
360
|
+
function isConflict(value) {
|
|
361
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
362
|
+
return false;
|
|
363
|
+
const conflict = value;
|
|
364
|
+
return Number.isInteger(conflict.pid) && typeof conflict.runnerInstanceId === "string" && isTimestamp(conflict.seenAt);
|
|
365
|
+
}
|
|
366
|
+
function isTimestamp(value) {
|
|
367
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value));
|
|
368
|
+
}
|
|
369
|
+
function safely(read, fallback) {
|
|
370
|
+
try {
|
|
371
|
+
return read();
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return fallback;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes JSON atomically: a temp file in the same folder, then a rename over the old one.
|
|
3
|
+
* On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an antivirus
|
|
4
|
+
* scanner has the target open, so it retries briefly.
|
|
5
|
+
*/
|
|
6
|
+
export declare function writeJsonFileAtomically(target: string, value: unknown): Promise<void>;
|
|
7
|
+
/** True when a process with this id exists. EPERM means it exists but belongs to someone else. */
|
|
8
|
+
export declare function isProcessAlive(pid: number): boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is
|
|
11
|
+
* open. The backoff is jittered so a writer does not keep landing in lockstep with polling
|
|
12
|
+
* readers, and the budget runs on the monotonic clock so a faked `Date` cannot stretch it.
|
|
13
|
+
*/
|
|
14
|
+
export declare function withFsRetry<T>(operation: () => Promise<T>, budgetMs?: number): Promise<T>;
|
|
15
|
+
export declare function errorCode(error: unknown): string;
|