@north-light/cli 0.3.694 → 0.3.696
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 +4 -7
- package/dist/api/command-manifest/result.d.ts +5 -5
- package/dist/api/command-manifest/result.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/run-events.d.ts +1 -0
- package/dist/api/dto/run-events.js +1 -0
- package/dist/api/dto/worktree.d.ts +0 -4
- package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
- package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
- package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
- package/dist/builtin-memory/crouter-sdk/README.md +14 -42
- package/dist/builtin-memory/crouter-sdk/client.md +5 -7
- package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
- package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
- package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
- package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
- package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
- package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
- package/dist/clients/attach/session/connection.d.ts +11 -2
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/keys.d.ts +2 -0
- package/dist/clients/attach/session/keys.js +1 -1
- package/dist/clients/attach/session/pane-tag.d.ts +3 -3
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/viewer.js +539 -538
- package/dist/commands/node-worktree.js +1 -1
- package/dist/commands/surface/node/placement.d.ts +2 -2
- package/dist/commands/surface/node/placement.js +1 -1
- package/dist/commands/surface.js +1 -1
- package/dist/core/broker-client/client.d.ts +6 -9
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/broker-client/transport-relay.d.ts +12 -1
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/canvas/canvas.js +5 -5
- package/dist/core/canvas/types.d.ts +0 -2
- package/dist/core/conversation-store/row-store.js +10 -10
- package/dist/core/graph/names.js +9 -9
- package/dist/core/keybindings/attach-control.d.ts +3 -0
- package/dist/core/keybindings/attach-control.js +1 -1
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/ledger/chunks.d.ts +3 -1
- package/dist/core/ledger/chunks.js +2 -2
- package/dist/core/ledger/index.d.ts +1 -1
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/read.d.ts +4 -0
- package/dist/core/ledger/read.js +2 -2
- package/dist/core/llm/run.js +2 -2
- package/dist/core/logged-step-timings.d.ts +7 -0
- package/dist/core/logged-step-timings.js +1 -0
- package/dist/core/permissions/evaluator.d.ts +2 -1
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/receipts.js +1 -1
- package/dist/core/runs/operations.js +8 -8
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/nodes.d.ts +1 -1
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +7 -13
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/machine/runner.d.ts +3 -2
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/runtime/tmux-driver.d.ts +0 -10
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/step-timings.d.ts +7 -1
- package/dist/core/step-timings.js +1 -1
- package/dist/core/worktree-close.js +4 -6
- package/dist/core/worktree-landing.d.ts +0 -38
- package/dist/core/worktree-landing.js +2 -3
- package/dist/core/worktree-sweep.d.ts +0 -1
- package/dist/core/worktree-sweep.js +4 -6
- package/dist/core/worktree.d.ts +0 -4
- package/dist/core/worktree.js +13 -15
- package/dist/daemon/api/app-listener.d.ts +1 -0
- package/dist/daemon/api/app-listener.js +10 -10
- package/dist/daemon/api/bridge.js +5 -5
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +3 -3
- package/dist/daemon/api/server.d.ts +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/cron/armed-context.js +1 -1
- package/dist/daemon/crtrd.js +20 -18
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +7 -1
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.d.ts +2 -4
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/pidfile.js +2 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
- package/dist/daemon/runs/append-section.js +2 -2
- package/dist/daemon/runs/observer.js +3 -3
- package/docs/apps/guides/stream-a-run.md +6 -7
- package/docs/concepts/lifecycle-and-wakes.md +1 -1
- package/docs/concepts/nodes-and-the-canvas.md +2 -2
- package/docs/concepts/profiles-kinds-and-modes.md +1 -1
- package/docs/concepts/scopes-and-trust.md +1 -1
- package/docs/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +13 -41
- package/docs/sdk/client.md +5 -7
- package/docs/sdk/docker.md +1 -1
- package/docs/sdk/errors.md +3 -43
- package/docs/sdk/getting-started.md +11 -83
- package/docs/sdk/release-notes.md +10 -0
- package/docs/sdk/resources.md +11 -44
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/connection.js +73 -25
- package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
- package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
- package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
- package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
- package/packages/crouter-api/dist/commands/surface.js +2 -3
- package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
- package/packages/crouter-api/dist/core/canvas/canvas.js +2 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
- package/packages/crouter-api/dist/core/graph/names.js +7 -20
- package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
- package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
- package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
- package/packages/crouter-api/dist/core/ledger/index.js +1 -1
- package/packages/crouter-api/dist/core/ledger/read.js +18 -1
- package/packages/crouter-api/dist/core/llm/run.js +1 -1
- package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
- package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
- package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
- package/packages/crouter-api/dist/core/runs/operations.js +5 -4
- package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
- package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
- package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +14 -32
- package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
- package/packages/crouter-api/dist/core/step-timings.js +7 -2
- package/packages/crouter-api/dist/core/worktree-close.js +5 -51
- package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
- package/packages/crouter-api/dist/core/worktree.js +9 -74
- package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +22 -10
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +7 -0
- package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
- package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
- package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/serve.js +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/self-update.mjs +7 -3
- package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
- package/dist/builtin-memory/crouter-sdk/files.md +0 -50
- package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
- package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
- package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
- package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
- package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
- package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
- package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
- package/dist/commands/surface-reload.d.ts +0 -7
- package/dist/commands/surface-reload.js +0 -1
- package/docs/sdk/bash.md +0 -39
- package/docs/sdk/files.md +0 -49
- package/docs/sdk/guides/README.md +0 -17
- package/docs/sdk/guides/event-driven-assistant.md +0 -24
- package/docs/sdk/guides/fan-out-pipeline.md +0 -24
- package/docs/sdk/guides/human-approval.md +0 -24
- package/docs/sdk/guides/typed-extraction.md +0 -24
- package/docs/sdk/nodes.md +0 -194
- package/docs/sdk/streaming.md +0 -149
- package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// logged-step-timings.ts — step timings of a request nobody on the calling side reads (the broker's conversation POST, the machine link, a viewer's
|
|
2
|
+
// WebSocket upgrade), written to the process's own event log as one `daemon.timing.<name>` event. Same recorder as step-timings.ts, so the same
|
|
3
|
+
// `timedStep` / `addStepTiming` calls feed both the `Server-Timing` header and this log. Names, durations in ms and byte counts only.
|
|
4
|
+
// Read on the machine that ran it: `crtr sys logs --component daemon --pattern daemon.timing.`
|
|
5
|
+
import { emitEvent } from './events/emit.js';
|
|
6
|
+
import { addStepTiming, collectStepTimings, receiptOf, sinceCollectionStart } from './step-timings.js';
|
|
7
|
+
/** Run `fn`, then log every step recorded beneath it as `daemon.timing.<name>`. `duration_ms` runs from when the listener received `req` to the end of `fn`;
|
|
8
|
+
* `handler_ms` is `fn` alone, `auth_ms` is receipt to the end of authentication. A step named `refused_status` marks a refused upgrade as failed. `fields` are identifiers and counts. */
|
|
9
|
+
export async function withLoggedStepTimings(name, fields, req, fn) {
|
|
10
|
+
const { receivedAt, authenticatedAt } = receiptOf(req);
|
|
11
|
+
const start = performance.now();
|
|
12
|
+
const steps = [];
|
|
13
|
+
let threw = true;
|
|
14
|
+
try {
|
|
15
|
+
const value = await collectStepTimings(fn, steps).then((collected) => collected.value);
|
|
16
|
+
threw = false;
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
const end = performance.now();
|
|
21
|
+
const stepFields = {
|
|
22
|
+
...(authenticatedAt === undefined ? {} : { auth_ms: authenticatedAt - receivedAt, authenticated_to_handler_ms: start - authenticatedAt }),
|
|
23
|
+
receive_to_handler_ms: start - receivedAt,
|
|
24
|
+
handler_ms: end - start,
|
|
25
|
+
};
|
|
26
|
+
for (const [step, ms] of steps) {
|
|
27
|
+
let key = step;
|
|
28
|
+
for (let n = 2; key in stepFields; n++)
|
|
29
|
+
key = `${step}_${n}`;
|
|
30
|
+
stepFields[key] = ms;
|
|
31
|
+
}
|
|
32
|
+
for (const key of Object.keys(stepFields))
|
|
33
|
+
stepFields[key] = Math.round(stepFields[key] * 10) / 10;
|
|
34
|
+
const failed = threw || steps.some(([step]) => step === 'refused_status');
|
|
35
|
+
emitEvent({ level: 'info', event: `daemon.timing.${name}`, duration_ms: end - receivedAt, outcome: failed ? 'failed' : 'succeeded', fields: { ...fields, ...stepFields } });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Run `fn` and record when it began (ms since collection began, `<name>_begin_at`) and how long it took (`<name>_ms`), whether it returns or throws. */
|
|
39
|
+
export async function timedSpan(name, fn) {
|
|
40
|
+
addStepTiming(`${name}_begin_at`, sinceCollectionStart());
|
|
41
|
+
const start = performance.now();
|
|
42
|
+
try {
|
|
43
|
+
return await fn();
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
addStepTiming(`${name}_ms`, performance.now() - start);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Record that a point was reached: ms since collection began, as `<name>_at`. */
|
|
50
|
+
export function markAt(name) {
|
|
51
|
+
addStepTiming(`${name}_at`, sinceCollectionStart());
|
|
52
|
+
}
|
|
@@ -73,11 +73,25 @@ export async function permits(db, reader, permission, alias = 'o', options = {})
|
|
|
73
73
|
}
|
|
74
74
|
const schemaPart = cases.length === 0 ? f `(CASE WHEN ${raw(alias)}.schema_type IS NULL THEN ${builtin} ELSE FALSE END)`
|
|
75
75
|
: f `(CASE WHEN ${raw(alias)}.schema_type IS NULL THEN ${builtin} ${{ sql: cases.map((c) => c.sql).join(' '), params: cases.flatMap((c) => c.params) }} ELSE FALSE END)`;
|
|
76
|
-
const ceiling = await
|
|
76
|
+
const ceiling = await ceilingOf(db, ev, ACCESS[permission], options);
|
|
77
77
|
if (ceiling === null)
|
|
78
78
|
return schemaPart;
|
|
79
79
|
return and([ceilingFrag(ceiling, alias), schemaPart]);
|
|
80
80
|
}
|
|
81
|
+
const ceilings = new WeakMap();
|
|
82
|
+
export function ceilingOf(db, ev, access, options = {}) {
|
|
83
|
+
let m = ceilings.get(ev.reader);
|
|
84
|
+
if (m === undefined)
|
|
85
|
+
ceilings.set(ev.reader, m = new Map());
|
|
86
|
+
const k = `${access} ${options.verb ?? ''} ${ev.userId} ${ev.subjects.groupIds.join(',')}`;
|
|
87
|
+
let c = m.get(k);
|
|
88
|
+
if (c === undefined) {
|
|
89
|
+
c = resolveCeiling(db, ev.reader, ev.userId, access, options);
|
|
90
|
+
m.set(k, c);
|
|
91
|
+
c.catch(() => m.delete(k));
|
|
92
|
+
}
|
|
93
|
+
return c;
|
|
94
|
+
}
|
|
81
95
|
async function ownNamespaceTypes(db, appObjectId) {
|
|
82
96
|
const rows = await db.prepare(`SELECT s.namespace FROM schemas s JOIN identities i ON i.external_id = s.app AND i.scheme = 'app' WHERE i.object = ?`).all(appObjectId);
|
|
83
97
|
return new Set(rows.map((r) => r.namespace));
|
|
@@ -41,20 +41,9 @@ export async function acceptProviderReceipt(value, call) {
|
|
|
41
41
|
await withCanvasWrite(async (db) => {
|
|
42
42
|
for (const receipt of accepted) {
|
|
43
43
|
// One row per receipt, keyed by (provider, receipt id): a repeat delivery writes nothing and adds nothing.
|
|
44
|
-
|
|
44
|
+
await writeCharge({ id: receiptChargeId(call.provider, receipt.receipt_id), request: call.request_id, kind: 'tool', what: `${call.provider}:${call.tool}`,
|
|
45
45
|
units: { units: receipt.units, unit: receipt.unit }, usd: receipt.usd_equivalent, payer: call.payer, funding: call.funding, sub: call.sub,
|
|
46
46
|
grantee: call.ledger_grantee ?? call.grantee, node: call.node_id, run: call.run_id, provider: `app:${call.provider}`, causedBy: call.caused_by, vendorRef: receipt.receipt_id });
|
|
47
|
-
if (!written)
|
|
48
|
-
continue;
|
|
49
|
-
if (!call.run_id)
|
|
50
|
-
continue;
|
|
51
|
-
const root = await db.prepare('SELECT usage_json FROM nodes WHERE node_id = ? AND run_id = ?')
|
|
52
|
-
.get(call.run_id, call.run_id);
|
|
53
|
-
if (!root)
|
|
54
|
-
continue;
|
|
55
|
-
const usage = root.usage_json ? JSON.parse(root.usage_json) : {};
|
|
56
|
-
usage['cost_usd'] = (typeof usage['cost_usd'] === 'number' ? usage['cost_usd'] : 0) + receipt.usd_equivalent;
|
|
57
|
-
await db.prepare('UPDATE nodes SET usage_json = ? WHERE node_id = ?').run(JSON.stringify(usage), call.run_id);
|
|
58
47
|
}
|
|
59
48
|
});
|
|
60
49
|
return accepted[0].receipt_id;
|
|
@@ -34,6 +34,8 @@ import { isPortableModelToken } from '../runtime/launch.js';
|
|
|
34
34
|
import { parseDurationMs } from '../wake.js';
|
|
35
35
|
import { expandModelCandidates, parseModelSpec } from '../model-routes.js';
|
|
36
36
|
import { payerOfGrant } from '../grants/mirror.js';
|
|
37
|
+
import { runUsage } from '../ledger/read.js';
|
|
38
|
+
import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
|
|
37
39
|
import { isolatedBrokerLauncherAvailable } from '../runtime/host.js';
|
|
38
40
|
import { blaxelEnvironmentOf } from '../runtime/blaxel-environment.js';
|
|
39
41
|
import { resolveRunKind, resolveRunModel } from '../runtime/launch-target.js';
|
|
@@ -80,7 +82,6 @@ export class RunError extends Error {
|
|
|
80
82
|
}
|
|
81
83
|
const invalid = (message, param) => new RunError(400, 'invalid_request', message, param);
|
|
82
84
|
const missing = () => new RunError(404, 'not_found', 'run not found');
|
|
83
|
-
const usage = () => ({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 });
|
|
84
85
|
const db = async () => await openDb();
|
|
85
86
|
export async function ownedRun(id, grantee, allowDeleting = false) {
|
|
86
87
|
const node = await getNode(id);
|
|
@@ -139,7 +140,7 @@ export async function runObject(root) {
|
|
|
139
140
|
...(result === undefined ? {} : { result }),
|
|
140
141
|
...(report !== undefined ? { last_report: report } : {}), ...(recap ? { recap } : {}), pending_question_ids: pending, open_notice_ids: status === 'settled' ? [] : await openNoticeIds(root.node_id),
|
|
141
142
|
...(root.last_turn_error_json ? { last_turn_error: JSON.parse(root.last_turn_error_json) } : {}),
|
|
142
|
-
usage:
|
|
143
|
+
usage: await runUsage(root.node_id), payer: await payerOfGrant(root.grant_id), scopes: root.scopes,
|
|
143
144
|
metadata: root.metadata_json ? JSON.parse(root.metadata_json) : {}, created_at: root.created,
|
|
144
145
|
...(status === 'settled' && root.outcome_at ? { settled_at: root.outcome_at } : {}), latest_sequence: (root.event_cursor ?? 1) - 1,
|
|
145
146
|
last_activity_at: root.last_activity_at, activity: await runActivity(root.node_id, status),
|
|
@@ -335,7 +336,7 @@ export async function startRun(principal, input, idempotencyKey, resolveAttachme
|
|
|
335
336
|
...(input.deadline === undefined ? {} : { deadlineAt: new Date(Date.now() + parseRunDeadlineMs(input.deadline)).toISOString() }),
|
|
336
337
|
...(input.scopes === null ? {} : { scopes: input.scopes }),
|
|
337
338
|
run: { grantee: principal.grantee, sub: principal.sub, grant_id: principal.grant, client_id: principal.client_id,
|
|
338
|
-
metadata_json: JSON.stringify(input.metadata), run_id: runId, event_cursor: 1
|
|
339
|
+
metadata_json: JSON.stringify(input.metadata), run_id: runId, event_cursor: 1 },
|
|
339
340
|
withinCreate: async (tx, row) => {
|
|
340
341
|
// A concurrent start under this key may have committed while this one fetched attachments and awaited the
|
|
341
342
|
// spawn: re-check on the transaction before any write, so exactly one start creates the run.
|
|
@@ -351,7 +352,7 @@ export async function startRun(principal, input, idempotencyKey, resolveAttachme
|
|
|
351
352
|
await insertUploadUses(uses.map(({ upload_id, path, blob_key }) => ({ upload_id, path, blob_key, run_id: runId })), tx);
|
|
352
353
|
}
|
|
353
354
|
response = { run_id: runId, node_id: runId, grantee: principal.grantee, grant: principal.grant, rev: principal.rev, scopes: input.scopes, payer, status: 'running', created_at: row.created, metadata: input.metadata, sequence_number: 0 };
|
|
354
|
-
await appendRunEvent(tx, runId, runId, 'run.started', { scopes: input.scopes, payer, usage:
|
|
355
|
+
await appendRunEvent(tx, runId, runId, 'run.started', { scopes: input.scopes, payer, usage: ZERO_RUN_USAGE });
|
|
355
356
|
if (firstMessage) {
|
|
356
357
|
const accepted = await acceptRunMessage(tx, runId, principal.grantee, principal.sub, firstMessage, false);
|
|
357
358
|
response.message = { run_id: runId, message_id: accepted.messageId, sequence_number: accepted.sequence };
|
|
@@ -179,6 +179,15 @@ function parseRefusal(value) {
|
|
|
179
179
|
throw new Error('llm returned an invalid refusal');
|
|
180
180
|
return error;
|
|
181
181
|
}
|
|
182
|
+
/** A model-call answer that is not JSON (an HTML error page from a server in between) means the model service is unavailable, which is retried. */
|
|
183
|
+
function parseAnswer(text) {
|
|
184
|
+
try {
|
|
185
|
+
return JSON.parse(text);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
throw new UpstreamModelUnavailableError(`llm returned a non-JSON answer: ${text.slice(0, 120)}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
182
191
|
/** `Crtr-Caused-By: message:<id>` for the turn running now; nothing when the turn has no input message. */
|
|
183
192
|
/** `/v1/llm` at `CRTR_API_URL` (the control plane, from a sandbox) or on the local API socket. */
|
|
184
193
|
function llmUrl() {
|
|
@@ -280,8 +289,10 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
|
|
|
280
289
|
});
|
|
281
290
|
const response = await unwrapDeferredHead(fetched);
|
|
282
291
|
if (!response.ok) {
|
|
283
|
-
|
|
284
|
-
|
|
292
|
+
if (response.status === 413)
|
|
293
|
+
throw contextTooLargeError(bytes, MODEL_CONTEXT_BODY_MAX_BYTES);
|
|
294
|
+
const error = parseRefusal(parseAnswer(await response.text()));
|
|
295
|
+
if (error.code === 'payload_too_large')
|
|
285
296
|
throw contextTooLargeError(bytes, MODEL_CONTEXT_BODY_MAX_BYTES);
|
|
286
297
|
applyServedModel(message, refusalRoute(error));
|
|
287
298
|
if (error.retryable !== true)
|
|
@@ -318,7 +329,7 @@ export function streamBrokerModel(model, context, options = {}, intent, causedBy
|
|
|
318
329
|
let receivedUsage = false;
|
|
319
330
|
let receivedServedModel = false;
|
|
320
331
|
const apply = (line) => {
|
|
321
|
-
const chunk =
|
|
332
|
+
const chunk = parseAnswer(line);
|
|
322
333
|
if (chunk.error) {
|
|
323
334
|
// An error after headers still names the route that was serving: the
|
|
324
335
|
// errored turn, and the fault recorded from it, belong to that route.
|
|
@@ -18,6 +18,7 @@ import { activeGrant, terminalGrant } from '../grants/mirror.js';
|
|
|
18
18
|
import { callerPerson, nodeTerminalGrant } from '../grants/terminal.js';
|
|
19
19
|
import { grantSnapshotMissing } from '../../daemon/readiness.js';
|
|
20
20
|
import { appendRunEvent } from '../runs/events.js';
|
|
21
|
+
import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
|
|
21
22
|
import { isCloudRole, personId } from '../canvas/person.js';
|
|
22
23
|
import { InputError } from '../io.js';
|
|
23
24
|
import { ApiError } from '../../api/errors.js';
|
|
@@ -319,7 +320,6 @@ export async function spawnNode(opts) {
|
|
|
319
320
|
metadata_json: isRoot ? opts.run?.metadata_json ?? null : null,
|
|
320
321
|
run_id: isRoot ? nodeId : opts.run?.run_id ?? null,
|
|
321
322
|
event_cursor: isRoot ? opts.run?.event_cursor ?? 1 : null,
|
|
322
|
-
usage_json: isRoot ? opts.run?.usage_json ?? JSON.stringify({ input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, cost_usd: 0 }) : null,
|
|
323
323
|
passive_default: opts.passiveDefault ?? false,
|
|
324
324
|
caused_by: opts.causedBy ?? null,
|
|
325
325
|
...(opts.managedWorktree !== undefined ? { managed_worktree: opts.managedWorktree } : {}),
|
|
@@ -494,7 +494,7 @@ export async function spawnNode(opts) {
|
|
|
494
494
|
if (row.run_id && row.run_id !== row.node_id)
|
|
495
495
|
await assertRunNotDeleting(db, row.run_id);
|
|
496
496
|
if (isRoot && opts.run === undefined)
|
|
497
|
-
await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: 'user', usage:
|
|
497
|
+
await appendRunEvent(db, nodeId, nodeId, 'run.started', { scopes: row.scopes ?? null, payer: 'user', usage: ZERO_RUN_USAGE });
|
|
498
498
|
await opts.withinCreate?.(db, row);
|
|
499
499
|
await recordBirth(db, row);
|
|
500
500
|
} }));
|
|
@@ -20,7 +20,7 @@ import { paneLocation, ensureSession, openNodeWindow, splitWindow, selectLayout,
|
|
|
20
20
|
import { BROKER_VIEW_SOCKET_WAIT_MS } from './view-socket.js';
|
|
21
21
|
// Re-export the pure tmux driver verbs the CLI/viewer consumers need without
|
|
22
22
|
// exposing the canvas focuses table or sending command modules to the raw driver.
|
|
23
|
-
export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground,
|
|
23
|
+
export { paneExists, paneLocation, paneOfNode, paneCurrentPath, paneSize, paneRunning, ensureSession, openNodeWindow, splitWindow, closePane, currentTmux, switchClient, selectWindow, selectLayout, selectPane, getPaneOption, setPaneOption, breakPane, inTmux, piCommand, shellQuote, renameWindow, displayPopup, displayPopupAsync, windowOfPane, respawnPaneSync, respawnPaneInBackground, runShellInBackground, paneStartCommand, swapPanes, paneCurrentCommand, closeWindow, windowAlive, listLivePanes, VIEWER_STAMP_OPTION, stampViewerPaneAsync, liveViewerPanes, sendAttachControl, displayClientMessage, displayMessage, windowIndex, sessionExists, tmuxAvailable, tmuxInteractive, } from './tmux-driver.js';
|
|
24
24
|
export { installTmuxBindings } from './tmux-bindings.js';
|
|
25
25
|
// view.sock readiness — the one shared broker-cold-start primitive
|
|
26
26
|
export { BROKER_VIEW_SOCKET_WAIT_MS, waitForBrokerViewSocket } from './view-socket.js';
|
|
@@ -42,7 +42,7 @@ import { isCloudRole } from '../canvas/person.js';
|
|
|
42
42
|
import { asNodePerson } from '../../daemon/reconcilers/node-lifecycle/node-person.js';
|
|
43
43
|
import { processRunner } from './runner/process.js';
|
|
44
44
|
import { runnerForEnvironment } from './runner/index.js';
|
|
45
|
-
import {
|
|
45
|
+
import { MachineOfflineError } from './runner/machine/ops.js';
|
|
46
46
|
import { blaxelEnvironmentOf } from './blaxel-environment.js';
|
|
47
47
|
import { recordLaunchFailure } from '../../daemon/reconcilers/node-lifecycle/launch-failure.js';
|
|
48
48
|
import { acceptedRelease, remoteMachineEnvironmentOf, checkBilledWake, EnvironmentImagePending, imageForWake } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
|
|
@@ -679,7 +679,7 @@ async function launchRevive(nodeId, meta, opts) {
|
|
|
679
679
|
}
|
|
680
680
|
}
|
|
681
681
|
catch (error) {
|
|
682
|
-
// A machine
|
|
682
|
+
// A machine call that failed (offline, or sent and unanswered) does not crash the node; the caller leaves it dormant with its mail pending (the outer catch ends the execution).
|
|
683
683
|
if (error instanceof MachineOfflineError)
|
|
684
684
|
throw error;
|
|
685
685
|
try {
|
|
@@ -734,9 +734,9 @@ async function launchRevive(nodeId, meta, opts) {
|
|
|
734
734
|
};
|
|
735
735
|
}
|
|
736
736
|
catch (error) {
|
|
737
|
-
// A
|
|
738
|
-
// tick asks `status` of
|
|
739
|
-
if (error instanceof
|
|
737
|
+
// A start sent to the Mac and unanswered leaves its execution launching: the Mac may have spawned the broker, and the lifecycle
|
|
738
|
+
// tick's `recoverLaunching` asks `status` of it once the link is back (running is adopted, gone is ended).
|
|
739
|
+
if (error instanceof MachineOfflineError && error.sent)
|
|
740
740
|
throw error;
|
|
741
741
|
await abortExecution(executionId, { reason: 'launch_failed' });
|
|
742
742
|
// Best effort after the exit transition: a failed diagnostic write must neither leave the row live nor replace the launch error.
|
|
@@ -5,6 +5,7 @@ export class MachineOfflineError extends Error {
|
|
|
5
5
|
environmentId;
|
|
6
6
|
sent;
|
|
7
7
|
code = 'machine_offline';
|
|
8
|
+
status = 503;
|
|
8
9
|
/** True when the call was written to the link before it dropped: the machine may have run it. False: it ran nowhere. */
|
|
9
10
|
constructor(environmentId, detail, sent = false) {
|
|
10
11
|
super(`machine ${environmentId} is offline${detail ? `: ${detail}` : ''}`);
|
|
@@ -12,13 +13,7 @@ export class MachineOfflineError extends Error {
|
|
|
12
13
|
this.sent = sent;
|
|
13
14
|
}
|
|
14
15
|
}
|
|
15
|
-
/**
|
|
16
|
-
* and never starts another. After the link returns `status` of that execution decides: running is adopted, gone is ended. */
|
|
17
|
-
export class MachineLaunchUncertainError extends MachineOfflineError {
|
|
18
|
-
uncertain = true;
|
|
19
|
-
constructor(environmentId, detail) { super(environmentId, detail, true); }
|
|
20
|
-
}
|
|
21
|
-
/** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The caller runs `status` before a new `start`. */
|
|
16
|
+
/** The holder claimed the call and never answered before its lease expired: the call may or may not have run. The machine runner reports a lost `start` as offline after send. */
|
|
22
17
|
export class MachineLostError extends Error {
|
|
23
18
|
environmentId;
|
|
24
19
|
callId;
|
|
@@ -1,15 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
// profile's environment is kind `machine` and that machine is not this process's own host. Every method is one `callMachine`
|
|
3
|
-
// to the Mac over its link; the Mac executes it with `machine/executor.ts`.
|
|
4
|
-
//
|
|
5
|
-
// The node token is minted HERE, in the control plane (the Mac has no database to mint it in) and travels in the `start` call.
|
|
6
|
-
// `wake` and `stop` throw `machine_offline` untouched where the caller can wait; `stop` and `status` fold a failed call into
|
|
7
|
-
// `confirmed: false` / `unknown` as the runner interface requires (the caller leaves everything as it is and retries).
|
|
1
|
+
import { getNode } from '../../../canvas/canvas.js';
|
|
8
2
|
import { openDb } from '../../../canvas/db.js';
|
|
3
|
+
import { personIdAsync } from '../../../canvas/person.js';
|
|
9
4
|
import { mintExecutionToken } from '../../../canvas/node-tokens.js';
|
|
10
5
|
import { callMachine } from './call.js';
|
|
11
6
|
import { machineEnvironmentOfProfile } from './environment.js';
|
|
12
|
-
import {
|
|
7
|
+
import { MachineLostError, MachineOfflineError } from './ops.js';
|
|
13
8
|
/** The machine environment of a node's profile, or null when the profile points at no machine environment. */
|
|
14
9
|
export async function machineEnvironmentOfNode(nodeId) {
|
|
15
10
|
const row = await (await openDb()).prepare('SELECT profile_id FROM nodes WHERE node_id = ?').get(nodeId);
|
|
@@ -21,7 +16,12 @@ const defaultEnvironmentOf = async (nodeId) => {
|
|
|
21
16
|
throw new Error(`node ${nodeId} has no machine environment`);
|
|
22
17
|
return environment;
|
|
23
18
|
};
|
|
24
|
-
const
|
|
19
|
+
const defaultBundle = async (input) => {
|
|
20
|
+
// Loaded here: the handler imports the runtime that imports this module.
|
|
21
|
+
const { buildStartBundle } = await import('../../../../daemon/api/handlers/execution-start.js');
|
|
22
|
+
const node = await getNode(input.nodeId);
|
|
23
|
+
return await buildStartBundle({ nodeId: input.nodeId, app: node?.grantee ?? 'app:terminal', sub: node?.sub ?? await personIdAsync(), launchJson: input.launchJson, runner: 'machine' });
|
|
24
|
+
};
|
|
25
25
|
const asError = (error) => error instanceof Error ? error : new Error(String(error));
|
|
26
26
|
export function createMachineRunner(deps = {}) {
|
|
27
27
|
const environmentOf = deps.environmentOf ?? defaultEnvironmentOf;
|
|
@@ -29,34 +29,16 @@ export function createMachineRunner(deps = {}) {
|
|
|
29
29
|
kind: 'machine',
|
|
30
30
|
async start(input) {
|
|
31
31
|
const environment = await environmentOf(input.nodeId);
|
|
32
|
-
const
|
|
33
|
-
const uncertain = (why) => new MachineLaunchUncertainError(environment, `the launch of execution ${input.executionId} is unconfirmed: ${why}`);
|
|
34
|
-
// `status` of THIS execution decides. A repeated start (a reconciler whose lease was taken, a start whose answer was lost) finds the
|
|
35
|
-
// broker of this execution and adopts it. A token is never minted twice for one execution (D75): one that exists means a start was
|
|
36
|
-
// already handed over, so what is left to learn is whether its broker exists.
|
|
37
|
-
const handedOver = await tokenMinted(input.executionId);
|
|
38
|
-
let status;
|
|
39
|
-
try {
|
|
40
|
-
status = await callMachine(environment, 'status', { execution: input });
|
|
41
|
-
}
|
|
42
|
-
catch (error) {
|
|
43
|
-
if (handedOver && (error instanceof MachineOfflineError || error instanceof MachineLostError))
|
|
44
|
-
throw uncertain('the machine could not be asked');
|
|
45
|
-
throw error;
|
|
46
|
-
}
|
|
47
|
-
if (status.state === 'running')
|
|
48
|
-
return { pid: status.pid, exited: null };
|
|
49
|
-
if (handedOver)
|
|
50
|
-
throw uncertain('a start was handed over and no broker is running yet');
|
|
32
|
+
const bundle = await (deps.bundle ?? defaultBundle)(input);
|
|
51
33
|
const nodeToken = await (deps.mintToken ?? ((i) => mintExecutionToken(i.executionId, i.nodeId)))(input);
|
|
52
34
|
try {
|
|
53
|
-
const result = await callMachine(environment, 'start', { ...input, nodeToken });
|
|
35
|
+
const result = await callMachine(environment, 'start', { ...input, nodeToken, bundle });
|
|
54
36
|
return { pid: result.pid, exited: null };
|
|
55
37
|
}
|
|
56
38
|
catch (error) {
|
|
57
|
-
// Sent and unanswered (the
|
|
58
|
-
if (error instanceof MachineLostError
|
|
59
|
-
throw
|
|
39
|
+
// Sent and unanswered (the lease ran out): the Mac may have spawned the broker, so it is offline-after-send and the execution stays launching.
|
|
40
|
+
if (error instanceof MachineLostError)
|
|
41
|
+
throw new MachineOfflineError(environment, error.message, true);
|
|
60
42
|
throw error;
|
|
61
43
|
}
|
|
62
44
|
},
|
|
@@ -49,7 +49,7 @@ const LEAF_MENU_ACTIONS = {
|
|
|
49
49
|
'crtr.tmux.menu.graph': { description: 'canvas graph', action: { kind: 'keys', keys: '/graph' } },
|
|
50
50
|
'crtr.tmux.menu.focus-manager': { description: 'go to manager', action: { kind: 'command', run: 'surface node focus {manager}' } },
|
|
51
51
|
'crtr.tmux.menu.copy-id': { description: 'copy node id', action: { kind: 'direct', run: 'surface node id --pane {pane}' } },
|
|
52
|
-
'crtr.tmux.menu.reload-viewer': { description: 'reload viewer', action: { kind: '
|
|
52
|
+
'crtr.tmux.menu.reload-viewer': { description: 'reload viewer', action: { kind: 'literal-input', input: encodeAttachControlInput('crtr.attach.reload-viewer') } },
|
|
53
53
|
'crtr.tmux.menu.recap': { description: 'generate recap', action: { kind: 'keys', keys: '/recap' } },
|
|
54
54
|
'crtr.tmux.menu.pin': { description: 'pin conversation', action: { kind: 'direct', run: 'surface node pin --pane {pane}' } },
|
|
55
55
|
'crtr.tmux.menu.issue.idea': { description: 'idea', action: { kind: 'popup', run: 'canvas issue new --type idea' } },
|
|
@@ -624,24 +624,6 @@ export function paneCurrentCommand(pane) {
|
|
|
624
624
|
const r = tmux(['display-message', '-p', '-t', pane, '#{pane_current_command}']);
|
|
625
625
|
return r.ok && r.stdout !== '' ? r.stdout : undefined;
|
|
626
626
|
}
|
|
627
|
-
/** The pane's root process pid (`#{pane_pid}`) — the process tmux launched in
|
|
628
|
-
* the pane (the viewer itself, or the login shell hosting it). undefined when
|
|
629
|
-
* tmux is unreachable or the pane is gone. */
|
|
630
|
-
export function panePid(pane) {
|
|
631
|
-
const r = tmux(['display-message', '-p', '-t', pane, '#{pane_pid}']);
|
|
632
|
-
if (!r.ok)
|
|
633
|
-
return undefined;
|
|
634
|
-
const pid = Number.parseInt(r.stdout, 10);
|
|
635
|
-
return Number.isInteger(pid) && pid > 0 ? pid : undefined;
|
|
636
|
-
}
|
|
637
|
-
/** Kill a pane's current process and re-run the SAME command line it was
|
|
638
|
-
* started with (`respawn-pane -k` with no command reuses the pane's original
|
|
639
|
-
* command). Used to hot-reload a viewer pane in place: the fresh process
|
|
640
|
-
* re-resolves `crtr` and picks up the currently selected runtime generation,
|
|
641
|
-
* while the pane id, geometry, and the node's broker are untouched. */
|
|
642
|
-
export function respawnPaneInPlace(pane) {
|
|
643
|
-
return tmux(['respawn-pane', '-k', '-t', pane]).ok;
|
|
644
|
-
}
|
|
645
627
|
// pi command assembly
|
|
646
628
|
/** Turn a pi argv array into a single shell command string.
|
|
647
629
|
*
|
|
@@ -8,8 +8,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
|
|
|
8
8
|
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
9
9
|
const stepTimings = new AsyncLocalStorage();
|
|
10
10
|
/** Run `fn`, collecting the steps recorded beneath it. */
|
|
11
|
-
export async function collectStepTimings(fn) {
|
|
12
|
-
const steps = [];
|
|
11
|
+
export async function collectStepTimings(fn, steps = []) {
|
|
13
12
|
// How long the event loop was blocked while the request ran: a blocked loop delays every await in it, and shows as time no step explains.
|
|
14
13
|
const loop = monitorEventLoopDelay({ resolution: 5 });
|
|
15
14
|
loop.enable();
|
|
@@ -56,3 +55,9 @@ export async function timedStep(name, fn) {
|
|
|
56
55
|
export function serverTimingHeader(steps) {
|
|
57
56
|
return steps.map(([name, ms]) => `${name};dur=${ms.toFixed(1)}`).join(', ');
|
|
58
57
|
}
|
|
58
|
+
/** When a request or upgrade arrived (`performance.now()`), and when its authentication finished; set by the listeners before and after they authenticate. */
|
|
59
|
+
const receipts = new WeakMap();
|
|
60
|
+
export function markReceived(req) { receipts.set(req, { receivedAt: performance.now() }); }
|
|
61
|
+
export function markAuthenticated(req) { const r = receipts.get(req); if (r !== undefined)
|
|
62
|
+
r.authenticatedAt = performance.now(); }
|
|
63
|
+
export function receiptOf(req) { return receipts.get(req) ?? { receivedAt: performance.now() }; }
|
|
@@ -5,7 +5,6 @@ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
|
5
5
|
import { gitAsync } from './git.js';
|
|
6
6
|
import { proveBranchContained } from './worktree-containment.js';
|
|
7
7
|
import { concludeAbsentManagedWorktreeAsync, concludeAbsentManagedWorktreeOnHost } from './worktree-mutation-async.js';
|
|
8
|
-
import { parseStatusPorcelain, planLandIntoCheckout } from './worktree-landing.js';
|
|
9
8
|
import { WORKTREE_LOCK_WAIT_MS, checkoutPathForBranchInList, missingWorktreeRecoveryHint, persistClosedWorktreeState, samePath, worktreeLockPathForCommonDir, WorktreeError } from './worktree.js';
|
|
10
9
|
import { shellQuote } from '../shared/shell-quote.js';
|
|
11
10
|
function detailOf(result) {
|
|
@@ -62,52 +61,9 @@ function deferredCleanupResult(wt) {
|
|
|
62
61
|
branch_delete_error: `cleanup pending: local branch ${wt.branch} remains checked out at ${wt.path}; delete it only after that checkout is removed and its landed commit is still contained in ${wt.base_ref}.`,
|
|
63
62
|
};
|
|
64
63
|
}
|
|
65
|
-
async function
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
await gitAsync(['stash', 'drop'], cwd);
|
|
69
|
-
}
|
|
70
|
-
async function landIntoBaseCheckout(baseCheckout, branch, baseSha, landedSha) {
|
|
71
|
-
const status = await gitAsync(['status', '--porcelain'], baseCheckout);
|
|
72
|
-
if (status.status !== 0)
|
|
73
|
-
return { ok: false, detail: detailOf(status) };
|
|
74
|
-
const diff = await gitAsync(['diff', '--name-only', baseSha, landedSha], baseCheckout);
|
|
75
|
-
if (diff.status !== 0)
|
|
76
|
-
return { ok: false, detail: detailOf(diff) };
|
|
77
|
-
const incoming = diff.stdout.split('\n').map((line) => line.trim()).filter((line) => line !== '');
|
|
78
|
-
const plan = planLandIntoCheckout(parseStatusPorcelain(status.stdout), incoming);
|
|
79
|
-
if (plan.kind === 'refuse')
|
|
80
|
-
return { ok: false, detail: `untracked files in ${baseCheckout} would be overwritten by the incoming commits: ${plan.collisions.join(', ')}` };
|
|
81
|
-
const merge = async () => {
|
|
82
|
-
const result = await gitAsync(['merge', '--ff-only', landedSha], baseCheckout);
|
|
83
|
-
return result.status === 0 ? { ok: true } : { ok: false, detail: detailOf(result) };
|
|
84
|
-
};
|
|
85
|
-
if (plan.kind === 'direct')
|
|
86
|
-
return merge();
|
|
87
|
-
const before = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
|
|
88
|
-
const beforeSha = before.status === 0 ? before.stdout.trim() : null;
|
|
89
|
-
const pushed = await gitAsync(['stash', 'push', '--message', `crtr landing ${branch}`], baseCheckout);
|
|
90
|
-
if (pushed.status !== 0)
|
|
91
|
-
return { ok: false, detail: detailOf(pushed) };
|
|
92
|
-
const after = await gitAsync(['rev-parse', '--verify', '--quiet', 'refs/stash'], baseCheckout);
|
|
93
|
-
const stashSha = after.status === 0 ? after.stdout.trim() : null;
|
|
94
|
-
if (stashSha === null || stashSha === beforeSha)
|
|
95
|
-
return merge();
|
|
96
|
-
const recovery = `local changes from ${baseCheckout} are retained in stash ${stashSha}; recover them with \`git -C ${shellQuote(baseCheckout)} stash apply ${stashSha}\` and resolve any conflict.`;
|
|
97
|
-
const landed = await merge();
|
|
98
|
-
if (!landed.ok) {
|
|
99
|
-
if ((await gitAsync(['stash', 'apply', stashSha], baseCheckout)).status === 0) {
|
|
100
|
-
await dropStashIfStillTip(baseCheckout, stashSha);
|
|
101
|
-
return landed;
|
|
102
|
-
}
|
|
103
|
-
return { ok: false, detail: `${landed.detail}\n${recovery}` };
|
|
104
|
-
}
|
|
105
|
-
if ((await gitAsync(['stash', 'apply', stashSha], baseCheckout)).status === 0) {
|
|
106
|
-
await dropStashIfStillTip(baseCheckout, stashSha);
|
|
107
|
-
return { ok: true };
|
|
108
|
-
}
|
|
109
|
-
await gitAsync(['reset', '--hard', landedSha], baseCheckout);
|
|
110
|
-
return { ok: true, stash: `the shared base checkout was reset to landed commit ${landedSha} because local changes conflicted with it. ${recovery}` };
|
|
64
|
+
async function landIntoBaseCheckout(baseCheckout, landedSha) {
|
|
65
|
+
const result = await gitAsync(['merge', '--ff-only', landedSha], baseCheckout);
|
|
66
|
+
return result.status === 0 ? { ok: true } : { ok: false, detail: detailOf(result) };
|
|
111
67
|
}
|
|
112
68
|
async function closeLocked(nodeId) {
|
|
113
69
|
const node = await getNode(nodeId);
|
|
@@ -184,22 +140,20 @@ async function closeOutcome(nodeId, wt) {
|
|
|
184
140
|
return blocked(`rebased worktree is not a fast-forward of local base branch '${wt.base_ref}'`, 'Ask the user how to land this managed worktree.', detailOf(fastForward));
|
|
185
141
|
const list = await runGit(wt.path, ['worktree', 'list', '--porcelain'], 'worktree_list_failed', 'Inspect the repository worktrees manually, then retry.');
|
|
186
142
|
const baseCheckout = checkoutPathForBranchInList(list, wt.base_ref);
|
|
187
|
-
let stashNote;
|
|
188
143
|
if (baseCheckout !== null) {
|
|
189
144
|
const checkoutHead = await gitAsync(['rev-parse', 'HEAD'], baseCheckout);
|
|
190
145
|
if (checkoutHead.status !== 0 || checkoutHead.stdout.trim() !== baseSha)
|
|
191
146
|
return blocked(`local base branch '${wt.base_ref}' changed while this worktree was closing`, `Reconcile the base checkout at ${baseCheckout}, then rerun \`crtr node worktree close\`.`, checkoutHead.status !== 0 ? detailOf(checkoutHead) : `expected ${baseSha}, found ${checkoutHead.stdout.trim()}`);
|
|
192
|
-
const landed = await landIntoBaseCheckout(baseCheckout,
|
|
147
|
+
const landed = await landIntoBaseCheckout(baseCheckout, landedSha);
|
|
193
148
|
if (!landed.ok)
|
|
194
149
|
return blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, `Local base branch '${wt.base_ref}' is checked out at ${baseCheckout} in a state that blocks a fast-forward.`, landed.detail);
|
|
195
|
-
stashNote = landed.stash;
|
|
196
150
|
}
|
|
197
151
|
else {
|
|
198
152
|
const update = await gitAsync(['update-ref', `refs/heads/${wt.base_ref}`, landedSha, baseSha], wt.path);
|
|
199
153
|
if (update.status !== 0)
|
|
200
154
|
return blocked(`could not fast-forward local base branch '${wt.base_ref}' to this worktree`, 'Ask the user how to land this managed worktree.', detailOf(update));
|
|
201
155
|
}
|
|
202
|
-
return { kind: 'closed', result: { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: landedSha, ...deferredCleanupResult(wt)
|
|
156
|
+
return { kind: 'closed', result: { node_id: nodeId, branch: wt.branch, worktree_path: wt.path, landed_sha: landedSha, ...deferredCleanupResult(wt) } };
|
|
203
157
|
}
|
|
204
158
|
/** Async daemon executor for explicit close. The lock wait and every Git
|
|
205
159
|
* subprocess yield to the daemon event loop. */
|
|
@@ -1,51 +1,3 @@
|
|
|
1
|
-
// The judgment shared by every path that lands a managed worktree onto its
|
|
2
|
-
// base branch. These functions run no subprocesses and touch no filesystem:
|
|
3
|
-
// they decide from Git output that the caller already has in hand.
|
|
4
|
-
//
|
|
5
|
-
// Two callers execute the same decision in two forms — `worktree.ts`'s
|
|
6
|
-
// synchronous `close` (an API handler, already blocking) and
|
|
7
|
-
// `worktree-sweep.ts`'s asynchronous daemon sweep (which must never block the
|
|
8
|
-
// event loop). Only the process plumbing differs; the rules that decide whether
|
|
9
|
-
// local work is at risk live here once, so the two can never drift.
|
|
10
|
-
/** Split `git status --porcelain` (v1 format) into tracked modifications and
|
|
11
|
-
* untracked paths. A rename entry (`R old -> new`) reports the destination:
|
|
12
|
-
* that is the path an incoming commit would collide with. */
|
|
13
|
-
export function parseStatusPorcelain(porcelain) {
|
|
14
|
-
const tracked = [];
|
|
15
|
-
const untracked = [];
|
|
16
|
-
for (const line of porcelain.split('\n')) {
|
|
17
|
-
if (line.length < 4)
|
|
18
|
-
continue;
|
|
19
|
-
const code = line.slice(0, 2);
|
|
20
|
-
const rest = line.slice(3);
|
|
21
|
-
const path = rest.includes(' -> ') ? rest.slice(rest.indexOf(' -> ') + 4) : rest;
|
|
22
|
-
const unquoted = path.startsWith('"') && path.endsWith('"') ? path.slice(1, -1) : path;
|
|
23
|
-
if (code === '??')
|
|
24
|
-
untracked.push(unquoted);
|
|
25
|
-
else if (code !== '!!')
|
|
26
|
-
tracked.push(unquoted);
|
|
27
|
-
}
|
|
28
|
-
return { tracked, untracked };
|
|
29
|
-
}
|
|
30
|
-
/** How to fast-forward a base checkout that may hold local changes.
|
|
31
|
-
*
|
|
32
|
-
* Git is less fragile than it looks here: a fast-forward refuses only when an
|
|
33
|
-
* incoming commit touches a file with local modifications, so DISJOINT local
|
|
34
|
-
* changes are carried along fine and need no stash at all. Overlap is the
|
|
35
|
-
* blocker, not dirt.
|
|
36
|
-
*
|
|
37
|
-
* Untracked files are different. They also do not block a fast-forward unless
|
|
38
|
-
* an incoming commit adds the same path — and that collision is a refusal
|
|
39
|
-
* rather than a stash, because sweeping a person's untracked file into a stash
|
|
40
|
-
* to make room for a commit is not a trade this code may make on their behalf. */
|
|
41
|
-
export function planLandIntoCheckout(status, incoming) {
|
|
42
|
-
const arriving = new Set(incoming);
|
|
43
|
-
const collisions = status.untracked.filter((path) => arriving.has(path));
|
|
44
|
-
if (collisions.length > 0)
|
|
45
|
-
return { kind: 'refuse', collisions };
|
|
46
|
-
const overlapping = status.tracked.filter((path) => arriving.has(path));
|
|
47
|
-
return overlapping.length > 0 ? { kind: 'stash', overlapping } : { kind: 'direct' };
|
|
48
|
-
}
|
|
49
1
|
/** The `git update-ref --stdin` body that deletes a managed branch ONLY while
|
|
50
2
|
* the ref that proved its content already landed is still at the exact SHA the
|
|
51
3
|
* proof inspected. Compare-and-delete is the whole ownership guard: a branch
|