@north-light/cli 0.3.693 → 0.3.695
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/api/errors.js +1 -1
- 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/cli.js +6 -6
- 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 +538 -537
- package/dist/commands/node/inspect.js +9 -9
- package/dist/commands/node-worktree.js +1 -1
- package/dist/commands/pkg/market-manage.js +1 -1
- package/dist/commands/pkg/plugin-manage.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/commands/sys/update.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/canvas/canvas.js +7 -7
- package/dist/core/canvas/types.d.ts +0 -2
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/row-store.js +10 -10
- package/dist/core/graph/exposures.js +1 -1
- package/dist/core/graph/names.js +9 -9
- package/dist/core/graph/watches.js +1 -1
- package/dist/core/installed-plugins.js +1 -1
- 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/ops.d.ts +2 -7
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/runner/machine/runner.d.ts +0 -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/scoped-state/imported-mac-installs.d.ts +12 -0
- package/dist/core/scoped-state/imported-mac-installs.js +2 -0
- package/dist/core/spaces/stop.js +1 -1
- 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 +4 -4
- 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-link/client.d.ts +5 -1
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/daemon/machine-link/holder.js +3 -3
- 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/runs/append-section.js +2 -2
- package/dist/daemon/runs/observer.js +3 -3
- package/dist/shared/env.d.ts +8 -3
- package/dist/shared/env.js +2 -2
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- 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/api/errors.js +1 -1
- package/packages/crouter-api/dist/clients/attach/session/connection.js +36 -1
- 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/inspect.js +16 -2
- package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
- package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
- package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
- 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/commands/sys/update.js +5 -3
- package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
- package/packages/crouter-api/dist/core/canvas/canvas.js +6 -11
- package/packages/crouter-api/dist/core/config.js +10 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
- package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
- package/packages/crouter-api/dist/core/graph/names.js +7 -20
- package/packages/crouter-api/dist/core/graph/watches.js +1 -1
- package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
- 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 +4 -24
- 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/scoped-state/imported-mac-installs.js +94 -0
- package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
- 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 +13 -2
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +2 -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/dist/shared/env.js +15 -4
- package/packages/crouter-api/dist/types.js +1 -1
- 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/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
|
@@ -17,9 +17,8 @@ export function createReconnect(ctx, hooks) {
|
|
|
17
17
|
let lastSocketError;
|
|
18
18
|
let reconnecting = false;
|
|
19
19
|
let viewerDormant = hooks.initialDormant === true;
|
|
20
|
-
// Captured at give-up: a
|
|
21
|
-
//
|
|
22
|
-
// `dead`/`canceled` keep the corpse.
|
|
20
|
+
// Captured at give-up: a finished node closes its pane; a deleted one keeps
|
|
21
|
+
// the "broker gone" corpse.
|
|
23
22
|
let finalizedDone = false;
|
|
24
23
|
let stopped = false;
|
|
25
24
|
let resolveStopped = () => { };
|
|
@@ -63,9 +62,8 @@ export function createReconnect(ctx, hooks) {
|
|
|
63
62
|
term: { cols: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 },
|
|
64
63
|
});
|
|
65
64
|
};
|
|
66
|
-
// On close we HOLD the pane and keep re-dialing
|
|
67
|
-
//
|
|
68
|
-
// terminal (done/dead/canceled or row reaped). There is deliberately NO
|
|
65
|
+
// On close we HOLD the pane and keep re-dialing until the node is deleted or
|
|
66
|
+
// finished with a final report (`reconnectShouldGiveUp`). There is deliberately NO
|
|
69
67
|
// wall-clock give-up: a fixed deadline races the daemon's legitimate relaunch
|
|
70
68
|
// latency (a slow supervision tick on a big canvas, the 20s crash-revive
|
|
71
69
|
// grace, a slow pi boot), and losing that race dumped the user to a shell
|
|
@@ -91,9 +89,10 @@ export function createReconnect(ctx, hooks) {
|
|
|
91
89
|
row = undefined;
|
|
92
90
|
}
|
|
93
91
|
if (row !== undefined && reconnectShouldGiveUp(row)) {
|
|
94
|
-
finalizedDone = row
|
|
95
|
-
break;
|
|
92
|
+
finalizedDone = row !== null;
|
|
93
|
+
break;
|
|
96
94
|
}
|
|
95
|
+
const deadOrCanceled = row?.status === 'dead' || row?.status === 'canceled';
|
|
97
96
|
// A dormant node has NO broker until its next wake. We still track that
|
|
98
97
|
// (the dormant flag routes a submitted prompt through the wake path
|
|
99
98
|
// instead of a dead socket), but we DON'T shout about it: a parked pane
|
|
@@ -103,18 +102,15 @@ export function createReconnect(ctx, hooks) {
|
|
|
103
102
|
// keep the reconnecting notice only for a transient broker relaunch.
|
|
104
103
|
const dormant = row?.status === 'idle'
|
|
105
104
|
|| row?.intent === 'idle-release'
|
|
106
|
-
||
|
|
107
|
-
&& row.status === 'done'
|
|
108
|
-
&& row.intent === 'parked'
|
|
109
|
-
&& row.final_report == null);
|
|
105
|
+
|| row?.status === 'done';
|
|
110
106
|
const enteredDormancy = dormant && !viewerDormant;
|
|
111
107
|
viewerDormant = dormant;
|
|
112
108
|
if (enteredDormancy)
|
|
113
109
|
hooks.onEnterDormancy();
|
|
114
|
-
hooks.setNotice(dormant ? '' : '↻ node refreshing — reconnecting…', { sticky: !dormant });
|
|
110
|
+
hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' : '↻ node refreshing — reconnecting…', { sticky: !dormant });
|
|
115
111
|
try {
|
|
116
112
|
const redialed = await Promise.race([
|
|
117
|
-
socket.redial({ brokerUnavailableIsExpected: dormant }).then(() => true),
|
|
113
|
+
socket.redial({ brokerUnavailableIsExpected: dormant || deadOrCanceled }).then(() => true),
|
|
118
114
|
stoppedSignal.then(() => false),
|
|
119
115
|
]);
|
|
120
116
|
if (!redialed || stopped || hooks.isTornDown())
|
|
@@ -126,7 +122,7 @@ export function createReconnect(ctx, hooks) {
|
|
|
126
122
|
}
|
|
127
123
|
catch {
|
|
128
124
|
// ENOENT (socket not recreated yet) / ECONNREFUSED (listen not ready) → retry.
|
|
129
|
-
const elapsed = await waitForRetry(dormant ? RECONNECT_DORMANT_DELAY_MS : Math.min(delay, RECONNECT_ACTIVE_DELAY_CAP_MS));
|
|
125
|
+
const elapsed = await waitForRetry(dormant || deadOrCanceled ? RECONNECT_DORMANT_DELAY_MS : Math.min(delay, RECONNECT_ACTIVE_DELAY_CAP_MS));
|
|
130
126
|
if (!elapsed)
|
|
131
127
|
return;
|
|
132
128
|
delay *= 2;
|
|
@@ -101,11 +101,11 @@ onConnected) {
|
|
|
101
101
|
// read, native slash command, pane tag and lifecycle action gates on it,
|
|
102
102
|
// and no collaborator may re-derive it.
|
|
103
103
|
mark('viewer.connect_start', { node: nodeId });
|
|
104
|
-
const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
|
|
105
|
-
mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
|
|
106
|
-
const { remote, canvasSource, meta, socket } = connection;
|
|
107
104
|
const role = resolveHelloRole(observer);
|
|
108
105
|
const clientId = randomUUID();
|
|
106
|
+
const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node, { role, clientId });
|
|
107
|
+
mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
|
|
108
|
+
const { remote, canvasSource, meta, socket } = connection;
|
|
109
109
|
// 2. Theme + keybindings — pi's components throw "Theme not initialized"
|
|
110
110
|
// otherwise. One KeybindingsManager feeds BOTH editor and input; the
|
|
111
111
|
// editor may resolve a separate pi-tui instance, so mirror onto it (and
|
|
@@ -165,6 +165,11 @@ onConnected) {
|
|
|
165
165
|
const whipAnimation = new WhipAnimation(tui, pal);
|
|
166
166
|
containers.header.addChild(whipAnimation);
|
|
167
167
|
containers.header.addChild(recapHeader.component);
|
|
168
|
+
// A viewer that restarted itself in place hands its unsent draft to its successor.
|
|
169
|
+
const restoredDraft = process.env['CRTR_ATTACH_DRAFT'];
|
|
170
|
+
delete process.env['CRTR_ATTACH_DRAFT'];
|
|
171
|
+
if (restoredDraft !== undefined)
|
|
172
|
+
editor.setText(restoredDraft);
|
|
168
173
|
const ctx = { nodeId, remote, role, meta, canvasSource, socket, tui, pal, editor, containers };
|
|
169
174
|
// The pending-request strip below the recap goal line. Its hooks close over
|
|
170
175
|
// collaborators built later (paneFocus, roster, inbox, setNotice) — all are
|
|
@@ -590,8 +595,37 @@ onConnected) {
|
|
|
590
595
|
crouterBindings = crouterBindingSettings.bindings;
|
|
591
596
|
},
|
|
592
597
|
modelThinkingLabel: sync.modelThinkingLabel,
|
|
593
|
-
onWelcome: () =>
|
|
598
|
+
onWelcome: () => {
|
|
599
|
+
scheduleTmuxBindingInstall();
|
|
600
|
+
if (!remote)
|
|
601
|
+
void restartIfReleaseChanged();
|
|
602
|
+
},
|
|
594
603
|
});
|
|
604
|
+
// The one restart path: replace this process with a fresh viewer for the same
|
|
605
|
+
// node and flags, through the `crtr` launcher so it loads the selected
|
|
606
|
+
// release. A shell hosting the viewer stays alive underneath.
|
|
607
|
+
const restartViewer = (env = {}) => {
|
|
608
|
+
const draft = editor.getText();
|
|
609
|
+
// Checked before teardown: a failed exec after it would close the pane and lose the draft.
|
|
610
|
+
if (process.execve === undefined || Buffer.byteLength(draft) > 100_000) {
|
|
611
|
+
setNotice(process.execve === undefined ? `This Node.js ${process.version} cannot restart the viewer in place` : 'The unsent draft is too long to carry across a restart');
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
teardown('detach');
|
|
615
|
+
const args = ['surface', 'attach', 'to', nodeId, ...(observer ? ['--observer'] : []), ...(canvasName !== undefined ? ['--canvas', canvasName] : [])];
|
|
616
|
+
process.execve(process.execPath, [process.execPath, ...process.execArgv, process.argv[1], ...args], { ...process.env, ...env, CRTR_ATTACH_DRAFT: draft, CRTR_ATTACH_WAKE_PARKED: '0' });
|
|
617
|
+
};
|
|
618
|
+
// One automatic restart per daemon release: if the launcher still loads another release, a second try would loop.
|
|
619
|
+
const restartedFor = process.env['CRTR_ATTACH_RESTARTED_FOR'];
|
|
620
|
+
delete process.env['CRTR_ATTACH_RESTARTED_FOR'];
|
|
621
|
+
const restartIfReleaseChanged = async () => {
|
|
622
|
+
const { processGeneration } = await import('../../commands/sys/shared.js');
|
|
623
|
+
const mine = processGeneration()?.id;
|
|
624
|
+
const daemons = (await cliClient().status().catch(() => undefined))?.generation_id;
|
|
625
|
+
if (mine !== undefined && daemons != null && daemons !== mine && daemons !== restartedFor && !lifecycle.isTornDown()) {
|
|
626
|
+
restartViewer({ CRTR_ATTACH_RESTARTED_FOR: daemons });
|
|
627
|
+
}
|
|
628
|
+
};
|
|
595
629
|
// Last resort for a background daemon call that escaped its owner's catch.
|
|
596
630
|
// Node's default for an unhandled rejection is to exit, and this process IS
|
|
597
631
|
// the person's pane: one stray promise from a fire-and-forget refresh closed
|
|
@@ -843,6 +877,7 @@ onConnected) {
|
|
|
843
877
|
search.open();
|
|
844
878
|
},
|
|
845
879
|
whip,
|
|
880
|
+
reloadViewer: () => restartViewer(),
|
|
846
881
|
});
|
|
847
882
|
// Registered only now: every collaborator `stopLocal` touches (the key
|
|
848
883
|
// listener included) finally exists, so a signal cannot race a half-built
|
|
@@ -864,8 +899,10 @@ onConnected) {
|
|
|
864
899
|
if (connection.initialSnapshot !== undefined)
|
|
865
900
|
scheduleTmuxBindingInstall();
|
|
866
901
|
if (connection.initialSnapshot === undefined) {
|
|
902
|
+
// The hello went out during the connect and the broker's welcome answered it; replay what it sent through the handlers just installed.
|
|
867
903
|
mark('viewer.hello_sent');
|
|
868
|
-
|
|
904
|
+
for (const frame of connection.takeEarlyFrames())
|
|
905
|
+
socket.emit('frame', frame);
|
|
869
906
|
}
|
|
870
907
|
else {
|
|
871
908
|
reconnect.startDormant();
|
|
@@ -8,6 +8,7 @@ import { fuzzyMatch } from '../../core/tui/fuzzy.js';
|
|
|
8
8
|
import { nodeSnapshotLeaf } from '../node-snapshot.js';
|
|
9
9
|
import { nodeTranscriptLeaf } from '../node-transcript.js';
|
|
10
10
|
import { nodeContextLeaf } from '../node-context.js';
|
|
11
|
+
import { ApiError } from '../../api/index.js';
|
|
11
12
|
import { cliClient, cliCanvasSource, rethrowAsCliError } from '../api-client.js';
|
|
12
13
|
import { RemoteCanvasSource } from '../../core/canvas/remote-canvas-source.js';
|
|
13
14
|
import { kindsStateBlock, profilesStateBlock, resolveProfileViaDaemon } from '../profile/daemon-profiles.js';
|
|
@@ -88,6 +89,8 @@ const nodeList = defineLeaf({
|
|
|
88
89
|
// Keep remote provenance out of the returned DTO-shaped object without adding a
|
|
89
90
|
// second wire field or mutating the remote response.
|
|
90
91
|
const remoteShowResults = new WeakSet();
|
|
92
|
+
/** Results whose node runs in a cloud sandbox: its broker pid is a process id inside that sandbox, so this computer cannot check it. */
|
|
93
|
+
const sandboxShowResults = new WeakSet();
|
|
91
94
|
// Enrich a declared source edge so a debugger reads who a report/manager is
|
|
92
95
|
// without rebuilding a NodeMeta compatibility object.
|
|
93
96
|
async function enrichNeighbor(source, ref) {
|
|
@@ -171,14 +174,25 @@ const nodeShow = defineLeaf({
|
|
|
171
174
|
if (reports.length > 0)
|
|
172
175
|
hints.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${reports.map((r) => r['node_id']).join(', ')}).`);
|
|
173
176
|
hints.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${id}\`.`);
|
|
174
|
-
|
|
177
|
+
const result = { node, fault: node.fault ?? null, reports, managers, pending_crons, paths, follow_up: hints.join('\n') };
|
|
178
|
+
// The environment read answers 400 for a profile that runs on a machine.
|
|
179
|
+
const inSandbox = node.profile_id !== null && await client.getProfileEnvironment(node.profile_id).then(() => true, (err) => {
|
|
180
|
+
if (err instanceof ApiError && err.status === 400)
|
|
181
|
+
return false;
|
|
182
|
+
return rethrowAsCliError(err);
|
|
183
|
+
});
|
|
184
|
+
if (inSandbox)
|
|
185
|
+
sandboxShowResults.add(result);
|
|
186
|
+
return result;
|
|
175
187
|
},
|
|
176
188
|
render: (r) => {
|
|
177
189
|
const node = r['node'];
|
|
178
190
|
const id = String(node['node_id']);
|
|
179
191
|
const pid = node['pi_pid'];
|
|
180
192
|
const isRemoteShow = remoteShowResults.has(r);
|
|
181
|
-
const alive = isRemoteShow
|
|
193
|
+
const alive = isRemoteShow
|
|
194
|
+
? 'remote (liveness not checked locally)'
|
|
195
|
+
: sandboxShowResults.has(r) ? 'in a cloud sandbox (liveness not checked locally)' : (isPidAlive(pid) ? 'alive' : 'dead');
|
|
182
196
|
const intent = node['intent'] ? `/${String(node['intent'])}` : '';
|
|
183
197
|
const fault = r['fault'];
|
|
184
198
|
const parts = [];
|
|
@@ -85,8 +85,7 @@ const worktreeClose = defineLeaf({
|
|
|
85
85
|
{ name: 'worktree_removed', type: 'boolean', required: true, constraint: 'Always false for an active caller: its checkout remains intact rather than being removed beneath the node.' },
|
|
86
86
|
{ name: 'worktree_remove_error', type: 'string', required: true, constraint: 'The named deferred-cleanup state and safe manual follow-up after the caller exits.' },
|
|
87
87
|
{ name: 'branch_deleted', type: 'boolean', required: true, constraint: 'False while the deferred-cleanup checkout still has this branch checked out.' },
|
|
88
|
-
{ name: 'branch_delete_error', type: 'string', required: true, constraint: 'The safe branch-cleanup follow-up after the checkout is removed.' }
|
|
89
|
-
{ name: 'base_checkout_stash', type: 'string', required: false, constraint: 'Present when conflicting base-checkout changes were retained in a stash; names the exact stash SHA and command required to recover them.' }
|
|
88
|
+
{ name: 'branch_delete_error', type: 'string', required: true, constraint: 'The safe branch-cleanup follow-up after the checkout is removed.' }
|
|
90
89
|
],
|
|
91
90
|
outputKind: 'object',
|
|
92
91
|
effects: [
|
|
@@ -117,9 +116,6 @@ const worktreeClose = defineLeaf({
|
|
|
117
116
|
if (r['branch_deleted'] === false) {
|
|
118
117
|
notes.push(String(r['branch_delete_error'] ?? `local branch ${branch} could not be deleted automatically.`));
|
|
119
118
|
}
|
|
120
|
-
if (typeof r['base_checkout_stash'] === 'string') {
|
|
121
|
-
notes.push(`Warning: ${r['base_checkout_stash']}`);
|
|
122
|
-
}
|
|
123
119
|
if (notes.length > 0)
|
|
124
120
|
return `${base} Note: ${notes.join(' ')}`;
|
|
125
121
|
return base;
|
|
@@ -19,29 +19,20 @@ export async function addMarketplace(opts) {
|
|
|
19
19
|
const { url, ref, scope } = opts;
|
|
20
20
|
const root = requireScopeRoot(scope);
|
|
21
21
|
await ensureScopeInitialized(scope, root);
|
|
22
|
-
const tempName = deriveNameFromUrl(url);
|
|
23
22
|
const mktsDir = marketplacesDir(scope);
|
|
24
23
|
ensureDir(mktsDir);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
const manifest = readMarketplaceManifest(tempDest);
|
|
24
|
+
// Clone beside the live checkouts and swap only after the registration is written: a refused write must leave an existing checkout,
|
|
25
|
+
// and every plugin linked into it, untouched.
|
|
26
|
+
const staging = join(mktsDir, `.${deriveNameFromUrl(url)}.${process.pid}.${Date.now()}.candidate`);
|
|
27
|
+
clone(url, staging, { depth: 1, ref: ref !== undefined ? ref : undefined });
|
|
28
|
+
const manifest = readMarketplaceManifest(staging);
|
|
31
29
|
if (!manifest) {
|
|
32
|
-
removePath(
|
|
33
|
-
throw notFound(`marketplace manifest not found at ${
|
|
30
|
+
removePath(staging);
|
|
31
|
+
throw notFound(`marketplace manifest not found at ${staging}/.crouter-marketplace/marketplace.json — not a valid marketplace`);
|
|
34
32
|
}
|
|
35
33
|
const finalName = manifest.name;
|
|
36
34
|
const finalDest = join(mktsDir, finalName);
|
|
37
|
-
if (finalName !== tempName) {
|
|
38
|
-
if (pathExists(finalDest)) {
|
|
39
|
-
removePath(finalDest);
|
|
40
|
-
}
|
|
41
|
-
renameSync(tempDest, finalDest);
|
|
42
|
-
}
|
|
43
35
|
const effectiveRef = ref !== undefined ? ref : 'main';
|
|
44
|
-
// A refused registration leaves no clone behind: a directory without its config row would list as a marketplace with no url.
|
|
45
36
|
try {
|
|
46
37
|
await updateConfig(scope, (cfg) => {
|
|
47
38
|
cfg.marketplaces[finalName] = {
|
|
@@ -52,9 +43,13 @@ export async function addMarketplace(opts) {
|
|
|
52
43
|
});
|
|
53
44
|
}
|
|
54
45
|
catch (error) {
|
|
55
|
-
removePath(
|
|
46
|
+
removePath(staging);
|
|
56
47
|
throw error;
|
|
57
48
|
}
|
|
49
|
+
if (pathExists(finalDest))
|
|
50
|
+
activateStagedRoots([{ active: finalDest, candidate: staging, previous: `${staging}.previous` }]);
|
|
51
|
+
else
|
|
52
|
+
renameSync(staging, finalDest);
|
|
58
53
|
return { name: finalName, scope, path: finalDest };
|
|
59
54
|
}
|
|
60
55
|
export const marketAdd = defineLeaf({
|
|
@@ -316,6 +311,7 @@ export const marketUpdate = defineLeaf({
|
|
|
316
311
|
],
|
|
317
312
|
output: [
|
|
318
313
|
{ name: 'updated', type: 'object[]', required: true, constraint: 'One entry per marketplace processed: {name, updated, sha}.' },
|
|
314
|
+
{ name: 'skipped', type: 'object[]', required: false, constraint: 'Present when a marketplace checkout has no registered url: {name, reason}. It is not refreshed.' },
|
|
319
315
|
],
|
|
320
316
|
outputKind: 'object',
|
|
321
317
|
effects: ['Stages and validates marketplace and sourced-plugin revisions before atomically activating them, replacing each checkout even at an unchanged revision — local modifications inside those directories are discarded. `updated` reports whether the revision moved, not whether the checkout was replaced. Updates installed plugin content/version for plugins sourced from refreshed marketplaces.'],
|
|
@@ -333,8 +329,15 @@ export const marketUpdate = defineLeaf({
|
|
|
333
329
|
return [found];
|
|
334
330
|
})();
|
|
335
331
|
const updated = [];
|
|
336
|
-
|
|
332
|
+
const skipped = [];
|
|
333
|
+
for (const target of targets) {
|
|
334
|
+
// A checkout with no registered url has nothing to clone from: name it instead of cloning ''.
|
|
335
|
+
if (target.url === '') {
|
|
336
|
+
skipped.push({ name: target.name, reason: `no url registered for ${target.root}; re-add it with \`crtr pkg market add <url>\`` });
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
337
339
|
updated.push(await updateMarketplaceTarget(target));
|
|
338
|
-
|
|
340
|
+
}
|
|
341
|
+
return skipped.length === 0 ? { updated } : { updated, skipped };
|
|
339
342
|
},
|
|
340
343
|
});
|
|
@@ -451,7 +451,8 @@ async function refreshMarketplace(name, cache, opts) {
|
|
|
451
451
|
const activeManifest = readMarketplaceManifest(marketplace.root);
|
|
452
452
|
if (activeManifest === null)
|
|
453
453
|
throw notFound(`marketplace manifest not found: ${marketplace.root}/.crouter-marketplace/marketplace.json`);
|
|
454
|
-
|
|
454
|
+
// A checkout with no registered url (or no git history) has nothing to refresh from.
|
|
455
|
+
if (!isGitRepo(marketplace.root) || marketplace.url === '') {
|
|
455
456
|
const unchanged = { marketplace, manifest: activeManifest, pull: { updated: false, sha: currentSha(marketplace.root) ?? '' } };
|
|
456
457
|
cache.set(name, unchanged);
|
|
457
458
|
return unchanged;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// `crtr surface node` — pure tmux placement for node viewers.
|
|
2
|
-
import { closePane, currentTmux, displayPopup, ensureSession, getPaneOption, openNodeWindow, paneCurrentPath, paneExists,
|
|
2
|
+
import { closePane, currentTmux, displayPopup, ensureSession, getPaneOption, openNodeWindow, paneCurrentPath, paneExists, paneStartCommand, respawnPaneSync, selectPane, selectWindow, shellQuote, viewerSplitEnv, } from '../../../core/runtime/placement-tmux.js';
|
|
3
3
|
import { focusViewer as focusViewerWith, viewerEnv, viewerPaneOf, } from '../../../core/runtime/focus-viewer.js';
|
|
4
4
|
import { cliClient, rethrowAsCliError } from '../../api-client.js';
|
|
5
|
-
export { closePane, currentTmux, displayPopup, paneCurrentPath, paneExists,
|
|
5
|
+
export { closePane, currentTmux, displayPopup, paneCurrentPath, paneExists, paneStartCommand, respawnPaneSync, shellQuote, viewerSplitEnv };
|
|
6
6
|
export { viewerEnv, viewerPaneOf };
|
|
7
7
|
/** `focusViewer` bound to the CLI's daemon client, with daemon failures
|
|
8
8
|
* rethrown as clean CLI errors. The implementation is shared with the attach
|
|
@@ -7,7 +7,6 @@ import { tmuxSpreadLeaf } from './surface-tmux-spread.js';
|
|
|
7
7
|
import { surfaceEditLeaf } from './surface-edit.js';
|
|
8
8
|
import { registerSurfaceNode } from './surface-node.js';
|
|
9
9
|
import { surfaceInspectLeaf } from './surface-inspect.js';
|
|
10
|
-
import { surfaceReloadLeaf } from './surface-reload.js';
|
|
11
10
|
import { surfaceInboxLeaf } from './surface-inbox.js';
|
|
12
11
|
import { surfaceDashboardLeaf } from './surface-dashboard.js';
|
|
13
12
|
export function registerSurface() {
|
|
@@ -22,8 +21,8 @@ export function registerSurface() {
|
|
|
22
21
|
help: {
|
|
23
22
|
name: 'surface',
|
|
24
23
|
summary: 'open and manage screen-facing surfaces',
|
|
25
|
-
model: 'Choose `node` for navigation among node viewers. The other commands open a broker attachment, node Inspector, subtree spread,
|
|
24
|
+
model: 'Choose `node` for navigation among node viewers. The other commands open a broker attachment, node Inspector, subtree spread, or adjacent editor pane.',
|
|
26
25
|
},
|
|
27
|
-
children: [registerSurfaceNode(), attach, surfaceInspectLeaf,
|
|
26
|
+
children: [registerSurfaceNode(), attach, surfaceInspectLeaf, tmuxSpreadLeaf, surfaceEditLeaf, surfaceInboxLeaf, surfaceDashboardLeaf],
|
|
28
27
|
});
|
|
29
28
|
}
|
|
@@ -21,7 +21,7 @@ export const sysUpdateLeaf = defineLeaf({
|
|
|
21
21
|
{ name: 'target', type: 'string', required: false, constraint: 'Present when applying updates: self | content | all.' },
|
|
22
22
|
{ name: 'status', type: 'string', required: false, constraint: 'done | failed when applying updates.' },
|
|
23
23
|
{ name: 'error', type: 'string', required: false, constraint: 'Failure message when status is failed.' },
|
|
24
|
-
{ name: 'warning', type: 'string', required: false, constraint: 'Present when the update was applied but recording the self-check time failed; status stays done.' },
|
|
24
|
+
{ name: 'warning', type: 'string', required: false, constraint: 'Present when the update was applied but recording the self-check time failed, or a marketplace with no registered url was skipped; status stays done.' },
|
|
25
25
|
{ name: 'updates', type: 'object[]', required: false, constraint: 'Present when --check. Each: {name, current, latest, up_to_date, unreachable, kind}.' },
|
|
26
26
|
{ name: 'up_to_date', type: 'boolean', required: false, constraint: 'Present when --check. True when all items are up to date.' },
|
|
27
27
|
],
|
|
@@ -105,10 +105,12 @@ export const sysUpdateLeaf = defineLeaf({
|
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
107
|
if (resolvedTarget === 'content' || resolvedTarget === 'all') {
|
|
108
|
-
await marketUpdate.run({});
|
|
108
|
+
const markets = await marketUpdate.run({});
|
|
109
|
+
for (const skip of markets.skipped ?? [])
|
|
110
|
+
warnings.push(`marketplace ${skip.name} skipped: ${skip.reason}`);
|
|
109
111
|
await pluginUpdate.run({});
|
|
110
112
|
}
|
|
111
|
-
return warnings.length === 0 ? { target: resolvedTarget, status: 'done' } : { target: resolvedTarget, status: 'done', warning:
|
|
113
|
+
return warnings.length === 0 ? { target: resolvedTarget, status: 'done' } : { target: resolvedTarget, status: 'done', warning: warnings.join('; ') };
|
|
112
114
|
}
|
|
113
115
|
catch (e) {
|
|
114
116
|
const msg = e instanceof Error ? e.message : String(e);
|
|
@@ -36,24 +36,12 @@ export { RelayTransport } from './transport-relay.js';
|
|
|
36
36
|
* rejecting — bounds a pending picker fetch if the broker drops the request
|
|
37
37
|
* (it should always reply with `data` or a correlated `error`). */
|
|
38
38
|
const REQUEST_TIMEOUT_MS = 10_000;
|
|
39
|
-
/** The reconnect supervisor's give-up predicate
|
|
40
|
-
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* broker on the same path. It gives up only when the node is genuinely gone:
|
|
44
|
-
* a terminal status (done/dead/canceled) or a reaped row (null). `idle` and an
|
|
45
|
-
* exact unfinalized parked resident are NOT terminal — either can wake while
|
|
46
|
-
* the viewer remains seated. Local canvas rows only — a remote target has no
|
|
47
|
-
* local row, so callers driving a remote attach must not consult this. */
|
|
39
|
+
/** The reconnect supervisor's give-up predicate. A node can be revived from
|
|
40
|
+
* any status, so the viewer keeps re-dialing through dead and canceled; it
|
|
41
|
+
* gives up only when the row is deleted (null) or the node finished with a
|
|
42
|
+
* final report. */
|
|
48
43
|
export function reconnectShouldGiveUp(row) {
|
|
49
|
-
|
|
50
|
-
return true;
|
|
51
|
-
if (row.lifecycle === 'resident'
|
|
52
|
-
&& row.status === 'done'
|
|
53
|
-
&& row.intent === 'parked'
|
|
54
|
-
&& row.final_report == null)
|
|
55
|
-
return false;
|
|
56
|
-
return row.status === 'done' || row.status === 'dead' || row.status === 'canceled';
|
|
44
|
+
return row === null || (row.status === 'done' && row.final_report != null);
|
|
57
45
|
}
|
|
58
46
|
export class BrokerClient extends EventEmitter {
|
|
59
47
|
nodeId;
|
|
@@ -63,8 +63,8 @@ async function seedRow(meta, db) {
|
|
|
63
63
|
// A node directly under an app is readable by the person it was made for.
|
|
64
64
|
if (profile === null && meta.sub)
|
|
65
65
|
await writeActsFor(db, meta.node_id, meta.sub);
|
|
66
|
-
await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor,
|
|
67
|
-
.run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.
|
|
66
|
+
await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill('?').join(', ')})`)
|
|
67
|
+
.run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.deleting_at ?? null, meta.caused_by ?? null, app.id);
|
|
68
68
|
}
|
|
69
69
|
/** The `node_rows` view projects the active fault's columns under a `fault_`
|
|
70
70
|
* prefix; strip it and hydrate through the same mapper `readFault` uses. */
|
|
@@ -102,7 +102,6 @@ function rowFrom(r) {
|
|
|
102
102
|
run_id: r['run_id'] ?? null,
|
|
103
103
|
event_cursor: r['event_cursor'] ?? null,
|
|
104
104
|
last_activity_at: r['last_activity_at'] ?? null,
|
|
105
|
-
usage_json: r['usage_json'] ?? null,
|
|
106
105
|
caused_by: r['caused_by'] ?? null,
|
|
107
106
|
last_turn_error_json: r['last_turn_error_json'] ?? null,
|
|
108
107
|
deleting_at: r['deleting_at'] ?? null,
|
|
@@ -942,7 +941,7 @@ async function nodeConversationIds(nodeIds) {
|
|
|
942
941
|
if (nodeIds.length === 0)
|
|
943
942
|
return [];
|
|
944
943
|
const placeholders = nodeIds.map(() => '?').join(',');
|
|
945
|
-
const rows = await (await openDb()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${placeholders}) AND s.session_id IS NOT NULL
|
|
944
|
+
const rows = await (await openDb()).prepareUncached(`SELECT s.session_id, s.transcript_path, s.node_id, n.grantee FROM sessions s JOIN node_rows n ON n.node_id = s.node_id WHERE s.node_id IN (${placeholders}) AND s.session_id IS NOT NULL ORDER BY s.created_at, s.seq`).all(...nodeIds);
|
|
946
945
|
return [...new Map(rows.map((row) => [row.session_id, { id: row.session_id, path: row.transcript_path, dir: join(appSpace(row.grantee).conversations, row.node_id) }])).values()];
|
|
947
946
|
}
|
|
948
947
|
/** Delete conversations nothing still needs: no sessions row names them, and no fork
|
|
@@ -957,14 +956,10 @@ async function deleteNodeConversations(conversations) {
|
|
|
957
956
|
for (const { id, path, dir } of conversations) {
|
|
958
957
|
if (await referenced.get(id) !== undefined || await pendingFork.get(id) !== undefined)
|
|
959
958
|
continue;
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
if (!isBeneath(dir, path)) {
|
|
963
|
-
console.error(`[canvas] not deleting transcript outside its node's conversations directory: ${path}`);
|
|
964
|
-
continue;
|
|
965
|
-
}
|
|
959
|
+
// A legacy transcript file goes too, but only from beneath the node's own conversations directory.
|
|
960
|
+
const file = path !== null && lstatSync(path, { throwIfNoEntry: false }) !== undefined && isBeneath(dir, path) ? path : undefined;
|
|
966
961
|
try {
|
|
967
|
-
await conversationStore().delete(id,
|
|
962
|
+
await conversationStore().delete(id, file);
|
|
968
963
|
}
|
|
969
964
|
catch (error) {
|
|
970
965
|
if (!(error instanceof ConversationNotFoundError))
|
|
@@ -12,7 +12,8 @@ import { scopeRoot, requireScopeRoot, findProjectScopeRoots, userScopeRoot } fro
|
|
|
12
12
|
import { listInstalledPluginsInRoot } from './installed-plugins.js';
|
|
13
13
|
import { profileDir, listProfiles } from './profiles/manifest.js';
|
|
14
14
|
import { canonicalRoot } from './scoped-state/paths.js';
|
|
15
|
-
import { readCachedSettings, readCachedState, revisionOf, SettingsRevisionConflictError, writeSettings } from './scoped-state/person-store.js';
|
|
15
|
+
import { currentSnapshot, readCachedSettings, readCachedState, revisionOf, SettingsRevisionConflictError, writeSettings } from './scoped-state/person-store.js';
|
|
16
|
+
import { importedIntoNorthlight, splitUserSettingsWrite, withAppInstalls } from './scoped-state/imported-mac-installs.js';
|
|
16
17
|
import { withExclusiveDirectoryLock } from './exclusive-lock.js';
|
|
17
18
|
import { SCOPE_CONFIG_KEYS } from './user-settings.js';
|
|
18
19
|
import { normalizeWorkingGerunds } from '../shared/working-activity.js';
|
|
@@ -64,7 +65,10 @@ function readRawAtRoot(root) {
|
|
|
64
65
|
if (canonical !== canonicalRoot(userScopeRoot()))
|
|
65
66
|
return readJsonIfExists(configPathFor(root));
|
|
66
67
|
}
|
|
67
|
-
|
|
68
|
+
const key = settingsOwnerForRoot(root).key;
|
|
69
|
+
const settings = readCachedSettings(key).settings;
|
|
70
|
+
// An imported Mac's installs are the terminal app's block: the control plane keeps none in the user settings.
|
|
71
|
+
return (key === 'user' && importedIntoNorthlight() ? withAppInstalls(currentSnapshot(), settings) : settings);
|
|
68
72
|
}
|
|
69
73
|
/** Replace a user or profile owner's settings through the one write algorithm: `compute` runs against the cached raw settings and
|
|
70
74
|
* runs again if the rows changed underneath it. */
|
|
@@ -72,8 +76,11 @@ async function mutatePersonSettings(key, mutate) {
|
|
|
72
76
|
let value;
|
|
73
77
|
await writeSettings((snapshot) => {
|
|
74
78
|
const current = snapshot.settings[key];
|
|
75
|
-
const
|
|
79
|
+
const appInstalls = key === 'user' && importedIntoNorthlight();
|
|
80
|
+
const result = mutate(structuredClone((appInstalls ? withAppInstalls(snapshot, current ?? null) : current) ?? {}));
|
|
76
81
|
value = result.value;
|
|
82
|
+
if (appInstalls)
|
|
83
|
+
return splitUserSettingsWrite(snapshot, result.next, revisionOf(current));
|
|
77
84
|
return [{ op: 'settings.replace', owner: key, raw: result.next, ifRevision: revisionOf(current) }];
|
|
78
85
|
});
|
|
79
86
|
return value;
|
|
@@ -5,6 +5,8 @@ import { SessionManager } from '@earendil-works/pi-coding-agent';
|
|
|
5
5
|
import { blobStore } from '../blobs/index.js';
|
|
6
6
|
import { openDb, withCanvasWrite } from '../canvas/db.js';
|
|
7
7
|
import { appSpace } from '../layout.js';
|
|
8
|
+
import { timedSpan } from '../logged-step-timings.js';
|
|
9
|
+
import { addStepTiming } from '../step-timings.js';
|
|
8
10
|
import { appendConversationEvents, rootRepromptPending } from '../../daemon/runs/append-section.js';
|
|
9
11
|
import { ConversationNotFoundError } from './index.js';
|
|
10
12
|
const OWNER_ORDER = 's.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC';
|
|
@@ -149,7 +151,7 @@ export function createRowStore() {
|
|
|
149
151
|
const store = {
|
|
150
152
|
async create(nodeId, header, entries, _path) {
|
|
151
153
|
const db = await openDb();
|
|
152
|
-
const node = await db.prepare('SELECT grantee, run_id FROM node_rows WHERE node_id = ?').get(nodeId);
|
|
154
|
+
const node = await timedSpan('owner_read', async () => await db.prepare('SELECT grantee, run_id FROM node_rows WHERE node_id = ?').get(nodeId));
|
|
153
155
|
if (!node)
|
|
154
156
|
throw new Error(`missing conversation owner ${nodeId}`);
|
|
155
157
|
const id = header.id;
|
|
@@ -157,8 +159,9 @@ export function createRowStore() {
|
|
|
157
159
|
const body = encode([header, ...entries]);
|
|
158
160
|
const key = keyFor(nodeId, id, 0);
|
|
159
161
|
const reprompt = node.run_id ? await rootRepromptPending(node.run_id, nodeId, entries) : false;
|
|
160
|
-
|
|
161
|
-
await
|
|
162
|
+
addStepTiming('blob_bytes', Buffer.byteLength(body));
|
|
163
|
+
await timedSpan('blob_put', async () => await (await blobStore()).put(key, body));
|
|
164
|
+
await timedSpan('transaction', () => withCanvasWrite(async (tx) => {
|
|
162
165
|
if (await tx.prepare('SELECT 1 FROM conversation_parts WHERE conversation_id = ?').get(id))
|
|
163
166
|
throw new Error(`conversation already exists: ${id}`);
|
|
164
167
|
const created = at();
|
|
@@ -170,7 +173,7 @@ export function createRowStore() {
|
|
|
170
173
|
const pending = await appendConversationEvents(tx, node.run_id, nodeId, entries, [], reprompt);
|
|
171
174
|
await tx.prepare('UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?').run(entries.at(-1)?.id ?? null, JSON.stringify(pending), id, nodeId);
|
|
172
175
|
}
|
|
173
|
-
});
|
|
176
|
+
}, { timingName: 'create_tx' }));
|
|
174
177
|
return { conversation_id: id, path };
|
|
175
178
|
},
|
|
176
179
|
async append(id, entries) {
|
|
@@ -40,7 +40,7 @@ export async function saveLedger(db, ledger) {
|
|
|
40
40
|
}
|
|
41
41
|
const upserts = [];
|
|
42
42
|
const removes = [];
|
|
43
|
-
const objects = new Set([...before.objects.keys(), ...ledger.objects.keys()]);
|
|
43
|
+
const objects = [...new Set([...before.objects.keys(), ...ledger.objects.keys()])].sort(); // one row lock order for concurrent deliveries
|
|
44
44
|
for (const object of objects) {
|
|
45
45
|
const now = ledger.objects.get(object);
|
|
46
46
|
const was = before.objects.get(object);
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { isSafeNodeId } from '../canvas/paths.js';
|
|
2
2
|
import { OBJECT_TYPE } from '../permissions/builtin.js';
|
|
3
|
-
import { ceilingFrag, readablePackageApps
|
|
3
|
+
import { ceilingFrag, readablePackageApps } from '../permissions/ceiling.js';
|
|
4
4
|
import { compilePermission } from '../permissions/compile.js';
|
|
5
|
-
import { permits, readerUser, resolveReader, subjectSet } from '../permissions/evaluator.js';
|
|
5
|
+
import { ceilingOf, permits, readerUser, resolveReader, subjectSet } from '../permissions/evaluator.js';
|
|
6
6
|
import { loadDefinitions } from '../permissions/schemas.js';
|
|
7
7
|
import { and, or, raw } from '../permissions/sql.js';
|
|
8
8
|
import { flatMapAsync } from '../async-array.js';
|
|
@@ -35,7 +35,7 @@ export async function viewOf(db, reader) {
|
|
|
35
35
|
* schema-typed object has had its facts removed, so only the `permits` branch answers it: its own namespace's app. */
|
|
36
36
|
export async function readableOrDeleted(db, ev, alias) {
|
|
37
37
|
const live = await permits(db, ev, 'read', alias);
|
|
38
|
-
const ceiling = await
|
|
38
|
+
const ceiling = await ceilingOf(db, ev, 'read');
|
|
39
39
|
const grants = compilePermission(await loadDefinitions(db), ev.subjects, OBJECT_TYPE, 'read', raw('gr.id'));
|
|
40
40
|
const chain = { sql: `EXISTS (WITH RECURSIVE up(id, depth) AS (
|
|
41
41
|
SELECT ${alias}.id, 0
|
|
@@ -44,28 +44,15 @@ export async function readableOrDeleted(db, ev, alias) {
|
|
|
44
44
|
const deleted = and([raw(`${alias}.deleted_at IS NOT NULL AND ${alias}.schema_type IS NULL`), ...(ceiling === null ? [] : [ceilingFrag(ceiling, alias)]), chain]);
|
|
45
45
|
return or([live, deleted]);
|
|
46
46
|
}
|
|
47
|
-
// A resolution asks for `readableOrDeleted(ev, 'o')` once per owner in the reader's view, and a corpus resolves every name with one `ev`: each
|
|
48
|
-
// ask recompiled the schema and re-resolved the ceiling (several queries apiece). The fragment depends only on `ev`, which lives for one
|
|
49
|
-
// resolution or one corpus, so compute it once per `ev`.
|
|
50
|
-
const readFrags = new WeakMap();
|
|
51
|
-
function readableFrag(db, ev) {
|
|
52
|
-
let frag = readFrags.get(ev);
|
|
53
|
-
if (frag === undefined) {
|
|
54
|
-
frag = readableOrDeleted(db, ev, 'o');
|
|
55
|
-
frag.catch(() => readFrags.delete(ev));
|
|
56
|
-
readFrags.set(ev, frag);
|
|
57
|
-
}
|
|
58
|
-
return frag;
|
|
59
|
-
}
|
|
60
47
|
/** Whether the reader may read the object `id`, live or deleted. */
|
|
61
48
|
export async function canReadOrDeleted(db, ev, id) {
|
|
62
|
-
const p = await
|
|
49
|
+
const p = await readableOrDeleted(db, ev, 'o');
|
|
63
50
|
const row = await db.prepareUncached(`SELECT ${p.sql} AS ok FROM objects o WHERE o.id = ?`).get(...p.params, id);
|
|
64
51
|
return row?.ok === true;
|
|
65
52
|
}
|
|
66
53
|
/** The documents and custom objects named `name` under `owner` that the reader may read. */
|
|
67
54
|
async function namedObjects(db, ev, owner, name, deleted, stubs = false) {
|
|
68
|
-
const read = await
|
|
55
|
+
const read = await readableOrDeleted(db, ev, 'o');
|
|
69
56
|
return await db.prepareUncached(`SELECT o.* FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0) AND o.owner = ? AND o.name = ? AND o.home_machine IS ${stubs ? 'NOT NULL' : 'NULL'}
|
|
70
57
|
AND o.deleted_at IS ${deleted ? 'NOT NULL' : 'NULL'} AND ${read.sql}${deleted ? ' ORDER BY o.deleted_at DESC' : ''}`).all(owner.id, name, ...read.params);
|
|
71
58
|
}
|
|
@@ -109,7 +96,7 @@ export async function viewResolutions(db, context, names) {
|
|
|
109
96
|
const settled = plain.filter((n) => !ids.has(n));
|
|
110
97
|
for (const n of settled)
|
|
111
98
|
hits.set(n, null);
|
|
112
|
-
const read = await
|
|
99
|
+
const read = await readableOrDeleted(db, context.ev, 'o');
|
|
113
100
|
const rows = await db.prepareUncached(`SELECT o.id, o.owner, o.name FROM objects o WHERE (o.type = 'document' OR strpos(o.type, '.') > 0)
|
|
114
101
|
AND o.owner = ANY(?::text[]) AND o.name = ANY(?::text[]) AND o.home_machine IS NULL AND o.deleted_at IS NULL AND ${read.sql}`)
|
|
115
102
|
.all(context.view.map((o) => o.id), settled, ...read.params);
|
|
@@ -148,7 +135,7 @@ export async function resolveNames(db, reader, raws, context) {
|
|
|
148
135
|
const found = new Map();
|
|
149
136
|
const wanted = [...new Set(normal.values())];
|
|
150
137
|
if (wanted.length > 0) {
|
|
151
|
-
const read = await
|
|
138
|
+
const read = await readableOrDeleted(db, ev, 'o');
|
|
152
139
|
const byId = await db.prepareUncached(`SELECT o.*, ${read.sql} AS readable_ok FROM objects o WHERE o.id = ANY(?::text[])`)
|
|
153
140
|
.all(...read.params, wanted);
|
|
154
141
|
for (const { readable_ok, ...row } of byId)
|
|
@@ -60,7 +60,7 @@ export async function recordWatches(db, items) {
|
|
|
60
60
|
pair.linkApp = opts?.linkApp?.id ?? pair.linkApp;
|
|
61
61
|
pairs.set(key, pair);
|
|
62
62
|
}
|
|
63
|
-
const list = [...pairs.entries()];
|
|
63
|
+
const list = [...pairs.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); // one row lock order for concurrent deliveries
|
|
64
64
|
const col = (f) => list.map(([, p]) => f(p));
|
|
65
65
|
const rows = await db.prepare(`INSERT INTO watches (watch_id, watcher, object, in_tree, read_heads_key, created_at, link_app)
|
|
66
66
|
SELECT v.id, v.watcher, v.object, 0, v.rhk, ?::text, v.link
|