@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.134
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/CHANGELOG.md +687 -0
- package/README.md +101 -1
- package/dist/build-info.json +10 -10
- package/dist/cli/argument-values.js +38 -0
- package/dist/cli/command-inputs.js +306 -0
- package/dist/cli/help.js +88 -12
- package/dist/cli/hook-ingress.js +78 -0
- package/dist/cli/input-preparation.js +116 -0
- package/dist/cli/native-hook-ingress.js +80 -0
- package/dist/cli/run-cli.js +1465 -450
- package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
- package/dist/cli/runtime-maintenance-ingress.js +52 -0
- package/dist/cli/runtime-process.js +153 -0
- package/dist/cli.js +17 -2
- package/dist/domain/stage-catalog.js +1 -1
- package/dist/harness-runtime/DD-ZCODE.md +99 -0
- package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
- package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
- package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
- package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
- package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
- package/dist/harness-runtime/lib/codex-capacity-policy.d.mts +10 -0
- package/dist/harness-runtime/lib/codex-capacity-policy.mjs +89 -0
- package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
- package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
- package/dist/harness-runtime/lib/daemon-operations.mjs +370 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +693 -0
- package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +190 -0
- package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +805 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +128 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +561 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +490 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +255 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +128 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +703 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +1128 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
- package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
- package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
- package/dist/harness-runtime/lib/lease-renewal.mjs +36 -0
- package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
- package/dist/harness-runtime/lib/lifecycle-command.mjs +272 -0
- package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
- package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
- package/dist/harness-runtime/lib/managed-daemon.d.mts +12 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +619 -0
- package/dist/harness-runtime/lib/model-observations.mjs +101 -0
- package/dist/harness-runtime/lib/native-children.d.mts +14 -0
- package/dist/harness-runtime/lib/native-children.mjs +94 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
- package/dist/harness-runtime/lib/native-streams.mjs +45 -0
- package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
- package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
- package/dist/harness-runtime/lib/operation-progress.mjs +112 -0
- package/dist/harness-runtime/lib/process-json.d.mts +5 -0
- package/dist/harness-runtime/lib/process-json.mjs +201 -0
- package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
- package/dist/harness-runtime/lib/runner-events.mjs +200 -0
- package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
- package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
- package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
- package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
- package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
- package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
- package/dist/protocol/local-files.js +18 -9
- package/dist/runtime/context.js +8 -4
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +1 -1
- package/dist/schemas/code-verification.schema.json +7 -5
- package/dist/schemas/code-work-batch.schema.json +2 -2
- package/dist/schemas/flow-run.schema.json +2 -0
- package/dist/schemas/plan-review-decision.schema.json +3 -3
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/run-control-receipt.schema.json +118 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/branch-context.js +3 -3
- package/dist/services/canon.js +11 -8
- package/dist/services/check-runner-evidence.js +121 -0
- package/dist/services/cleanup.js +133 -40
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +851 -109
- package/dist/services/codex-capacity.js +367 -0
- package/dist/services/codex-hook-delivery.js +32 -0
- package/dist/services/command-context.js +80 -0
- package/dist/services/compatibility-preflight.js +13 -3
- package/dist/services/config.js +11 -8
- package/dist/services/continuation-outcome.js +20 -0
- package/dist/services/controller-fanout.js +136 -0
- package/dist/services/dashboard.js +135 -56
- package/dist/services/engines.js +245 -119
- package/dist/services/eval-snapshots.js +1146 -105
- package/dist/services/execution-policy.js +181 -0
- package/dist/services/external-work-launch.js +230 -0
- package/dist/services/harness-adapter.js +329 -36
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +753 -325
- package/dist/services/lanes.js +78 -65
- package/dist/services/lifecycle-command.js +1 -288
- package/dist/services/lifecycle-contract.js +1 -0
- package/dist/services/lifecycle-invocations.js +1828 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-lease-monitor.js +133 -0
- package/dist/services/managed-processes.js +409 -51
- package/dist/services/merge-queue.js +228 -149
- package/dist/services/merge-server.js +163 -35
- package/dist/services/migrations.js +37 -16
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/plan-runtime.js +26 -11
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +20 -15
- package/dist/services/prompts.js +28 -17
- package/dist/services/protocols.js +163 -87
- package/dist/services/recovery-observation-budget.js +121 -0
- package/dist/services/recovery-snapshot-database.js +145 -0
- package/dist/services/repair-intents.js +42 -0
- package/dist/services/review-copy.js +157 -0
- package/dist/services/review-deferral.js +23 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +411 -0
- package/dist/services/run-control.js +985 -0
- package/dist/services/run-controller-adapter.js +399 -0
- package/dist/services/run-controller-capture.js +179 -0
- package/dist/services/run-controller-process.js +187 -0
- package/dist/services/run-controller-recovery.js +289 -0
- package/dist/services/run-controller-state.js +97 -0
- package/dist/services/run-controller.js +1035 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +147 -0
- package/dist/services/run-observations.js +152 -0
- package/dist/services/run-projection.js +22 -64
- package/dist/services/run-recovery-guard.js +75 -0
- package/dist/services/run-recovery-runtime.js +112 -0
- package/dist/services/run-recovery.js +349 -0
- package/dist/services/runs.js +558 -217
- package/dist/services/runtime-budget.js +430 -0
- package/dist/services/runtime-command.js +43 -0
- package/dist/services/runtime-scope-capture.js +52 -0
- package/dist/services/runtime-scope-control.js +468 -0
- package/dist/services/runtime-scope-resume.js +599 -0
- package/dist/services/runtime-scope-stop.js +180 -0
- package/dist/services/runtime-scope-worker.js +287 -0
- package/dist/services/runtime-service.js +96 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/scope-writer-cleanup.js +27 -0
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +185 -19
- package/dist/services/stage-lifecycle.js +98 -107
- package/dist/services/stage-pause.js +89 -75
- package/dist/services/stage-report-renderer.js +158 -6
- package/dist/services/stage-work-graph.js +35 -0
- package/dist/services/tooling.js +32 -23
- package/dist/services/usage.js +49 -101
- package/dist/services/verification-matrix.js +374 -0
- package/dist/services/vnext-code-review.js +222 -87
- package/dist/services/vnext-code.js +324 -251
- package/dist/services/vnext-contracts.js +10 -1
- package/dist/services/vnext-execution-profile.js +79 -4
- package/dist/services/vnext-fanout.js +182 -17
- package/dist/services/vnext-merge.js +335 -113
- package/dist/services/vnext-plan-review.js +276 -126
- package/dist/services/vnext-plan.js +227 -102
- package/dist/services/vnext-protocolize.js +335 -82
- package/dist/services/vnext-specify.js +119 -81
- package/dist/services/work-registry.js +1083 -194
- package/dist/services/workspace-bootstrap.js +87 -0
- package/dist/services/workspace-files.js +85 -0
- package/dist/services/worktrees.js +98 -44
- package/dist/shared/entity-references.js +8 -0
- package/dist/shared/errors.js +17 -0
- package/dist/storage/agent-output.js +26 -0
- package/dist/storage/database.js +785 -37
- package/dist/storage/foreign-key-transaction.js +39 -0
- package/dist/storage/immutable-input.js +45 -0
- package/dist/storage/import-guard.js +102 -0
- package/dist/storage/native-cleanup.js +52 -0
- package/dist/storage/paths.js +17 -4
- package/dist/storage/projection-lock.js +73 -0
- package/dist/storage/work-references.js +23 -0
- package/dist/storage/writer-contract.js +77 -0
- package/dist/storage/writer-migration.js +85 -0
- package/package.json +30 -13
- package/tools/repair-paused-run-status.mjs +84 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { channel } from "node:diagnostics_channel";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
const requests = new AsyncLocalStorage();
|
|
4
|
+
export function isRuntimeMaintenance(args) {
|
|
5
|
+
return args[0] === "runtime" && args[1] === "process" && ["register", "heartbeat", "confirm", "admission", "finish", "check-admission", "release-turn", "status"].includes(args[2] ?? "");
|
|
6
|
+
}
|
|
7
|
+
export const withMaintenanceDiagnosticScope = (action) => requests.run(Symbol(), action);
|
|
8
|
+
/** Request-local, bounded evidence; never command bytes, paths or lease tokens. */
|
|
9
|
+
export function runtimeMaintenanceDiagnostics(args, deadline, write) {
|
|
10
|
+
const started = performance.now();
|
|
11
|
+
const request = requests.getStore();
|
|
12
|
+
const option = (name) => { const at = args.indexOf(`--${name}`); return at < 0 ? undefined : args[at + 1]; };
|
|
13
|
+
const safe = (value) => typeof value === "string" && /^[A-Za-z0-9:._-]{1,128}$/.test(value) ? value : undefined;
|
|
14
|
+
const identity = { action: safe(args[2]), process_id: safe(option("id")), operation_id: safe(option("operation-id") ?? option("operation")), native_dispatch_started: false };
|
|
15
|
+
let previous = "", count = 0, committed = false;
|
|
16
|
+
const phase = (name, details = {}) => {
|
|
17
|
+
const key = `${details.store_kind ?? ""}:${name}`;
|
|
18
|
+
if (key === previous || count >= 64)
|
|
19
|
+
return;
|
|
20
|
+
previous = key;
|
|
21
|
+
count++;
|
|
22
|
+
write(`${JSON.stringify({ kind: "process_maintenance_phase", ...identity, phase: name, elapsed_ms: Math.round(performance.now() - started), ...(deadline !== undefined ? { remaining_ms: Math.max(0, deadline - Date.now()) } : {}), ...details, ...(["ack", "failed"].includes(name) ? { maintenance_effect: committed ? "committed" : name === "ack" ? "no_mutation_observed" : "unknown" } : {}) })}\n`);
|
|
23
|
+
};
|
|
24
|
+
const timing = channel("dd-flow.sqlite.ingress");
|
|
25
|
+
const log = (message) => {
|
|
26
|
+
if (requests.getStore() !== request)
|
|
27
|
+
return;
|
|
28
|
+
const record = message;
|
|
29
|
+
if (record.phase === "committed" && record.store_kind === "resource")
|
|
30
|
+
committed = true;
|
|
31
|
+
phase(record.phase, { ...(record.store_kind ? { store_kind: record.store_kind } : {}) });
|
|
32
|
+
};
|
|
33
|
+
timing.subscribe(log);
|
|
34
|
+
phase("request", { maintenance_effect: "unknown" });
|
|
35
|
+
return { phase, failure: (error) => {
|
|
36
|
+
let current = error;
|
|
37
|
+
let sqlite;
|
|
38
|
+
for (let depth = 0; current && depth < 8; depth++) {
|
|
39
|
+
sqlite = current.errcode ?? current.sqlite_extended_code ?? current.details?.sqlite_extended_code;
|
|
40
|
+
if (Number.isSafeInteger(sqlite))
|
|
41
|
+
break;
|
|
42
|
+
current = (current.cause ?? current.details?.cause);
|
|
43
|
+
}
|
|
44
|
+
phase("failed", { ...(Number.isSafeInteger(sqlite) ? { sqlite_extended_code: sqlite } : {}) });
|
|
45
|
+
}, close: () => timing.unsubscribe(log) };
|
|
46
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isRuntimeMaintenance, runtimeMaintenanceDiagnostics, withMaintenanceDiagnosticScope } from "./runtime-maintenance-diagnostics.js";
|
|
2
|
+
import { errorRecord, isAppError } from "../shared/errors.js";
|
|
3
|
+
import { writeJson } from "../shared/json.js";
|
|
4
|
+
/** Only the already-selected engine's internal JSON transport takes this path.
|
|
5
|
+
* Operator calls and richer output formats retain the ordinary engine router. */
|
|
6
|
+
export function isRuntimeMaintenanceIngress(args, env) {
|
|
7
|
+
return env.DD_FLOW_ENGINE_MODE === "1" && Number.isFinite(Number(env.DD_FLOW_HOOK_DEADLINE_AT))
|
|
8
|
+
&& Number(env.DD_FLOW_HOOK_DEADLINE_AT) > 0 && args.includes("--json")
|
|
9
|
+
&& isRuntimeMaintenance(args)
|
|
10
|
+
&& !args.some(arg => ["--help", "-h", "--progress-jsonl", "--response-file"].includes(arg) || arg.startsWith("--response-file="));
|
|
11
|
+
}
|
|
12
|
+
export async function runRuntimeMaintenanceIngress(args, env = process.env, io = { stdout: process.stdout, stderr: process.stderr }) {
|
|
13
|
+
return withMaintenanceDiagnosticScope(async () => {
|
|
14
|
+
const deadline = Number(env.DD_FLOW_HOOK_DEADLINE_AT);
|
|
15
|
+
// Publish evidence before loading even the maintenance service graph.
|
|
16
|
+
const diagnostics = runtimeMaintenanceDiagnostics(args, deadline, line => io.stderr.write(line));
|
|
17
|
+
let context;
|
|
18
|
+
try {
|
|
19
|
+
const [{ createContext }, { prepareCommandRoute }, { resolveCommandProjectRoot, resolveCommandPaths }, processCommands, { preflightCliCompatibility }] = await Promise.all([
|
|
20
|
+
import("../runtime/context.js"), import("./command-inputs.js"), import("../services/command-context.js"), import("./runtime-process.js"),
|
|
21
|
+
import("../services/compatibility-preflight.js")
|
|
22
|
+
]);
|
|
23
|
+
diagnostics.phase("imports_ready");
|
|
24
|
+
const invocation = args.filter(arg => arg !== "--json");
|
|
25
|
+
const options = { databaseDeadlineAt: deadline, resourceDatabaseMode: args[2] === "register" ? "initialize" : args[2] === "status" ? "read_existing" : "prepared_existing" };
|
|
26
|
+
context = createContext({ ...env, DD_FLOW_INVOCATION_READONLY: args[2] === "status" ? "1" : undefined }, "read_existing", undefined, options);
|
|
27
|
+
const root = resolveCommandProjectRoot(context, invocation, null);
|
|
28
|
+
const routedArgs = resolveCommandPaths(context, invocation, root);
|
|
29
|
+
const route = prepareCommandRoute(routedArgs);
|
|
30
|
+
const prepared = processCommands.prepareRuntimeProcess(context, route.key, route.parsed);
|
|
31
|
+
// Preserve the common compatibility gate; this is not a second dispatch
|
|
32
|
+
// implementation or permission granted by the ingress predicate.
|
|
33
|
+
await preflightCliCompatibility(context, routedArgs, env, root);
|
|
34
|
+
const result = await processCommands.dispatchRuntimeProcess(context, args[2], route.parsed, prepared);
|
|
35
|
+
const receipt = result;
|
|
36
|
+
const expiry = receipt?.lease_expires_at ?? receipt?.process?.lease_expires_at;
|
|
37
|
+
diagnostics.phase("ack", { ...(expiry && Number.isFinite(Date.parse(expiry)) ? { lease_expires_at: expiry } : {}) });
|
|
38
|
+
writeJson(io.stdout, result);
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
diagnostics.failure(error);
|
|
43
|
+
const record = errorRecord(error);
|
|
44
|
+
writeJson(io.stderr, { ok: false, error: { ...record, details: { ...(!isAppError(error) ? { effect: "unknown" } : {}), ...record.details } } });
|
|
45
|
+
return record.exitCode;
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
context?.db.close?.();
|
|
49
|
+
diagnostics.close();
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { AppError } from "../shared/errors.js";
|
|
2
|
+
import { requiredOption, optionalOption, optionalNumber, optionalPositiveNumber } from "./argument-values.js";
|
|
3
|
+
import { prepareError } from "./input-preparation.js";
|
|
4
|
+
import { recoveryGuard, assertRunMutationAllowed } from "../services/run-recovery-guard.js";
|
|
5
|
+
import { recoveryRuntimeAdmission } from "../services/run-recovery-guard.js";
|
|
6
|
+
import { prepareManagedProcessRegistration, prepareManagedProcessConfirmation, prepareManagedProcessHeartbeat, prepareManagedProcessFinish, prepareManagedProcessStopOperation, prepareManagedProcessReconcile, stopManagedProcess, confirmManagedProcess, finishManagedProcess, renewManagedProcess, assertManagedProcessAdmission, managedProcessRuntimeHome, managedProcessStatus, processIsAlive, reconcileExpiredManagedProcesses, registerManagedProcess } from "../services/managed-processes.js";
|
|
7
|
+
import { admitRuntimeCheck, parseRuntimeBudget, reserveProviderTurn, releaseProviderTurns, prepareProviderTurnRelease } from "../services/runtime-budget.js";
|
|
8
|
+
import { managedProcessBinding, resourceHome } from "../services/managed-processes.js";
|
|
9
|
+
function runtimeProcessStopInput(parsed) {
|
|
10
|
+
const graceMs = optionalNumber(parsed, "grace-ms");
|
|
11
|
+
return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(graceMs !== undefined ? { graceMs } : {}) };
|
|
12
|
+
}
|
|
13
|
+
function runtimeProcessRegistrationInput(context, parsed) {
|
|
14
|
+
const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
|
|
15
|
+
const budget = parseRuntimeBudget(optionalOption(parsed, "budget-json"));
|
|
16
|
+
const kind = requiredOption(parsed, "kind");
|
|
17
|
+
const projectId = optionalOption(parsed, "project-id") ?? null, runId = optionalOption(parsed, "run") ?? null;
|
|
18
|
+
const guard = projectId && runId ? recoveryGuard(context, projectId, runId) : null;
|
|
19
|
+
const run = projectId && runId ? context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]) : null;
|
|
20
|
+
return {
|
|
21
|
+
...(optionalOption(parsed, "id") ? { id: optionalOption(parsed, "id") } : {}), kind, ownerId: requiredOption(parsed, "owner"), uniqueActiveOperation: kind === "eval-observer",
|
|
22
|
+
...(kind === "eval-observer" ? { pid: optionalPositiveNumber(parsed, "pid", true) ?? 0, ...(optionalPositiveNumber(parsed, "process-group-id", true) ? { processGroupId: optionalPositiveNumber(parsed, "process-group-id", true) } : {}) } : {}),
|
|
23
|
+
ownerPid: optionalPositiveNumber(parsed, "owner-pid", true), projectId, runId,
|
|
24
|
+
workId: optionalOption(parsed, "work") ?? null, checkId: optionalOption(parsed, "check") ?? null,
|
|
25
|
+
operationId: optionalOption(parsed, "operation") ?? null, stdoutPath: optionalOption(parsed, "stdout") ?? null,
|
|
26
|
+
stderrPath: optionalOption(parsed, "stderr") ?? null, ...(leaseMs !== undefined ? { leaseMs } : {}),
|
|
27
|
+
metadata: { ...(budget ? { budget, harness: optionalOption(parsed, "harness") ?? null } : {}), ...(projectId && runId ? { run_generation: guard?.generation ?? 0, run_admitted: Boolean(run) && !["draining", "sealed", "resuming"].includes(guard?.status ?? "") } : {}), ...(optionalOption(parsed, "dispatch-barrier") ? { dispatch_barrier: optionalOption(parsed, "dispatch-barrier") } : {}), ...(optionalOption(parsed, "role") ? { role: optionalOption(parsed, "role") } : {}), ...(optionalOption(parsed, "state-dir") ? { state_dir: optionalOption(parsed, "state-dir") } : {}), ...(optionalOption(parsed, "adapter-executable") ? { adapter_executable: optionalOption(parsed, "adapter-executable") } : {}) }
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function runtimeProcessConfirmationInput(parsed) {
|
|
31
|
+
const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true), processGroupId = optionalPositiveNumber(parsed, "process-group-id", true);
|
|
32
|
+
return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ownerPid: optionalPositiveNumber(parsed, "owner-pid", true), pid: optionalPositiveNumber(parsed, "pid", true) ?? 0, ...(processGroupId !== undefined ? { processGroupId } : {}), ...(leaseMs !== undefined ? { leaseMs } : {}) };
|
|
33
|
+
}
|
|
34
|
+
function runtimeProcessHeartbeatInput(parsed) {
|
|
35
|
+
const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
|
|
36
|
+
return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(leaseMs !== undefined ? { leaseMs } : {}) };
|
|
37
|
+
}
|
|
38
|
+
function runtimeProcessFinishInput(parsed) {
|
|
39
|
+
const state = requiredOption(parsed, "state");
|
|
40
|
+
if (state !== "stopped" && state !== "failed")
|
|
41
|
+
throw new AppError("validation", "--state must be stopped or failed", 2);
|
|
42
|
+
return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), state, reason: optionalOption(parsed, "reason") ?? null };
|
|
43
|
+
}
|
|
44
|
+
export function prepareRuntimeProcess(context, key, parsed) {
|
|
45
|
+
try {
|
|
46
|
+
return prepareRuntimeProcessInput(context, key, parsed);
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return prepareError(error);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function prepareRuntimeProcessInput(context, key, parsed) {
|
|
53
|
+
const prepared = {};
|
|
54
|
+
if (key === "runtime process register") {
|
|
55
|
+
prepareManagedProcessRegistration(context, runtimeProcessRegistrationInput(context, parsed));
|
|
56
|
+
}
|
|
57
|
+
if (key === "runtime process heartbeat")
|
|
58
|
+
prepareManagedProcessHeartbeat(context, runtimeProcessHeartbeatInput(parsed));
|
|
59
|
+
if (key === "runtime process finish")
|
|
60
|
+
prepareManagedProcessFinish(context, runtimeProcessFinishInput(parsed));
|
|
61
|
+
if (key === "runtime process confirm")
|
|
62
|
+
prepareManagedProcessConfirmation(context, runtimeProcessConfirmationInput(parsed));
|
|
63
|
+
if (key === "runtime process stop")
|
|
64
|
+
prepareManagedProcessStopOperation(context, runtimeProcessStopInput(parsed));
|
|
65
|
+
if (key === "runtime process reconcile")
|
|
66
|
+
prepareManagedProcessReconcile(requiredOption(parsed, "owner"), optionalNumber(parsed, "grace-ms"));
|
|
67
|
+
if (key === "runtime process release-turn") {
|
|
68
|
+
prepared.providerTurnRelease = prepareProviderTurnRelease({ daemonId: requiredOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), observationFile: optionalOption(parsed, "observation-file") });
|
|
69
|
+
}
|
|
70
|
+
return prepared;
|
|
71
|
+
}
|
|
72
|
+
export async function dispatchRuntimeProcess(context, action, parsed, prepared = {}) {
|
|
73
|
+
if (action === "check-admission")
|
|
74
|
+
return { ok: true, ...admitRuntimeCheck(context, requiredOption(parsed, "id"), requiredOption(parsed, "lease-token")) };
|
|
75
|
+
if (action === "stop")
|
|
76
|
+
return { ok: true, process: await stopManagedProcess(context, runtimeProcessStopInput(parsed)) };
|
|
77
|
+
if (action === "register") {
|
|
78
|
+
const process = registerManagedProcess(context, runtimeProcessRegistrationInput(context, parsed));
|
|
79
|
+
return { ok: true, process };
|
|
80
|
+
}
|
|
81
|
+
if (action === "confirm")
|
|
82
|
+
return { ok: true, process: confirmManagedProcess(context, runtimeProcessConfirmationInput(parsed)) };
|
|
83
|
+
if (action === "heartbeat") {
|
|
84
|
+
const hash = optionalOption(parsed, "registration-sha256");
|
|
85
|
+
if (hash) {
|
|
86
|
+
const record = managedProcessStatus(context).find(value => value.id === requiredOption(parsed, "id"));
|
|
87
|
+
if (!/^[a-f0-9]{64}$/.test(hash) || !record || managedProcessBinding(record, resourceHome(context)).registration_sha256 !== hash)
|
|
88
|
+
throw new AppError("process_maintenance_receipt_invalid", "Heartbeat registration changed", 1);
|
|
89
|
+
}
|
|
90
|
+
const receipt = renewManagedProcess(context, runtimeProcessHeartbeatInput(parsed));
|
|
91
|
+
return { ...receipt, ok: receipt.owned };
|
|
92
|
+
}
|
|
93
|
+
if (action === "admission") {
|
|
94
|
+
const [{ controllerHitlAdmission }, { assertCapacityOwnerAdmission }] = await Promise.all([import("../services/run-controller-adapter.js"), import("../services/codex-capacity.js")]);
|
|
95
|
+
const record = managedProcessStatus(context).find(process => process.id === requiredOption(parsed, "id"));
|
|
96
|
+
if (!record || record.lease_token !== requiredOption(parsed, "lease-token") || record.owner_id !== requiredOption(parsed, "owner") || record.state !== "running" || !record.pid || !record.pid_started_at || !processIsAlive(record))
|
|
97
|
+
throw new AppError("process_ownership_unknown", "Productive dispatch requires its current confirmed runtime owner", 1);
|
|
98
|
+
assertManagedProcessAdmission(context, record);
|
|
99
|
+
const metadata = JSON.parse(record.metadata_json);
|
|
100
|
+
if (metadata.state_dir !== requiredOption(parsed, "state-dir"))
|
|
101
|
+
throw new AppError("process_ownership_unknown", "Runtime admission belongs to another state directory", 1);
|
|
102
|
+
if (record.project_id && record.run_id) {
|
|
103
|
+
if (managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
|
|
104
|
+
throw new AppError("process_runtime_scope_mismatch", "Runtime admission belongs to another or unproven flow home", 1);
|
|
105
|
+
const recovering = recoveryRuntimeAdmission(context, record, { stateDir: requiredOption(parsed, "state-dir"), daemonId: optionalOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), operation: optionalOption(parsed, "operation"), nativeSessionId: optionalOption(parsed, "native-session-id"), promptSha256: optionalOption(parsed, "prompt-sha256") });
|
|
106
|
+
if (!recovering) {
|
|
107
|
+
if (metadata.run_admitted !== true || !Number.isSafeInteger(metadata.run_generation))
|
|
108
|
+
throw new AppError("run_recovery_guarded", "Runtime was not admitted before the RUN fence; reconcile its launch", 1);
|
|
109
|
+
assertRunMutationAllowed(context, record.project_id, record.run_id, metadata.run_generation);
|
|
110
|
+
}
|
|
111
|
+
const run = context.db.get("SELECT status FROM runs WHERE project_id = ? AND id = ?", [record.project_id, record.run_id]);
|
|
112
|
+
const retainedHitlPrompt = recovering && ["paused", "waiting_for_user"].includes(run?.status ?? "") && ["session.prompt", "session.resume"].includes(optionalOption(parsed, "operation") ?? "") && context.db.get("SELECT 1 FROM run_recovery_bindings b JOIN run_recovery_guards g ON g.recovery_id = b.recovery_id WHERE g.project_id = ? AND g.run_id = ? AND g.generation = ? AND b.daemon_id = ? AND b.provider_session_id = ?", [record.project_id, record.run_id, metadata.run_generation, optionalOption(parsed, "daemon-id"), optionalOption(parsed, "native-session-id")]);
|
|
113
|
+
const acceptedHitlPrompt = ["paused", "waiting_for_user"].includes(run?.status ?? "") && controllerHitlAdmission(context, record, { stateDir: requiredOption(parsed, "state-dir"), operationId: optionalOption(parsed, "operation-id"), operation: optionalOption(parsed, "operation"), nativeSessionId: optionalOption(parsed, "native-session-id"), promptSha256: optionalOption(parsed, "prompt-sha256") });
|
|
114
|
+
if (!run || run.status !== "running" && !retainedHitlPrompt && !acceptedHitlPrompt && !["judge", "probe"].includes(metadata.role ?? ""))
|
|
115
|
+
throw new AppError("invalid_run_state", "Subject dispatch requires a running RUN or its retained recovery/HITL prompt", 1);
|
|
116
|
+
if (!recovering)
|
|
117
|
+
assertCapacityOwnerAdmission(context, record, optionalOption(parsed, "operation-id"), { nativeSessionId: optionalOption(parsed, "native-session-id"), promptSha256: optionalOption(parsed, "prompt-sha256") });
|
|
118
|
+
}
|
|
119
|
+
const budget = reserveProviderTurn(context, record, { operationId: optionalOption(parsed, "operation-id") ?? "", operation: optionalOption(parsed, "operation") ?? "", sessionId: optionalOption(parsed, "native-session-id"), daemonId: optionalOption(parsed, "daemon-id"), promptSha256: optionalOption(parsed, "prompt-sha256") });
|
|
120
|
+
return { ok: true, ...budget, process_id: record.id, generation: metadata.run_generation ?? null };
|
|
121
|
+
}
|
|
122
|
+
if (action === "release-turn") {
|
|
123
|
+
const record = managedProcessStatus(context).find(process => process.id === requiredOption(parsed, "id"));
|
|
124
|
+
if (!record || record.lease_token !== requiredOption(parsed, "lease-token") || record.owner_id !== requiredOption(parsed, "owner") || managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
|
|
125
|
+
throw new AppError("process_ownership_unknown", "Budget release requires its retained physical owner", 1);
|
|
126
|
+
return releaseProviderTurns(context, record, { daemonId: requiredOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), observationFile: optionalOption(parsed, "observation-file") }, prepared.providerTurnRelease);
|
|
127
|
+
}
|
|
128
|
+
if (action === "finish")
|
|
129
|
+
return { ok: finishManagedProcess(context, runtimeProcessFinishInput(parsed)) };
|
|
130
|
+
if (action === "status") {
|
|
131
|
+
const id = optionalOption(parsed, "id"), token = optionalOption(parsed, "lease-token"), hash = optionalOption(parsed, "registration-sha256");
|
|
132
|
+
if (!id && !token && !hash)
|
|
133
|
+
return { ok: true, processes: managedProcessStatus(context) };
|
|
134
|
+
if (!id || !token || !hash || !/^[a-f0-9]{64}$/.test(hash))
|
|
135
|
+
throw new AppError("usage", "Exact status requires id, lease-token and registration-sha256", 2);
|
|
136
|
+
const record = managedProcessStatus(context).find(value => value.id === id);
|
|
137
|
+
if (!record || record.lease_token !== token || managedProcessBinding(record, resourceHome(context)).registration_sha256 !== hash || record.state !== "running" || !processIsAlive(record))
|
|
138
|
+
throw new AppError("process_maintenance_receipt_invalid", "Readback binding or physical owner changed", 1);
|
|
139
|
+
assertManagedProcessAdmission(context, record);
|
|
140
|
+
const metadata = JSON.parse(record.metadata_json);
|
|
141
|
+
if (record.project_id && record.run_id) {
|
|
142
|
+
if (metadata.run_admitted !== true || !Number.isSafeInteger(metadata.run_generation))
|
|
143
|
+
throw new AppError("run_recovery_guarded", "Readback has no admitted generation", 1);
|
|
144
|
+
assertRunMutationAllowed(context, record.project_id, record.run_id, metadata.run_generation);
|
|
145
|
+
if (managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
|
|
146
|
+
throw new AppError("process_runtime_scope_mismatch", "Readback belongs to another engine home", 1);
|
|
147
|
+
}
|
|
148
|
+
return { ok: true, process_id: id, lease_expires_at: record.lease_expires_at, registration_sha256: hash, readback: true };
|
|
149
|
+
}
|
|
150
|
+
if (action === "reconcile")
|
|
151
|
+
return { ok: true, processes: await reconcileExpiredManagedProcesses(context, requiredOption(parsed, "owner"), optionalNumber(parsed, "grace-ms")) };
|
|
152
|
+
throw new AppError("usage", "Usage: dd-flow runtime process <start|stop|register|confirm|heartbeat|admission|finish|status|reconcile>", 2);
|
|
153
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { isNativeHookIngress } from "./cli/native-hook-ingress.js";
|
|
3
|
+
import { isRuntimeMaintenanceIngress, runRuntimeMaintenanceIngress } from "./cli/runtime-maintenance-ingress.js";
|
|
4
|
+
import { publishSetup } from './harness-runtime/lib/setup-progress.mjs';
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
const managedHook = Boolean(process.env.DD_FLOW_CODEX_STATE_DIR) && args.slice(0, 3).join(" ") === "codex hook handle" && !args.includes("--help") && !args.includes("-h");
|
|
7
|
+
const exitCode = isRuntimeMaintenanceIngress(args, process.env)
|
|
8
|
+
? await runRuntimeMaintenanceIngress(args)
|
|
9
|
+
: managedHook
|
|
10
|
+
? await (await import("./cli/hook-ingress.js")).runHookIngress(args)
|
|
11
|
+
: isNativeHookIngress(args) && !args.includes("--help") && !args.includes("-h")
|
|
12
|
+
? await (await import("./cli/native-hook-ingress.js")).runNativeHookIngress(args)
|
|
13
|
+
: await (async () => {
|
|
14
|
+
publishSetup('ingress_entered');
|
|
15
|
+
const cli = await import('./cli/run-cli.js');
|
|
16
|
+
publishSetup('imports_ready');
|
|
17
|
+
return await cli.runCli(args);
|
|
18
|
+
})();
|
|
4
19
|
process.exitCode = exitCode;
|
|
@@ -3,7 +3,7 @@ export const vnextStages = [
|
|
|
3
3
|
{ id: "specify", directory: "01-specify", result: "specify.json", schema: "dd-flow/vnext-specify-result@4", next: ["protocolize"] },
|
|
4
4
|
{ id: "protocolize", directory: "02-protocolize", result: "protocolize-result.json", schema: "dd-flow/vnext-protocolize-result@3", next: ["plan"] },
|
|
5
5
|
{ id: "plan", directory: "03-plan", result: "stage-report.json", schema: "dd-flow/stage-report@2", next: ["plan-review", "code"] },
|
|
6
|
-
{ id: "plan-review", directory: "04-plan-review", result: "decision.json", schema: "dd-flow/plan-review-decision@
|
|
6
|
+
{ id: "plan-review", directory: "04-plan-review", result: "decision.json", schema: "dd-flow/plan-review-decision@4", next: ["code"] },
|
|
7
7
|
{ id: "code", directory: "05-code", result: "code-verification.json", schema: "dd-flow/code-verification@2", next: ["code-review", "merge"] },
|
|
8
8
|
{ id: "code-review", directory: "06-code-review", result: "decision.json", schema: "dd-flow/code-review-decision@3", next: ["merge"] },
|
|
9
9
|
{ id: "merge", directory: "07-merge", result: "stage-report.json", schema: "dd-flow/stage-report@2", next: [] }
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# dd-zcode integration boundary
|
|
2
|
+
|
|
3
|
+
`bin/dd-zcode.mjs`, `lib/dd-zcode.mjs` and `lib/dd-zcode-daemon.mjs` implement the
|
|
4
|
+
dd-flow adapter over ACP. The maintained bridge is
|
|
5
|
+
[deksden-com/zcode-acp](https://github.com/deksden-com/zcode-acp), based on upstream
|
|
6
|
+
[william0wang/zcode-acp](https://github.com/william0wang/zcode-acp).
|
|
7
|
+
|
|
8
|
+
| Owner | Responsibility |
|
|
9
|
+
| --- | --- |
|
|
10
|
+
| Upstream bridge | ZCode protocol compatibility, ACP transport, native event translation and general session mechanics. |
|
|
11
|
+
| Downstream bridge extensions | Expose native identity, evidence and control primitives missing upstream; preserve native errors and side-effect semantics. |
|
|
12
|
+
| dd-zcode | Requested/observed profile checks, native-to-dd-flow identity mapping, event normalization, lifecycle forwarding, execution daemon ownership, cancellation/settlement verification and usage forwarding. |
|
|
13
|
+
| dd-flow services | Durable lifecycle decisions, Work/RUN state and usage ingestion/accounting. |
|
|
14
|
+
| dd-eval | Qualify the complete tuple, pin profiles/artifacts and run/monitor evaluations. |
|
|
15
|
+
|
|
16
|
+
Native turn completion is evidence, not proof of semantic Work success. A
|
|
17
|
+
closed transport is not proof that its native descendants stopped. The adapter
|
|
18
|
+
must retain causal errors, missing observations and usage completeness rather
|
|
19
|
+
than turn them into successful/zero-valued results.
|
|
20
|
+
|
|
21
|
+
The bridge marks heuristic ACP completion with
|
|
22
|
+
`_meta.zcodeCompletionEvidence: "inferred"` and exhausted failed turns with
|
|
23
|
+
`"failed"`. dd-zcode rejects these before any post-turn materializing read:
|
|
24
|
+
inferred means `native_outcome_unknown` (not retryable automatically), failed
|
|
25
|
+
means `zcode_turn_not_completed`. This additive evidence does not change the
|
|
26
|
+
acceptance of already-qualified immutable older tuples. Native allocation
|
|
27
|
+
notifications are causal identity evidence, not authorization to replay a turn.
|
|
28
|
+
|
|
29
|
+
## Bridge contract
|
|
30
|
+
|
|
31
|
+
The identity check uses `--dd-harness-version` (`dd-zcode-harness@1` for existing
|
|
32
|
+
qualified builds, `dd-zcode-harness@2` for the qualified v0.46.7 bridge) and
|
|
33
|
+
`--dd-harness-commit`, alongside native and bridge versions. This is the current
|
|
34
|
+
mechanism, not a general capability negotiation protocol. `zcodeLifecycleQualification`
|
|
35
|
+
also admits exact native-binary SHA / bridge-commit tuples; a new tuple requires
|
|
36
|
+
behavioral evidence before admission. Merely changing an allowlist is not that
|
|
37
|
+
evidence.
|
|
38
|
+
|
|
39
|
+
The adapter consumes `zcode/session/resolve`, `read`, `subagents`, `usage`,
|
|
40
|
+
`close`, `resident` and `retainedSubagents`, plus standard/existing session
|
|
41
|
+
operations. Resolution must preserve the session's trusted workspace.
|
|
42
|
+
Residency and retained-tree reads after close must not implicitly resume it.
|
|
43
|
+
Cancellation must target owned sessions and verify resulting tree state.
|
|
44
|
+
Profile facts must come from native readback. Session updates supply tool events.
|
|
45
|
+
The adapter forwards a standalone public lifecycle command to `dd-flow zcode
|
|
46
|
+
event handle`; native Session/tool identity binds it to the one exact issued
|
|
47
|
+
assignment in that daemon scope. The command never exposes the runtime-owned
|
|
48
|
+
invocation ID. Its shell inherits `DD_FLOW_DAEMON_ID`, finds the assignment and
|
|
49
|
+
waits for the committed receipt before any lifecycle mutation can execute.
|
|
50
|
+
|
|
51
|
+
The execution-scoped daemon preserves the live native handles needed for
|
|
52
|
+
background children. Inspection remains available during productive operations;
|
|
53
|
+
a lost owner cannot be repaired by pretending retained topology is a live tree.
|
|
54
|
+
Keep process identity, native identity and adapter control locator distinct.
|
|
55
|
+
|
|
56
|
+
## Usage and contract @2
|
|
57
|
+
|
|
58
|
+
The @2 bridge returns native usage unchanged. `lib/zcode-usage.mjs` reads native
|
|
59
|
+
session evidence and computes request counters in the adapter. It deduplicates
|
|
60
|
+
identified requests, rejects conflicting/invalid measurements and records read
|
|
61
|
+
failures as incomplete evidence. Full history is required for cumulative usage;
|
|
62
|
+
turn-liveness history limits must not be applied here. Immutable @1 bridges
|
|
63
|
+
remain supported through their existing measured projection. All adapter usage
|
|
64
|
+
paths use the same helper; dd-flow services still own accounting deltas.
|
|
65
|
+
|
|
66
|
+
Contract support does not admit a new binary/commit tuple automatically. The
|
|
67
|
+
v0.46.7 @2 tuple is admitted for native SHA `500ae84f…f466` or the ZCode
|
|
68
|
+
Desktop 3.14.3 SHA `b1df2ef3…dad529`, with bridge commit `f4d47b5…2833`.
|
|
69
|
+
The latter passed the published beta.99 public-command probe on 2026-09-23:
|
|
70
|
+
root and two concurrent child Work starts/finishes, plus same-child continuation,
|
|
71
|
+
all with durable native identity receipts. Preserve that
|
|
72
|
+
fail-closed distinction when preparing later evals.
|
|
73
|
+
|
|
74
|
+
Future consumer-only retry, recovery, readiness and accounting rules belong
|
|
75
|
+
here or in the owning dd-flow service. Bridge changes are justified when native
|
|
76
|
+
access or protocol mechanics cannot be implemented through its public interface.
|
|
77
|
+
Review existing patches individually; do not claim that all policy has already
|
|
78
|
+
been extracted from the bridge.
|
|
79
|
+
|
|
80
|
+
## Verification and operations
|
|
81
|
+
|
|
82
|
+
Relevant adapter regressions include `test/zcode-invocation-observer.test.ts`;
|
|
83
|
+
select the additional daemon, usage and lifecycle tests affected by a change.
|
|
84
|
+
Bridge tests check transport facts; adapter tests check their interpretation;
|
|
85
|
+
live qualification checks the actual installed tuple. Release the adapter with
|
|
86
|
+
dd-flow when adapter code or qualification admission changes. A bridge-only
|
|
87
|
+
update does not inherently require an adapter release, but current exact-commit
|
|
88
|
+
admission may require one.
|
|
89
|
+
|
|
90
|
+
Follow the [ZCode upgrade runbook](https://github.com/deksden-com/dd-eval/blob/main/runbooks/update-zcode.md)
|
|
91
|
+
for release discovery, qualification, rollout and rollback. Fork patch maintenance
|
|
92
|
+
is documented in the fork itself. Neither procedure is duplicated here.
|
|
93
|
+
|
|
94
|
+
Adapter changes use short-lived `feat/`, `fix/` or `docs/` branches from `main`,
|
|
95
|
+
reviewed with affected checks before integration (normally squash merge).
|
|
96
|
+
Releases identify verified immutable artifacts, not moving main HEAD. See the
|
|
97
|
+
[cross-repository Git workflow](https://github.com/deksden-com/dd-eval/blob/main/runbooks/git-workflow.md)
|
|
98
|
+
for upgrade ordering, candidate acceptance and hotfixes. Branch-protection
|
|
99
|
+
configuration is separate from this documented policy.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { adapterTimeoutOptions } from "../lib/adapter-timeouts.mjs";
|
|
3
|
+
import { durableDaemonStart, inspectDaemonOperation, interruptDaemonOperation, settleDaemonOperation } from "../lib/daemon-operations.mjs";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { writeJsonAtomic } from "../lib/runner-events.mjs";
|
|
8
|
+
import { hookBudget, invokeNativeHook, readNativeHookInput } from "../lib/native-hook-command.mjs";
|
|
9
|
+
import { doctor } from "../lib/dd-agy.mjs";
|
|
10
|
+
import { callDaemon, qualifyAgyHooks, serveDaemon, startDaemon, stopDaemon } from "../lib/dd-agy-daemon.mjs";
|
|
11
|
+
|
|
12
|
+
function parse(argv) { const positional = [], options = {}; for (let i = 0; i < argv.length; i += 1) { const token = argv[i]; if (!token.startsWith("--")) { positional.push(token); continue; } const key = token.slice(2); if (["json","cancel-tree","tree","no-flow"].includes(key)) options[key] = true; else { if (argv[i + 1] === undefined) throw new Error(`--${key} requires a value`); options[key] = argv[++i]; } } return { positional, options }; }
|
|
13
|
+
const prompt = async options => options["prompt-file"] ? await readFile(options["prompt-file"], "utf8") : options.prompt;
|
|
14
|
+
async function hook(options) {
|
|
15
|
+
const budget = hookBudget(), requestId = randomUUID();
|
|
16
|
+
const payload = JSON.parse(await readNativeHookInput(process.stdin, budget) || "{}"), event = options.event;
|
|
17
|
+
try {
|
|
18
|
+
const observationMs = budget.remaining("observation");
|
|
19
|
+
const identity = await callDaemon(options["state-dir"], "hook.observe", { event, payload, daemonId: options["daemon-id"], deadlineAt: budget.deadlineAt }, observationMs, requestId);
|
|
20
|
+
if (identity.stale) return event === "PreToolUse" ? { decision: "deny", reason: "agy_stale_hook" } : {};
|
|
21
|
+
if (event === "PreToolUse" || event === "PostToolUse") {
|
|
22
|
+
const phase = event === "PreToolUse" ? "before" : "after", args = payload.toolCall?.args ?? {};
|
|
23
|
+
const normalized = { schema_id: "dd-flow/agy-tool-event@1", event_id: identity.event_id, phase, daemon_id: identity.daemon_id, launch_cwd: identity.launch_cwd, conversation_id: payload.conversationId, parent_conversation_id: identity.parent_conversation_id, execution_num: payload.executionNum, step_index: payload.stepIdx, tool: payload.toolCall?.name, input: args, workspace_paths: payload.workspacePaths, transcript_path: payload.transcriptPath, model: payload.modelName, profile: identity.profile, ...(phase === "after" ? { error: payload.error ?? "" } : {}) };
|
|
24
|
+
await invokeNativeHook({ bin: options["dd-flow-bin"] ?? identity.dd_flow_bin,
|
|
25
|
+
args: ["agy", "event", "handle", "--project-root", options["project-root"] ?? identity.project_root, "--json"],
|
|
26
|
+
payload: normalized, home: options["dd-flow-home"] ?? identity.dd_flow_home, timeoutMs: budget.remaining("admission", 15_000) });
|
|
27
|
+
}
|
|
28
|
+
return event === "PreToolUse" ? { decision: "allow" } : {};
|
|
29
|
+
} catch (error) {
|
|
30
|
+
// A failed socket cannot be used to report its own failure. The daemon
|
|
31
|
+
// reads only receipts matching request IDs it actually accepted this turn.
|
|
32
|
+
const correctable = event === "PreToolUse" && error.code === "lifecycle_shell_syntax_invalid" && error.details?.effect === "no_effect"
|
|
33
|
+
&& error.details?.recoverable === true && error.details?.disposition === "pre_cli_shell_refusal";
|
|
34
|
+
try { await writeJsonAtomic(path.join(options["state-dir"], "hook-failures", `${requestId}.json`), { request_id: requestId, observed_at: new Date().toISOString(), code: error.code ?? "agy_hook_rejected", message: error.message,
|
|
35
|
+
details: { ...error.details, effect: correctable ? "no_effect" : "unknown", ...(correctable ? { native_pre_cli_refusal: true } : {}) } }); }
|
|
36
|
+
catch (storage) { process.stderr.write(`${JSON.stringify({ code: error.code, receipt_error: storage.message })}\n`); }
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const { positional, options } = parse(process.argv.slice(2)), [family, command, modifier] = positional; const common = { journal: options.journal, stateDir: options["state-dir"], cwd: options.cwd, bin: options["agy-bin"], provider: options.provider, model: options.model, reasoning: options.reasoning, mode: options.mode, projectRoot: options["project-root"], ddFlowBin: options["dd-flow-bin"], ddFlowHome: options["dd-flow-home"], noFlow: options["no-flow"] === true, ...adapterTimeoutOptions(options, family === "session" ? command : null) }; let result;
|
|
43
|
+
if (family === "doctor") result = await doctor(common);
|
|
44
|
+
else if (family === "hooks" && ["install", "check"].includes(command)) result = await qualifyAgyHooks(common.projectRoot, { stateDir: common.stateDir, install: command === "install" });
|
|
45
|
+
else if (family === "daemon" && command === "start") result = await durableDaemonStart({ ...common, sessionId: options["session-id"], entryPath: process.argv[1] }, startDaemon);
|
|
46
|
+
else if (family === "daemon" && command === "serve") { await serveDaemon(common.stateDir); process.exit(0); }
|
|
47
|
+
else if (family === "daemon" && command === "status") result = await callDaemon(common.stateDir, "daemon.status");
|
|
48
|
+
else if (family === "daemon" && command === "operation" && modifier === "interrupt") result = await interruptDaemonOperation(common.stateDir, options["operation-id"], { control_id: options["control-id"], stop_operation_id: options["stop-operation-id"], daemon_id: options["daemon-id"], session_id: options["session-id"], evidence: options.evidence ? JSON.parse(options.evidence) : null });
|
|
49
|
+
else if (family === "daemon" && command === "operation" && modifier === "settle") result = await settleDaemonOperation(common.stateDir, options["operation-id"]);
|
|
50
|
+
else if (family === "daemon" && command === "operation") result = await inspectDaemonOperation(common.stateDir, options["operation-id"]);
|
|
51
|
+
else if (family === "daemon" && command === "stop") result = await stopDaemon({ stateDir: common.stateDir, cancelTree: options["cancel-tree"], timeoutMs: common.timeoutMs });
|
|
52
|
+
else if (family === "hook" && command === "handle") { process.stdout.write(`${JSON.stringify(await hook(options))}\n`); process.exit(0); }
|
|
53
|
+
else if (family === "session") { if (command === "fork") throw Object.assign(new Error("Antigravity native headless fork is unsupported; use deterministic_replay"), { code: "agy_headless_fork_unsupported" }); const operation = command === "status" ? "inspect" : command; result = await callDaemon(common.stateDir, `session.${operation}`, { sessionId: options["session-id"], livenessTimeoutMs: common.livenessTimeoutMs, ...(command === "create" || command === "prompt" ? { prompt: await prompt(options) } : {}), tree: options.tree === true }, common.timeoutMs ?? 1_800_000); }
|
|
54
|
+
else throw new Error("usage: dd-agy doctor | hooks install|check | daemon start|status|stop | session create|prompt|inspect|resume|cancel|fork [options] --json");
|
|
55
|
+
process.stdout.write(`${JSON.stringify({ ok: true, ...result })}\n`);
|
|
56
|
+
} catch (error) { if (process.argv.includes("hook") && process.argv.includes("handle")) { process.stdout.write(`${JSON.stringify({ decision: "deny", reason: `${error.code ?? "agy_hook_rejected"}: ${error.message ?? "Native hook refused this tool call"}` })}\n`); process.exit(0); } process.stderr.write(`${JSON.stringify({ ok: false, error: error.message, ...(error.code ? { code: error.code, retryable: error.retryable === true, details: error.details } : {}) })}\n`); process.exit(1); }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { adapterTimeoutOptions } from "../lib/adapter-timeouts.mjs";
|
|
3
|
+
import { durableDaemonStart, inspectDaemonOperation, interruptDaemonOperation, settleDaemonOperation } from "../lib/daemon-operations.mjs";
|
|
4
|
+
import { cancelSession, createSession, doctor, inspectSession, promptFromFile, promptSession, startSession } from "../lib/dd-codex.mjs";
|
|
5
|
+
import { callDaemon, serveDaemon, startDaemon, stopDaemon } from "../lib/dd-codex-daemon.mjs";
|
|
6
|
+
import { errorRecord } from "../lib/operation-errors.mjs";
|
|
7
|
+
|
|
8
|
+
function parse(argv) { const positional = []; const options = {}; for (let i = 0; i < argv.length; i += 1) { const token = argv[i]; if (!token.startsWith("--")) { positional.push(token); continue; } const key = token.slice(2); if (["json", "cancel-tree", "no-flow"].includes(key)) { options[key] = true; continue; } const value = argv[++i]; if (value === undefined) throw new Error(`--${key} requires a value`); options[key] = value; } return { positional, options }; }
|
|
9
|
+
function common(options, operation) { return { bin: options["codex-bin"], journal: options.journal, stateDir: options["state-dir"], cwd: options.cwd, sessionId: options["session-id"], turnId: options["turn-id"], model: options.model, reasoning: options.reasoning, ddFlowBin: options["dd-flow-bin"], ddFlowHome: options["dd-flow-home"], projectRoot: options["project-root"], noFlow: options["no-flow"] === true, ...adapterTimeoutOptions(options, operation) }; }
|
|
10
|
+
try {
|
|
11
|
+
const { positional, options } = parse(process.argv.slice(2)); const [family, command, modifier] = positional; const shared = common(options, family === "session" ? command : null); let result;
|
|
12
|
+
if (family === "doctor") result = await doctor(shared);
|
|
13
|
+
else if (family === "daemon" && command === "start") result = await durableDaemonStart({ ...shared, entryPath: process.argv[1] }, startDaemon);
|
|
14
|
+
else if (family === "daemon" && command === "serve") { await serveDaemon(shared.stateDir); process.exit(0); }
|
|
15
|
+
else if (family === "daemon" && command === "status") result = await callDaemon(shared.stateDir, "daemon.status");
|
|
16
|
+
else if (family === "daemon" && command === "operation" && modifier === "interrupt") result = await interruptDaemonOperation(shared.stateDir, options["operation-id"], { control_id: options["control-id"], stop_operation_id: options["stop-operation-id"], daemon_id: options["daemon-id"], session_id: options["session-id"], evidence: options.evidence ? JSON.parse(options.evidence) : null });
|
|
17
|
+
else if (family === "daemon" && command === "operation" && modifier === "settle") result = await settleDaemonOperation(shared.stateDir, options["operation-id"]);
|
|
18
|
+
else if (family === "daemon" && command === "operation") result = await inspectDaemonOperation(shared.stateDir, options["operation-id"]);
|
|
19
|
+
else if (family === "daemon" && command === "stop") result = await stopDaemon({ ...shared, cancelTree: options["cancel-tree"] });
|
|
20
|
+
else if (family === "session" && command === "create") result = shared.stateDir ? await callDaemon(shared.stateDir, "session.create", shared) : await createSession(shared);
|
|
21
|
+
else if (family === "session" && command === "prompt") result = shared.stateDir ? await callDaemon(shared.stateDir, "session.prompt", { ...shared, prompt: options["prompt-file"] ? await promptFromFile(options["prompt-file"]) : options.prompt }, shared.timeoutMs ?? 1_800_000) : await promptSession({ ...shared, prompt: options["prompt-file"] ? await promptFromFile(options["prompt-file"]) : options.prompt });
|
|
22
|
+
else if (family === "session" && command === "start") result = shared.stateDir ? await callDaemon(shared.stateDir, "session.start", { ...shared, prompt: options["prompt-file"] ? await promptFromFile(options["prompt-file"]) : options.prompt }, shared.timeoutMs ?? 30_000) : await startSession({ ...shared, prompt: options["prompt-file"] ? await promptFromFile(options["prompt-file"]) : options.prompt });
|
|
23
|
+
else if (family === "session" && ["inspect", "status", "resume"].includes(command)) result = shared.stateDir ? await callDaemon(shared.stateDir, command === "resume" ? "session.resume" : "session.inspect", shared) : await inspectSession(shared);
|
|
24
|
+
else if (family === "session" && command === "cancel") result = shared.stateDir ? await callDaemon(shared.stateDir, "session.cancel", shared) : await cancelSession(shared);
|
|
25
|
+
else throw new Error("usage: dd-codex doctor | daemon start|status|stop | session create|start|prompt|inspect|status|resume|cancel [--json]");
|
|
26
|
+
process.stdout.write(`${JSON.stringify({ ok: true, ...result })}\n`);
|
|
27
|
+
} catch (error) { const failure = errorRecord(error); process.stderr.write(`${JSON.stringify({ ok: false, error: failure.message, code: failure.code, ...(failure.details ? { details: failure.details } : {}), ...(failure.cause ? { cause: failure.cause } : {}) })}\n`); process.exit(1); }
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { adapterTimeoutOptions } from "../lib/adapter-timeouts.mjs";
|
|
3
|
+
import { durableDaemonStart, inspectDaemonOperation, interruptDaemonOperation, settleDaemonOperation } from "../lib/daemon-operations.mjs";
|
|
4
|
+
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { DROID_CONTRACT, DROID_PROTOCOL, DroidRuntime, droidVersion } from "../lib/dd-droid.mjs";
|
|
9
|
+
import { callDaemon, serveDaemon, startDaemon, stopDaemon } from "../lib/dd-droid-daemon.mjs";
|
|
10
|
+
import { errorRecord } from "../lib/operation-errors.mjs";
|
|
11
|
+
import { hookBudget, readNativeHookInput } from "../lib/native-hook-command.mjs";
|
|
12
|
+
|
|
13
|
+
function parse(argv) { const positional = [], options = {}; for (let i = 0; i < argv.length; i++) { const word = argv[i]; if (!word.startsWith("--")) { positional.push(word); continue; } const key = word.slice(2); if (["json", "cancel-tree", "tree", "no-flow"].includes(key)) options[key] = true; else { if (argv[i + 1] === undefined) throw new Error(`${word} requires a value`); options[key] = argv[++i]; } } return { positional, options }; }
|
|
14
|
+
try {
|
|
15
|
+
const { positional: [family, command, modifier], options } = parse(process.argv.slice(2));
|
|
16
|
+
const config = { stateDir: options["state-dir"], sessionId: options["session-id"], cwd: options.cwd, projectRoot: options["project-root"], bin: options["droid-bin"] ?? "droid", entryPath: process.argv[1], journal: options.journal, authHome: options["auth-home"], model: options.model, provider: options.provider, reasoning: options.reasoning, mode: options.mode, ddFlowBin: options["dd-flow-bin"], ddFlowHome: options["dd-flow-home"], noFlow: options["no-flow"] === true, ...adapterTimeoutOptions(options, family === "session" ? command : null, "droid-cli") };
|
|
17
|
+
let result;
|
|
18
|
+
if (family === "doctor") {
|
|
19
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), "dd-droid-doctor-"));
|
|
20
|
+
const runtime = new DroidRuntime({ ...config, stateDir: dir, home: path.join(dir, "home"), cwd: config.cwd ?? process.cwd(), journal: path.join(dir, "events.jsonl"), daemonId: randomUUID(), ddFlowHome: null, ddFlowBin: null }, {}, async () => {});
|
|
21
|
+
try { await runtime.start(); result = { harness: "droid-cli", observed_runtime: { droid: await droidVersion(config.bin), factory_protocol: runtime.protocol, dd_harness_contract: DROID_CONTRACT }, models: runtime.models.map(model => model.id ?? model.modelId), capabilities: { native_children: true, tree_cancel: true, selective_child_cancel: false, native_fork: false }, protocol_expected: DROID_PROTOCOL }; }
|
|
22
|
+
finally { await runtime.closeTree(true); await rm(dir, { recursive: true, force: true }); }
|
|
23
|
+
} else if (family === "daemon" && command === "start") result = await durableDaemonStart(config, startDaemon);
|
|
24
|
+
else if (family === "daemon" && command === "serve") { await serveDaemon(config.stateDir); process.exit(0); }
|
|
25
|
+
else if (family === "daemon" && command === "status") result = await callDaemon(config.stateDir, "daemon.status");
|
|
26
|
+
else if (family === "daemon" && command === "operation" && modifier === "interrupt") result = await interruptDaemonOperation(config.stateDir, options["operation-id"], { control_id: options["control-id"], stop_operation_id: options["stop-operation-id"], daemon_id: options["daemon-id"], session_id: options["session-id"], evidence: options.evidence ? JSON.parse(options.evidence) : null });
|
|
27
|
+
else if (family === "daemon" && command === "operation" && modifier === "settle") result = await settleDaemonOperation(config.stateDir, options["operation-id"]);
|
|
28
|
+
else if (family === "daemon" && command === "operation") result = await inspectDaemonOperation(config.stateDir, options["operation-id"]);
|
|
29
|
+
else if (family === "daemon" && command === "stop") result = await stopDaemon({ stateDir: config.stateDir, cancelTree: options["cancel-tree"] });
|
|
30
|
+
else if (family === "hook" && command === "handle") { const budget = hookBudget(); const payload = JSON.parse(await readNativeHookInput(process.stdin, budget)); const eventId = randomUUID(); result = await callDaemon(config.stateDir, "hook.observe", { payload, eventId, deadlineAt: budget.deadlineAt }, budget.remaining("observation"), eventId); }
|
|
31
|
+
else if (family === "session") { if (command === "fork") throw new Error("Droid fork is not qualified for this adapter"); const prompt = options["prompt-file"] ? await readFile(options["prompt-file"], "utf8") : options.prompt; result = await callDaemon(config.stateDir, `session.${command === "status" ? "inspect" : command}`, { sessionId: options["session-id"], livenessTimeoutMs: config.livenessTimeoutMs, ...(config.noFlow ? { noFlow: true } : {}), ...(prompt ? { prompt } : {}) }); }
|
|
32
|
+
else throw new Error("usage: dd-droid doctor | daemon start|status|operation|stop | session create|resume|prompt|inspect|cancel");
|
|
33
|
+
process.stdout.write(`${JSON.stringify(family === "hook" ? { ...(result.hookSpecificOutput ? { hookSpecificOutput: result.hookSpecificOutput } : {}), ...(typeof result.continue === "boolean" ? { continue: result.continue } : {}), ...(result.stopReason ? { stopReason: result.stopReason } : {}) } : { ok: true, ...result })}\n`);
|
|
34
|
+
} catch (error) { process.stderr.write(`${JSON.stringify({ ok: false, error: errorRecord(error) })}\n`); process.exitCode = process.argv[2] === "hook" ? 2 : 1; }
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { adapterTimeoutOptions } from "../lib/adapter-timeouts.mjs";
|
|
3
|
+
import { durableDaemonStart, inspectDaemonOperation, interruptDaemonOperation, settleDaemonOperation } from "../lib/daemon-operations.mjs";
|
|
4
|
+
import { hookBudget, invokeNativeHook, readNativeHookInput, writeNativeHookFailure } from "../lib/native-hook-command.mjs";
|
|
5
|
+
import { cancelSession, createSession, doctor, forkSession, inspectSession, promptFromFile, promptSession } from "../lib/dd-grok.mjs";
|
|
6
|
+
import { callDaemon, serveDaemon, startDaemon, stopDaemon } from "../lib/dd-grok-daemon.mjs";
|
|
7
|
+
import { errorRecord } from "../lib/operation-errors.mjs";
|
|
8
|
+
|
|
9
|
+
function parse(argv) { const positional = []; const options = {}; for (let index = 0; index < argv.length; index += 1) { const token = argv[index]; if (!token.startsWith("--")) { positional.push(token); continue; } const key = token.slice(2); if (["json", "cancel-tree", "no-flow"].includes(key)) { options[key] = true; continue; } const value = argv[++index]; if (value === undefined) throw new Error(`--${key} requires a value`); options[key] = value; } return { positional, options }; }
|
|
10
|
+
function common(options, operation) { return { bin: options["grok-bin"], journal: options.journal, stateDir: options["state-dir"], cwd: options.cwd, sessionId: options["session-id"], model: options.model, reasoning: options.reasoning, mode: options.mode ?? "bypassPermissions", authPath: options["auth-path"], authMethodId: options["auth-method-id"], ddFlowBin: options["dd-flow-bin"], ddFlowHome: options["dd-flow-home"], projectRoot: options["project-root"], sessionArchive: options["session-archive"], noFlow: options["no-flow"] === true, ...adapterTimeoutOptions(options, operation) }; }
|
|
11
|
+
async function hook(options) {
|
|
12
|
+
const budget = hookBudget();
|
|
13
|
+
const stdin = await readNativeHookInput(process.stdin, budget); const payload = JSON.parse(stdin || "{}"); const identity = await callDaemon(options["state-dir"], "hook.resolve", { sessionId: payload.sessionId ?? payload.session_id, payload }, budget.remaining("identity"));
|
|
14
|
+
const enriched = { ...payload, _meta: { ...(payload._meta ?? {}), ddGrok: identity } }; const args = ["grok", "event", "handle", "--project-root", options["project-root"], "--json"]; const command = options["dd-flow-bin"];
|
|
15
|
+
try { return await invokeNativeHook({ bin: command, args, home: options["dd-flow-home"], payload: enriched, timeoutMs: budget.remaining("admission", 15_000) }); }
|
|
16
|
+
catch (error) {
|
|
17
|
+
if (identity.nativeHookBinding) error.details = { ...error.details, native_hook_binding: identity.nativeHookBinding };
|
|
18
|
+
try {
|
|
19
|
+
await writeNativeHookFailure(options["state-dir"], identity.nativeHookBinding, error, hookBudget(1_000, null));
|
|
20
|
+
if (identity.nativeHookBinding) await callDaemon(options["state-dir"], "hook.failed", { requestId: identity.nativeHookBinding.request_id }, 1_000);
|
|
21
|
+
} catch (storage) { process.stderr.write(`${JSON.stringify({ code: error.code, receipt_error: storage.message })}\n`); }
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
const { positional, options } = parse(process.argv.slice(2)); const [family, command, modifier] = positional; const shared = common(options, family === "session" ? command : null); let result;
|
|
28
|
+
if (family === "doctor") result = await doctor(shared);
|
|
29
|
+
else if (family === "daemon" && command === "start") result = await durableDaemonStart({ ...shared, entryPath: process.argv[1] }, startDaemon);
|
|
30
|
+
else if (family === "daemon" && command === "serve") { await serveDaemon(shared.stateDir); process.exit(0); }
|
|
31
|
+
else if (family === "daemon" && command === "status") result = await callDaemon(shared.stateDir, "daemon.status");
|
|
32
|
+
else if (family === "daemon" && command === "operation" && modifier === "interrupt") result = await interruptDaemonOperation(shared.stateDir, options["operation-id"], { control_id: options["control-id"], stop_operation_id: options["stop-operation-id"], daemon_id: options["daemon-id"], session_id: options["session-id"], evidence: options.evidence ? JSON.parse(options.evidence) : null });
|
|
33
|
+
else if (family === "daemon" && command === "operation" && modifier === "settle") result = await settleDaemonOperation(shared.stateDir, options["operation-id"]);
|
|
34
|
+
else if (family === "daemon" && command === "operation") result = await inspectDaemonOperation(shared.stateDir, options["operation-id"]);
|
|
35
|
+
else if (family === "daemon" && command === "stop") result = await stopDaemon({ stateDir: shared.stateDir, cancelTree: options["cancel-tree"], timeoutMs: shared.timeoutMs });
|
|
36
|
+
else if (family === "hook" && command === "handle") { process.stdout.write(`${JSON.stringify(await hook(options))}\n`); process.exit(0); }
|
|
37
|
+
else if (family === "session") { const params = { ...shared, ...(command === "create" || command === "prompt" ? { prompt: options["prompt-file"] ? await promptFromFile(options["prompt-file"]) : options.prompt } : {}), ...(command === "fork" ? { target: JSON.parse(options["target-json"] ?? "null") } : {}), ...(command === "archive" ? { archiveDir: options["archive-dir"] } : {}) }; if (shared.stateDir) result = await callDaemon(shared.stateDir, `session.${command === "status" ? "inspect" : command}`, params, shared.timeoutMs ?? 1_800_000); else if (command === "create") result = await createSession(params); else if (command === "prompt") result = await promptSession(params); else if (["inspect", "status", "resume"].includes(command)) result = await inspectSession(params); else if (command === "cancel") result = await cancelSession(params); else if (command === "fork") result = await forkSession(params); else throw new Error(`unknown session command: ${command}`); }
|
|
38
|
+
else throw new Error("usage: dd-grok doctor | daemon start|status|stop | session create|prompt|inspect|status|resume|cancel|fork|archive [options] --json");
|
|
39
|
+
process.stdout.write(`${JSON.stringify({ ok: true, ...result })}\n`);
|
|
40
|
+
} catch (error) { if (process.argv[2] === "hook") { process.stderr.write(`${JSON.stringify({ native_hook_failure: errorRecord(error), bound: Boolean(error.details?.native_hook_binding) })}\n`); process.stdout.write(`${JSON.stringify({ decision: "deny", reason: error.message })}\n`); process.exit(2); } const failure = errorRecord(error); process.stderr.write(`${JSON.stringify({ ok: false, error: failure.message, ...failure })}\n`); process.exit(1); }
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { adapterTimeoutOptions } from "../lib/adapter-timeouts.mjs";
|
|
3
|
+
import { durableDaemonStart, inspectDaemonOperation, interruptDaemonOperation, settleDaemonOperation } from "../lib/daemon-operations.mjs";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { callDaemon, serveDaemon, startDaemon, stopDaemon } from "../lib/dd-opencode-daemon.mjs";
|
|
6
|
+
|
|
7
|
+
function parse(argv) { const positional = [], options = {}; for (let i = 0; i < argv.length; i += 1) { const token = argv[i]; if (!token.startsWith("--")) { positional.push(token); continue; } const key = token.slice(2); if (["json","cancel-tree","no-flow"].includes(key)) options[key] = true; else { if (argv[i + 1] === undefined) throw new Error(`--${key} requires a value`); options[key] = argv[++i]; } } return { positional, options }; }
|
|
8
|
+
const prompt = async options => options["prompt-file"] ? await readFile(options["prompt-file"], "utf8") : options.prompt;
|
|
9
|
+
try {
|
|
10
|
+
const { positional, options } = parse(process.argv.slice(2)), [family, command, modifier] = positional; const common = { journal: options.journal, stateDir: options["state-dir"], sessionId: options["session-id"], cwd: options.cwd, bin: options["opencode-bin"], provider: options.provider, model: options.model, variant: options.variant, agent: options.agent, authPath: options["auth-path"], projectRoot: options["project-root"], ddFlowBin: options["dd-flow-bin"], ddFlowHome: options["dd-flow-home"], noFlow: options["no-flow"] === true, sessionArchive: options["session-archive"], ...adapterTimeoutOptions(options, family === "session" ? command : null) }; let result;
|
|
11
|
+
if (family === "daemon" && command === "start") result = await durableDaemonStart({ ...common, entryPath: process.argv[1] }, startDaemon);
|
|
12
|
+
else if (family === "daemon" && command === "serve") { await serveDaemon(common.stateDir); process.exit(0); }
|
|
13
|
+
else if (family === "daemon" && command === "status") result = await callDaemon(common.stateDir, "daemon.status");
|
|
14
|
+
else if (family === "daemon" && command === "operation" && modifier === "interrupt") result = await interruptDaemonOperation(common.stateDir, options["operation-id"], { control_id: options["control-id"], stop_operation_id: options["stop-operation-id"], daemon_id: options["daemon-id"], session_id: options["session-id"], evidence: options.evidence ? JSON.parse(options.evidence) : null });
|
|
15
|
+
else if (family === "daemon" && command === "operation" && modifier === "settle") result = await settleDaemonOperation(common.stateDir, options["operation-id"]);
|
|
16
|
+
else if (family === "daemon" && command === "operation") result = await inspectDaemonOperation(common.stateDir, options["operation-id"]);
|
|
17
|
+
else if (family === "doctor") result = await callDaemon(common.stateDir, "daemon.doctor");
|
|
18
|
+
else if (family === "daemon" && command === "stop") result = await stopDaemon({ stateDir: common.stateDir, cancelTree: options["cancel-tree"], timeoutMs: common.timeoutMs });
|
|
19
|
+
else if (family === "session") { const operation = command === "status" ? "inspect" : command; const params = { livenessTimeoutMs: common.livenessTimeoutMs, sessionId: options["session-id"], title: options.title, messageId: options["message-id"], archiveFile: options["archive-file"], ...(command === "prompt" ? { prompt: await prompt(options) } : {}) }; result = await callDaemon(common.stateDir, `session.${operation}`, params, common.timeoutMs ?? 1_800_000); }
|
|
20
|
+
else throw new Error("usage: dd-opencode daemon start|status|stop | session create|prompt|inspect|fork|cancel|archive [options] --json");
|
|
21
|
+
process.stdout.write(`${JSON.stringify({ ok: true, ...result })}\n`);
|
|
22
|
+
} catch (error) { process.stderr.write(`${JSON.stringify({ ok: false, error: error.message, ...(error.code ? { code: error.code, retryable: error.retryable === true, details: error.details } : {}) })}\n`); process.exit(1); }
|