@north-light/cli 0.3.694 → 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/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 +538 -537
- 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/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/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/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/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 +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-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/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 +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/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/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
|
@@ -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();
|
|
@@ -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;
|
|
@@ -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
|
}
|
|
@@ -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,
|
|
@@ -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) {
|
|
@@ -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)
|
|
@@ -12,6 +12,7 @@ export const ATTACH_CONTROL_BINDINGS = [
|
|
|
12
12
|
{ menuId: 'crtr.tmux.menu.attach.profile-files', actionId: 'crtr.attach.profile-files' },
|
|
13
13
|
{ menuId: 'crtr.tmux.menu.attach.search', actionId: 'crtr.attach.search' },
|
|
14
14
|
{ menuId: 'crtr.tmux.menu.attach.whip', actionId: 'crtr.attach.whip' },
|
|
15
|
+
{ menuId: 'crtr.tmux.menu.attach.reload-viewer', actionId: 'crtr.attach.reload-viewer' },
|
|
15
16
|
];
|
|
16
17
|
const ATTACH_CONTROL_PREFIX = '\x1b_crtr;';
|
|
17
18
|
const ATTACH_CONTROL_SUFFIX = '\x1b\\';
|
|
@@ -69,7 +69,7 @@ export const BINDING_CATALOG = Object.freeze([
|
|
|
69
69
|
...menuEntry('graph', 'Canvas graph', 'Open the canvas graph.', ['g'], ['tmux.menu']),
|
|
70
70
|
...menuEntry('focus-manager', 'Go to manager', 'Focus this node’s manager.', ['h'], ['tmux.menu']),
|
|
71
71
|
...menuEntry('copy-id', 'Copy node id', 'Copy the focused node id to the system clipboard.', ['y'], ['tmux.menu']),
|
|
72
|
-
...menuEntry('reload-viewer', 'Reload viewer', '
|
|
72
|
+
...menuEntry('reload-viewer', 'Reload viewer', 'Restart this pane’s viewer in place on the installed release, keeping its flags and unsent draft.', ['r'], ['tmux.menu']),
|
|
73
73
|
...menuEntry('recap', 'Generate recap', 'Generate the focused node’s Goal and State recap and refresh its generated title.', ['s'], ['tmux.menu']),
|
|
74
74
|
...menuEntry('issues', 'Open create menu', 'Open the create submenu.', ['c'], ['tmux.menu']),
|
|
75
75
|
...menuEntry('issue.idea', 'Create idea', 'Create an idea issue.', ['i'], ['tmux.menu.issue']),
|
|
@@ -89,6 +89,7 @@ export const BINDING_CATALOG = Object.freeze([
|
|
|
89
89
|
...attachEntry('crtr.tmux.menu.attach.file-review', 'crtr.attach.file-review', 'Review a file', 'Open a line-anchored review of a file named in the transcript.', [], ['alt+shift+r']),
|
|
90
90
|
...attachEntry('crtr.tmux.menu.attach.profile-files', 'crtr.attach.profile-files', 'Search profile files', 'Fuzzy-match path segments across the node family’s working directories, their context directories (files), profile projects and the profile’s own directory; Ctrl+Y copies a selected path.', ['f'], ['ctrl+f']),
|
|
91
91
|
...attachEntry('crtr.tmux.menu.attach.search', 'crtr.attach.search', 'Search transcript', 'Search the transcript as it is currently displayed — folded tool output is not searched until it is unfolded.', ['/'], ['alt+/']),
|
|
92
|
+
...attachEntry('crtr.tmux.menu.attach.reload-viewer', 'crtr.attach.reload-viewer', 'Reload viewer', 'Restart this viewer in place on the installed release.', [], []),
|
|
92
93
|
...attachEntry('crtr.tmux.menu.attach.whip', 'crtr.attach.whip', 'Whip agent', 'Interrupt the agent and send a playful command.', ['w'], []),
|
|
93
94
|
b('crtr.attach.scroll.up', 'Attach', 'Scroll up', 'Scroll the transcript one line up.', ['shift+up'], 'terminal', ATTACH_CONTEXTS),
|
|
94
95
|
b('crtr.attach.scroll.down', 'Attach', 'Scroll down', 'Scroll the transcript one line down.', ['shift+down'], 'terminal', ATTACH_CONTEXTS),
|
|
@@ -6,8 +6,12 @@ import { blobStore } from '../blobs/index.js';
|
|
|
6
6
|
import { openDb } from '../canvas/db.js';
|
|
7
7
|
import { chargeOf } from './charges.js';
|
|
8
8
|
const FIELDS = ['id', 'request', 'at', 'month', 'kind', 'what', 'units', 'usd', 'payer', 'funding', 'sub', 'grantee', 'node', 'run', 'provider', 'caused_by', 'vendor_ref', 'refused', 'account', 'billed_usd', 'admission', 'admitted_as', 'cost_usd', 'cost_source'];
|
|
9
|
-
/** The moved rows of a month (or of every month), read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
|
|
9
|
+
/** The moved rows of a month (or of every month), from month `since` on, read once per instance. A chunk row whose blob is missing throws: the rows are nowhere else. */
|
|
10
10
|
export class ChunkRows {
|
|
11
|
+
since;
|
|
12
|
+
constructor(since = '0000-00') {
|
|
13
|
+
this.since = since;
|
|
14
|
+
}
|
|
11
15
|
byMonth = new Map();
|
|
12
16
|
all;
|
|
13
17
|
rows(month) {
|
|
@@ -21,8 +25,8 @@ export class ChunkRows {
|
|
|
21
25
|
return found;
|
|
22
26
|
}
|
|
23
27
|
async load(month) {
|
|
24
|
-
const chunks = await (await openDb()).prepareUncached(`SELECT blob_key FROM charge_chunks
|
|
25
|
-
.all(...(month === undefined ? [] : [month]));
|
|
28
|
+
const chunks = await (await openDb()).prepareUncached(`SELECT blob_key FROM charge_chunks WHERE month >= ?${month === undefined ? '' : ' AND month = ?'} ORDER BY month, payer`)
|
|
29
|
+
.all(this.since, ...(month === undefined ? [] : [month]));
|
|
26
30
|
if (chunks.length === 0)
|
|
27
31
|
return [];
|
|
28
32
|
const store = await blobStore();
|
|
@@ -5,6 +5,6 @@ export { payerOf } from './payer.js';
|
|
|
5
5
|
export { writeCharge, receiptChargeId, chargeOf } from './charges.js';
|
|
6
6
|
export { check, findRefusal, refusalError, refusedMark, userActionOf } from './check.js';
|
|
7
7
|
export { upsertLimit, deleteLimit, listLimits } from './limits.js';
|
|
8
|
-
export { usageFor, listCharges, monthTotals, assertReference } from './read.js';
|
|
8
|
+
export { usageFor, runUsage, listCharges, monthTotals, assertReference } from './read.js';
|
|
9
9
|
export { REBUILD_ALL_TOTALS, rebuildTotalsFor } from './totals.js';
|
|
10
10
|
export { appsHeldBy } from './account.js';
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Everything here reads this runtime only.
|
|
3
3
|
import { openDb } from '../canvas/db.js';
|
|
4
4
|
import { subjectSet } from '../permissions/evaluator.js';
|
|
5
|
+
import { ZERO_RUN_USAGE } from '../../api/dto/run-events.js';
|
|
5
6
|
import { RunError } from '../runs/operations.js';
|
|
6
7
|
import { appsHeldBy } from './account.js';
|
|
7
8
|
import { chargeOf } from './charges.js';
|
|
@@ -118,7 +119,7 @@ function decodeCursor(cursor) {
|
|
|
118
119
|
* is given), otherwise the month's rows (default the current month). */
|
|
119
120
|
export async function listCharges(filter = {}) {
|
|
120
121
|
const limit = Math.min(Math.max(Math.trunc(filter.limit ?? 1000), 1), 10_000);
|
|
121
|
-
const chunks = new ChunkRows();
|
|
122
|
+
const chunks = new ChunkRows(filter.since);
|
|
122
123
|
const conditions = [];
|
|
123
124
|
const params = [];
|
|
124
125
|
const tests = [];
|
|
@@ -164,6 +165,22 @@ export async function listCharges(filter = {}) {
|
|
|
164
165
|
const charges = filter.under !== undefined && filter.reader !== undefined ? await visibleChain(page, filter.reader, chunks) : page;
|
|
165
166
|
return { charges, next: rows.length > limit ? encodeCursor(page[limit - 1]) : null };
|
|
166
167
|
}
|
|
168
|
+
/** A run's usage, summed from the rows under `run:<id>` when read (refused and take rows excluded): the ledger is its only copy. */
|
|
169
|
+
export async function runUsage(runId) {
|
|
170
|
+
const usage = { ...ZERO_RUN_USAGE }, since = (await (await openDb()).prepare('SELECT created FROM nodes WHERE node_id = ?').get(runId))?.created.slice(0, 7);
|
|
171
|
+
for (let page; page === undefined || page.next !== null;) {
|
|
172
|
+
page = await listCharges({ under: `run:${runId}`, since, limit: 10_000, ...(page?.next ? { after: page.next } : {}) });
|
|
173
|
+
for (const row of page.charges.filter((charge) => charge.refused === null && charge.kind !== 'take')) {
|
|
174
|
+
const units = (row.kind === 'model' ? row.units ?? {} : {});
|
|
175
|
+
usage.input_tokens += units.input ?? 0;
|
|
176
|
+
usage.output_tokens += units.output ?? 0;
|
|
177
|
+
usage.cache_read_tokens += units.cache_read ?? 0;
|
|
178
|
+
usage.cache_write_tokens += units.cache_write ?? 0;
|
|
179
|
+
usage.cost_usd += Number(row.usd ?? 0);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return usage;
|
|
183
|
+
}
|
|
167
184
|
/** The payers a `user:<id>` answers for: itself, and every app held (`ledger_holder`) by it or by a team it belongs to. */
|
|
168
185
|
export async function payersOf(owner) {
|
|
169
186
|
const db = await openDb();
|
|
@@ -530,7 +530,7 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
|
|
|
530
530
|
// When the endpoint's admission row (id `admission:<id>`) is already in this ledger, this insert is a no-op. Otherwise it is the only row
|
|
531
531
|
// the local `grant:<id>` limit can count, so it carries the list-price amount: a null usd rolls up as zero and the cap never refuses.
|
|
532
532
|
if (spend !== undefined && paid !== null) {
|
|
533
|
-
await writeCharge({ id: chargeId, request: spend.request ?? id, kind: 'model', what: answered, usd: usage.usd_equivalent, payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, node: spend.node ?? null, run: spend.run ?? null, provider, causedBy: await causeOf(), vendorRef });
|
|
533
|
+
await writeCharge({ id: chargeId, request: spend.request ?? id, kind: 'model', what: answered, units: { input: completed.usage.input, output: completed.usage.output, cache_read: completed.usage.cacheRead, cache_write: completed.usage.cacheWrite }, usd: usage.usd_equivalent, payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, node: spend.node ?? null, run: spend.run ?? null, provider, causedBy: await causeOf(), vendorRef });
|
|
534
534
|
}
|
|
535
535
|
}
|
|
536
536
|
else if (spend !== undefined && paid !== null) {
|
|
@@ -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.
|