@kabmo-labs/kabmo 0.24.0 → 0.25.0
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/dist/client/index.html +1 -1
- package/dist/client/index.js +579 -510
- package/dist/client/static/js/index-bc9aa4mx.css +1 -0
- package/dist/client/static/js/{index-jcr5twtp.js → index-ga8cbpt4.js} +1072 -1174
- package/package.json +2 -4
- package/src/cli/lib/args.js +24 -1
- package/src/cli/lib/args.test.js +16 -0
- package/src/cli/lib/commands/session.js +233 -0
- package/src/cli/lib/commands/session.test.js +103 -0
- package/src/cli/main.js +1 -1
- package/src/client/components/common/ComposerPicker.tsx +3 -0
- package/src/client/components/common/code-surface/shiki.test.ts +82 -0
- package/src/client/components/common/code-surface/shiki.ts +28 -7
- package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
- package/src/client/components/common/session-actions-menu/index.tsx +33 -2
- package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
- package/src/client/components/common/session-row/index.tsx +27 -1
- package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
- package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
- package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
- package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +36 -5
- package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
- package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
- package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -35
- package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
- package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
- package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
- package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
- package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
- package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
- package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
- package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
- package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
- package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
- package/src/client/components/workspace/chat-timeline/index.tsx +3 -1
- package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
- package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
- package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
- package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
- package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
- package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
- package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
- package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
- package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
- package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
- package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
- package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
- package/src/client/data/settings/omp-schema.json +1 -1
- package/src/client/data/theme/terminal.test.ts +25 -0
- package/src/client/data/theme/terminal.ts +96 -79
- package/src/client/hooks/chat/composer/items.test.ts +12 -26
- package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
- package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
- package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
- package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
- package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
- package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
- package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
- package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
- package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
- package/src/client/hooks/chat/timeline/send.test.ts +3 -1
- package/src/client/hooks/chat/timeline/send.ts +51 -50
- package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
- package/src/client/hooks/models/use-harness-update.test.ts +193 -0
- package/src/client/hooks/models/use-harness-update.ts +202 -0
- package/src/client/hooks/workspace/child-expansion.ts +33 -0
- package/src/client/hooks/workspace/terminal/index.ts +17 -3
- package/src/client/hooks/workspace/terminal/socket.ts +9 -4
- package/src/client/lib/session-tree.test.ts +50 -0
- package/src/client/lib/session-tree.ts +59 -0
- package/src/client/tailwind.css +17 -11
- package/src/server/index.ts +2 -0
- package/src/server/lib/auth/guard.ts +10 -0
- package/src/server/lib/btw/session-copy.server.ts +6 -44
- package/src/server/lib/btw/session-copy.test.ts +2 -1
- package/src/server/lib/db/schema.ts +4 -0
- package/src/server/lib/db/seed-terminal.test.ts +1 -1
- package/src/server/lib/db/seed.test.ts +1 -1
- package/src/server/lib/harness/acp/background-work.test.ts +262 -0
- package/src/server/lib/harness/acp/background-work.ts +320 -0
- package/src/server/lib/harness/acp/client.ts +2 -2
- package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
- package/src/server/lib/harness/acp/gateway-env.ts +70 -0
- package/src/server/lib/harness/acp/prompt.test.ts +20 -0
- package/src/server/lib/harness/acp/prompt.ts +19 -3
- package/src/server/lib/harness/acp/session-background.test.ts +129 -0
- package/src/server/lib/harness/acp/session-exit.ts +31 -0
- package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
- package/src/server/lib/harness/acp/session-handshake.ts +27 -1
- package/src/server/lib/harness/acp/session-listeners.ts +31 -0
- package/src/server/lib/harness/acp/session-requests.ts +47 -0
- package/src/server/lib/harness/acp/session-turns.ts +20 -5
- package/src/server/lib/harness/acp/session.test-util.ts +23 -1
- package/src/server/lib/harness/acp/session.ts +59 -59
- package/src/server/lib/harness/acp/turn.test.ts +81 -0
- package/src/server/lib/harness/acp/turn.ts +26 -9
- package/src/server/lib/harness/acp/verbs.ts +12 -2
- package/src/server/lib/harness/launch.ts +3 -1
- package/src/server/lib/harness/spawn.server.ts +15 -2
- package/src/server/lib/harness/update-job-store.test.ts +126 -0
- package/src/server/lib/harness/update-job-store.ts +109 -0
- package/src/server/lib/harness/update-job.server.ts +203 -0
- package/src/server/lib/harness/update-worker.test.ts +153 -0
- package/src/server/lib/harness/update-worker.ts +197 -0
- package/src/server/lib/lifecycle/paths.ts +23 -0
- package/src/server/lib/omp/rpc/manager.ts +5 -5
- package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
- package/src/server/lib/omp/rpc/session-registry.ts +14 -2
- package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
- package/src/server/lib/omp/session/delete-flow.server.ts +47 -0
- package/src/server/lib/omp/session/delete.server.ts +5 -0
- package/src/server/lib/omp/session/rewind-file.ts +39 -21
- package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
- package/src/server/lib/omp/session/transcript-copy.ts +123 -0
- package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
- package/src/server/lib/sessions/agent-token.server.ts +134 -0
- package/src/server/lib/sessions/answers.server.test.ts +33 -0
- package/src/server/lib/sessions/answers.server.ts +37 -0
- package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
- package/src/server/lib/sessions/dispatch.server.ts +128 -0
- package/src/server/lib/sessions/fork.server.test.ts +209 -0
- package/src/server/lib/sessions/fork.server.ts +304 -0
- package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
- package/src/server/lib/sessions/lifecycle.server.ts +71 -0
- package/src/server/lib/sessions/notify.server.test.ts +112 -0
- package/src/server/lib/sessions/notify.server.ts +212 -0
- package/src/server/lib/sessions/relation-types.ts +76 -0
- package/src/server/lib/sessions/relations.server.test.ts +207 -0
- package/src/server/lib/sessions/relations.server.ts +337 -0
- package/src/server/lib/sessions/resolve.server.ts +106 -0
- package/src/server/lib/sessions/schema.server.ts +82 -0
- package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
- package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
- package/src/server/lib/sessions/spawn.server.test.ts +196 -0
- package/src/server/lib/sessions/spawn.server.ts +310 -0
- package/src/server/lib/terminal/attach-replay.test.ts +2 -2
- package/src/server/lib/terminal/output.test.ts +2 -2
- package/src/server/lib/terminal/output.ts +1 -1
- package/src/server/lib/terminal/resize.test.ts +99 -0
- package/src/server/lib/terminal/runtime.server.ts +26 -6
- package/src/server/lib/terminal/send-result.test.ts +18 -1
- package/src/server/lib/terminal/send-result.ts +26 -2
- package/src/server/lib/terminal/session.server.ts +6 -6
- package/src/server/lib/usage/new-api.test.ts +92 -0
- package/src/server/lib/usage/new-api.ts +131 -0
- package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
- package/src/server/lib/usage/provider-key.ts +33 -0
- package/src/server/lib/usage/providers.server.ts +10 -3
- package/src/server/lib/usage/vendor-balance.server.ts +4 -53
- package/src/server/lib/usage/vendor-http.ts +41 -0
- package/src/server/lib/usage/window.ts +55 -0
- package/src/server/routes/agent/command.ts +14 -1
- package/src/server/routes/agent/harness-command.ts +6 -0
- package/src/server/routes/agent/new.ts +15 -0
- package/src/server/routes/harness/add-provider.test.ts +9 -1
- package/src/server/routes/harness/import-action.ts +4 -0
- package/src/server/routes/harness/import.test.ts +1 -1
- package/src/server/routes/harness/index.ts +5 -1
- package/src/server/routes/harness/update-status.ts +26 -0
- package/src/server/routes/harness/update.test.ts +119 -0
- package/src/server/routes/harness/update.ts +59 -147
- package/src/server/routes/sessions/answer.ts +24 -0
- package/src/server/routes/sessions/batch-delete.ts +11 -5
- package/src/server/routes/sessions/delete.ts +4 -2
- package/src/server/routes/sessions/fork.ts +74 -0
- package/src/server/routes/sessions/index.ts +14 -0
- package/src/server/routes/sessions/relations.ts +85 -0
- package/src/server/routes/sessions/session.ts +4 -0
- package/src/server/routes/sessions/spawn.ts +134 -0
- package/src/server/routes/terminal/ws.ts +3 -3
- package/src/shared/lib/chat/composer/client.ts +31 -2
- package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
- package/src/shared/lib/chat/composer/delegation.ts +206 -0
- package/src/shared/lib/chat/notice-text.ts +1 -1
- package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
- package/src/shared/lib/code/ansi.ts +1 -1
- package/src/shared/lib/fonts/nerd-symbols.css +4 -3
- package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
- package/src/shared/lib/harness/provider-facts.test.ts +27 -0
- package/src/shared/lib/harness/providers.ts +35 -1
- package/src/shared/lib/harness/update-job.ts +33 -0
- package/src/shared/lib/harness/update-plan.test.ts +21 -6
- package/src/shared/lib/harness/update-plan.ts +12 -4
- package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
- package/src/shared/lib/omp/session/wait-idle.ts +12 -2
- package/src/shared/lib/theme/catalog.test.ts +13 -9
- package/src/shared/lib/theme/color.test.ts +2 -2
- package/src/shared/lib/theme/color.ts +4 -4
- package/src/shared/lib/theme/theme.test.ts +1 -1
- package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
- package/src/shared/lib/workspace/terminal/input.ts +33 -0
- package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
- package/src/shared/lib/workspace/terminal/keys.ts +7 -7
- package/src/shared/types/chat.ts +1 -1
- package/src/shared/types/harness-update.ts +65 -0
- package/src/shared/types/omp/agent.ts +19 -2
- package/src/shared/types/workspace.ts +4 -0
- package/src/test-support/fake-omp-fork.ts +16 -2
- package/src/test-support/harness-table.test-util.ts +15 -1
- package/dist/client/static/js/index-z3w7n85q.css +0 -1
- package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
- package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
|
@@ -21,6 +21,7 @@ import { recordSpawnProvenance } from '@/server/lib/omp/rpc/spawn-provenance';
|
|
|
21
21
|
import { registerSpawnedSession } from '@/server/lib/omp/rpc/session-registration';
|
|
22
22
|
import { resolveSessionOwnership, SessionOwnedElsewhereError } from '@/server/lib/omp/session/ownership.server';
|
|
23
23
|
import { claimPrewarmedSession } from '@/server/lib/omp/rpc/prewarm-pool';
|
|
24
|
+
import { mintAgentEnvironment, rememberAgentToken } from '@/server/lib/sessions/agent-token.server';
|
|
24
25
|
import { isUnrestorableModelFailure, resolveResumableModel } from '@/server/lib/omp/session/resumable-model.server';
|
|
25
26
|
import { DEFAULT_APPROVAL_MODE, type ApprovalMode } from '@/shared/lib/omp/config/access-mode';
|
|
26
27
|
import type { SelectedModel } from '@/shared/types/models';
|
|
@@ -308,12 +309,23 @@ export async function startNewRpcSession(
|
|
|
308
309
|
modeEnv?: Record<string, string>,
|
|
309
310
|
): Promise<{ session: AgentSessionWrapper; realSessionId: string }> {
|
|
310
311
|
const mode = approvalMode ?? DEFAULT_APPROVAL_MODE;
|
|
311
|
-
|
|
312
|
+
// Mint here, not at the route: the prewarmed entry and the cold spawn both
|
|
313
|
+
// get a callback credential, and no caller can forget it.
|
|
314
|
+
const { token, env: agentEnv } = mintAgentEnvironment();
|
|
315
|
+
const env = { ...(modeEnv ?? {}), ...agentEnv };
|
|
316
|
+
const wrapper = await claimPrewarmedSession(cwd, mode, env);
|
|
312
317
|
|
|
313
318
|
if (!wrapper) {
|
|
314
|
-
|
|
319
|
+
const started = await startRpcSession(`__new__${Bun.randomUUIDv7()}`, '', cwd, undefined, mode, env);
|
|
320
|
+
await rememberAgentToken(started.realSessionId, token).catch((cause: unknown) => {
|
|
321
|
+
console.error(`[sessions] could not record the agent token for ${started.realSessionId}:`, cause);
|
|
322
|
+
});
|
|
323
|
+
return started;
|
|
315
324
|
}
|
|
316
325
|
|
|
326
|
+
// A claimed prewarmed process recorded its own token before entering the
|
|
327
|
+
// pool; recording this call's token would invalidate the child's environment.
|
|
328
|
+
|
|
317
329
|
const registry = getRegistry();
|
|
318
330
|
const realSessionId = wrapper.sessionId;
|
|
319
331
|
wrapper.onDestroy(() => {
|
|
@@ -34,7 +34,8 @@ import {
|
|
|
34
34
|
import { scheduleQueueDelivery, type QueueDeliveryHost } from '@/server/lib/queue/delivery.server';
|
|
35
35
|
import { requestWaitingSweep } from '@/server/lib/waiting/sweep-trigger';
|
|
36
36
|
import { markStreamStatus, loadStreamStatuses } from '@/shared/lib/omp/session/stream-state.server';
|
|
37
|
-
import { driveGoalAfterTurn } from '@/server/lib/omp/session/goal-driver.server';
|
|
37
|
+
import { driveGoalAfterTurn, lastAssistantText } from '@/server/lib/omp/session/goal-driver.server';
|
|
38
|
+
import { noteChildOutcome } from '@/server/lib/sessions/notify.server';
|
|
38
39
|
import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
|
|
39
40
|
import { publishSidebarStructure } from '@/server/lib/realtime/topics.server';
|
|
40
41
|
|
|
@@ -74,6 +75,25 @@ function endedAborted(host: TerminalSettleHost, messages: unknown): boolean {
|
|
|
74
75
|
);
|
|
75
76
|
}
|
|
76
77
|
|
|
78
|
+
const FAILED_STOP_REASONS: Readonly<Record<string, true>> = { error: true, failed: true, failure: true };
|
|
79
|
+
|
|
80
|
+
/** The failure a terminal frame reports, or null for a normal stop.
|
|
81
|
+
*
|
|
82
|
+
* Conservative on purpose: only an assistant message's own `error` text or an
|
|
83
|
+
* explicit failure stop reason counts. A tool error is not a failed run. */
|
|
84
|
+
function endedFailure(messages: unknown): string | null {
|
|
85
|
+
if (!Array.isArray(messages)) return null;
|
|
86
|
+
for (const entry of messages) {
|
|
87
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue;
|
|
88
|
+
const record = entry as Record<string, unknown>;
|
|
89
|
+
const error = typeof record.error === 'string' ? record.error.trim() : '';
|
|
90
|
+
if (record.role === 'assistant' && error) return error;
|
|
91
|
+
const stop = typeof record.stopReason === 'string' ? record.stopReason : '';
|
|
92
|
+
if (FAILED_STOP_REASONS[stop] === true) return `The run ended with ${stop}`;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
77
97
|
/**
|
|
78
98
|
* Write the terminal stream badge from the ending turn's own stopReason.
|
|
79
99
|
*
|
|
@@ -90,15 +110,43 @@ async function markEndStatus(sessionId: string, host: TerminalSettleHost, messag
|
|
|
90
110
|
}
|
|
91
111
|
|
|
92
112
|
/**
|
|
93
|
-
*
|
|
113
|
+
* Report a refused `prompt` response as a failed child outcome.
|
|
94
114
|
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
* machine, and this function only performs the work the settle triggers.
|
|
115
|
+
* A refused prompt opens no turn, so no `agent_end` will ever settle it. The
|
|
116
|
+
* check lives here because this module already owns the outcome vocabulary.
|
|
98
117
|
*/
|
|
118
|
+
export function noteRefusedPrompt(
|
|
119
|
+
event: { type?: string; success?: unknown; command?: unknown; error?: unknown },
|
|
120
|
+
sessionId: string,
|
|
121
|
+
): void {
|
|
122
|
+
if (event.type !== 'response' || event.success !== false || event.command !== 'prompt' || !sessionId) return;
|
|
123
|
+
void noteChildOutcome({
|
|
124
|
+
sessionId,
|
|
125
|
+
status: 'failed',
|
|
126
|
+
failure: typeof event.error === 'string' ? event.error : 'Prompt failed',
|
|
127
|
+
}).catch((error: unknown) => {
|
|
128
|
+
console.error('[sessions] could not record a refused prompt:', error);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Run the side effects a terminal run end owns. */
|
|
99
133
|
export function settleTerminalRun(host: TerminalSettleHost, messages: unknown): void {
|
|
100
134
|
const aborted = endedAborted(host, messages);
|
|
135
|
+
const failure = aborted ? null : endedFailure(messages);
|
|
101
136
|
if (host.sessionId) void markEndStatus(host.sessionId, host, messages);
|
|
137
|
+
// Delegation is reported here, not from the route: this frame is the only
|
|
138
|
+
// moment that knows a run genuinely ended, and a synthetic `run-settle`
|
|
139
|
+
// reconcile must report the same outcome as a real `agent_end`.
|
|
140
|
+
if (host.sessionId) {
|
|
141
|
+
void noteChildOutcome({
|
|
142
|
+
sessionId: host.sessionId,
|
|
143
|
+
status: aborted ? 'interrupted' : failure ? 'failed' : 'completed',
|
|
144
|
+
output: aborted ? null : lastAssistantText(messages),
|
|
145
|
+
...(failure ? { failure } : {}),
|
|
146
|
+
}).catch((error: unknown) => {
|
|
147
|
+
console.error('[sessions] could not record a child outcome:', error);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
102
150
|
if (!aborted) {
|
|
103
151
|
void triggerAutoSessionTitle(host, 'settle');
|
|
104
152
|
void driveGoalAfterTurn({ host, messages });
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
|
|
30
30
|
import { getLiveSession } from '@/server/lib/omp/rpc/session-registry';
|
|
31
31
|
import { purgeSessionData } from '@/server/lib/omp/session/delete.server';
|
|
32
|
+
import { dependentsDeepestFirst } from '@/server/lib/sessions/lifecycle.server';
|
|
32
33
|
import { purgeBtwForSession } from '@/server/lib/btw/purge.server';
|
|
33
34
|
import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
|
|
34
35
|
import { isMockMode } from '@/server/mock.server';
|
|
@@ -106,3 +107,49 @@ export async function removeSession(sessionId: string): Promise<SessionRemoval>
|
|
|
106
107
|
};
|
|
107
108
|
}
|
|
108
109
|
}
|
|
110
|
+
|
|
111
|
+
export interface SessionTreeRemoval {
|
|
112
|
+
result: SessionRemoval;
|
|
113
|
+
/** Dependents removed before the root, deepest first. */
|
|
114
|
+
removedDependents: string[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function busyRemoval(sessionId: string): SessionRemoval {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
status: 409,
|
|
121
|
+
code: 'session_busy',
|
|
122
|
+
error: `Session ${sessionId} is working. Stop the run before deleting the tree.`,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Remove a session AND its dependents.
|
|
128
|
+
*
|
|
129
|
+
* Every dependent is prechecked for a busy child before anything is deleted: a
|
|
130
|
+
* partial cascade is worse than a refusal, because the user cannot tell which
|
|
131
|
+
* half of the tree disappeared. Deepest first, so a parent never loses the rows
|
|
132
|
+
* that name it before the children are gone.
|
|
133
|
+
*/
|
|
134
|
+
export async function removeSessionTree(sessionId: string): Promise<SessionTreeRemoval> {
|
|
135
|
+
const rootLive = getLiveSession(sessionId);
|
|
136
|
+
if (rootLive?.isAlive() && rootLive.isBusy()) {
|
|
137
|
+
return { result: busyRemoval(sessionId), removedDependents: [] };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const dependents = await dependentsDeepestFirst(sessionId);
|
|
141
|
+
for (const id of dependents) {
|
|
142
|
+
const live = getLiveSession(id);
|
|
143
|
+
if (live?.isAlive() && live.isBusy()) {
|
|
144
|
+
return { result: busyRemoval(id), removedDependents: [] };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const removedDependents: string[] = [];
|
|
149
|
+
for (const id of dependents) {
|
|
150
|
+
const verdict = await removeSession(id);
|
|
151
|
+
if (!verdict.ok) return { result: verdict, removedDependents };
|
|
152
|
+
removedDependents.push(id);
|
|
153
|
+
}
|
|
154
|
+
return { result: await removeSession(sessionId), removedDependents };
|
|
155
|
+
}
|
|
@@ -41,6 +41,7 @@ import { emitRealtimeSignal } from '@/server/lib/realtime/signals.server';
|
|
|
41
41
|
import { failWaitingOn } from '@/server/lib/waiting/store.server';
|
|
42
42
|
import { siblingDirForSession } from '@/server/lib/omp/subagent/history/paths';
|
|
43
43
|
import { isSinglePathSegment } from '@/server/lib/fs/path-segment';
|
|
44
|
+
import { deleteSessionRelations } from '@/server/lib/sessions/relations.server';
|
|
44
45
|
|
|
45
46
|
export interface SessionPurgeResult {
|
|
46
47
|
/** Something keyed to this id existed — a transcript, a mock session row, or
|
|
@@ -83,6 +84,10 @@ async function purgeKabmoRows(db: DbClient, sessionId: string): Promise<number>
|
|
|
83
84
|
changes += result.changes ?? 0;
|
|
84
85
|
}
|
|
85
86
|
const mockRow = await db.run('DELETE FROM sessions WHERE id = ?', [sessionId]);
|
|
87
|
+
// The tree's own rows: this session's relation, incoming edges that would
|
|
88
|
+
// otherwise point at a dead id, and its pending notice/token rows. Cascading
|
|
89
|
+
// DELETE of dependents is a separate, deliberate path (M19).
|
|
90
|
+
await deleteSessionRelations(sessionId).catch(() => {});
|
|
86
91
|
return changes + (mockRow.changes ?? 0);
|
|
87
92
|
}
|
|
88
93
|
|
|
@@ -121,26 +121,15 @@ function resolveCutIndex(
|
|
|
121
121
|
}
|
|
122
122
|
|
|
123
123
|
/**
|
|
124
|
-
* Build the
|
|
125
|
-
*
|
|
126
|
-
*
|
|
124
|
+
* Build the body for a resolved cut index. Shared with the fork path, which
|
|
125
|
+
* resolves its own index (the start of the anchored turn) and must keep the
|
|
126
|
+
* same header-carrying rules as a rewind.
|
|
127
127
|
*/
|
|
128
|
-
export function
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
try {
|
|
134
|
-
parsed = JSON.parse(trimmed);
|
|
135
|
-
} catch {
|
|
136
|
-
return null;
|
|
137
|
-
}
|
|
138
|
-
return isRecord(parsed) ? parsed : null;
|
|
139
|
-
});
|
|
140
|
-
|
|
141
|
-
const cutIndex = resolveCutIndex(records, cut);
|
|
142
|
-
if (cutIndex === undefined) return null;
|
|
143
|
-
|
|
128
|
+
export function buildTruncatedBody(
|
|
129
|
+
records: Array<Record<string, unknown> | null>,
|
|
130
|
+
cutIndex: number,
|
|
131
|
+
options: { requestedEntryId?: string; startedAt?: number } = {},
|
|
132
|
+
): TruncatedSession {
|
|
144
133
|
const kept = records.slice(0, cutIndex);
|
|
145
134
|
const outLines = kept
|
|
146
135
|
.filter((r): r is Record<string, unknown> => Boolean(r))
|
|
@@ -167,14 +156,43 @@ export function truncateSessionBody(body: string, cut: RewindCut): TruncatedSess
|
|
|
167
156
|
// the boundary for stored rows is that same clock — not the next file turn's.
|
|
168
157
|
// Using the file turn's clock kept every command row between the two alive,
|
|
169
158
|
// so undoing one `/usage` left the next one standing after a reload.
|
|
170
|
-
const resolvedByClock =
|
|
159
|
+
const resolvedByClock =
|
|
160
|
+
options.requestedEntryId !== undefined && cutRecord?.id !== options.requestedEntryId;
|
|
171
161
|
return {
|
|
172
162
|
body: `${outLines.join('\n')}\n`,
|
|
173
|
-
overlayCutClock: resolvedByClock
|
|
163
|
+
overlayCutClock: resolvedByClock
|
|
164
|
+
? options.startedAt
|
|
165
|
+
: (cutRecord ? recordClock(cutRecord) : undefined),
|
|
174
166
|
droppedEntryIds,
|
|
175
167
|
};
|
|
176
168
|
}
|
|
177
169
|
|
|
170
|
+
/**
|
|
171
|
+
* Build the truncated body: entries at/after the cut turn are dropped; header
|
|
172
|
+
* records and everything before it survive. Returns null when the cut cannot be
|
|
173
|
+
* resolved at all (an unknown id with no clock, or an id naming a non-turn).
|
|
174
|
+
*/
|
|
175
|
+
export function truncateSessionBody(body: string, cut: RewindCut): TruncatedSession | null {
|
|
176
|
+
const records: Array<Record<string, unknown> | null> = body.split('\n').map((line) => {
|
|
177
|
+
const trimmed = line.trim();
|
|
178
|
+
if (!trimmed) return null;
|
|
179
|
+
let parsed: unknown;
|
|
180
|
+
try {
|
|
181
|
+
parsed = JSON.parse(trimmed);
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
return isRecord(parsed) ? parsed : null;
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
const cutIndex = resolveCutIndex(records, cut);
|
|
189
|
+
if (cutIndex === undefined) return null;
|
|
190
|
+
return buildTruncatedBody(records, cutIndex, {
|
|
191
|
+
requestedEntryId: cut.entryId,
|
|
192
|
+
...(cut.startedAt !== undefined ? { startedAt: cut.startedAt } : {}),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
178
196
|
/**
|
|
179
197
|
* Drop the stored overlay rows the cut invalidated, and ONLY those.
|
|
180
198
|
*
|
|
@@ -31,6 +31,7 @@ import { DEFAULT_HARNESS_ID, HARNESS_IDS } from '@/shared/lib/harness/catalog';
|
|
|
31
31
|
import { knownHarness, loadAcpSessions, loadHarnessBySession } from '@/server/lib/harness/session-store.server';
|
|
32
32
|
import { canonicalPath } from '@/server/lib/fs/canonical';
|
|
33
33
|
import { acpRowsFor } from '@/server/lib/omp/session/acp-rows.server';
|
|
34
|
+
import { decorateSidebarSessions } from '@/server/lib/sessions/sidebar-relations.server';
|
|
34
35
|
import type { SessionWorktreeInfo } from '@/shared/lib/workspace/worktree/types';
|
|
35
36
|
import type { OmpSession } from '@/shared/types/omp/session';
|
|
36
37
|
|
|
@@ -329,9 +330,8 @@ async function buildRealFolders(folderRows: FolderRow[], archivedIds: Set<string
|
|
|
329
330
|
// The scan's own rule is `b.modified.localeCompare(a.modified)`
|
|
330
331
|
// (`groupSessionsByRoot`), so this uses the same key rather than a second
|
|
331
332
|
// definition of "newest".
|
|
332
|
-
const allSessions = [...folderSessions, ...uniqueAcp].sort((a, b) =>
|
|
333
|
-
|
|
334
|
-
);
|
|
333
|
+
const allSessions = [...folderSessions, ...uniqueAcp].sort((a, b) => (b.updated_at ?? b.created_at ?? '').localeCompare(a.updated_at ?? a.created_at ?? ''));
|
|
334
|
+
const visibleSessions = await decorateSidebarSessions(allSessions);
|
|
335
335
|
return {
|
|
336
336
|
id: folder.id,
|
|
337
337
|
name: folder.name,
|
|
@@ -342,9 +342,9 @@ async function buildRealFolders(folderRows: FolderRow[], archivedIds: Set<string
|
|
|
342
342
|
accentColor: folder.accent_color || '',
|
|
343
343
|
icon: folder.icon || 'default',
|
|
344
344
|
customIconUrl: folder.custom_icon_url || undefined,
|
|
345
|
-
sessions:
|
|
346
|
-
hasMore:
|
|
347
|
-
totalSessions:
|
|
345
|
+
sessions: visibleSessions,
|
|
346
|
+
hasMore: visibleSessions.length > 7,
|
|
347
|
+
totalSessions: visibleSessions.length,
|
|
348
348
|
};
|
|
349
349
|
}));
|
|
350
350
|
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The small pieces of omp transcript surgery shared by two features.
|
|
8
|
+
*
|
|
9
|
+
* BTW promotion turns a side-question transcript into a chat; a fork turns a
|
|
10
|
+
* chat into a branch. Both need the same three primitives — read whole lines
|
|
11
|
+
* without a torn tail, find the leaf, and rewrite the title/header pair under a
|
|
12
|
+
* new id — and a second copy of them is how the two drift.
|
|
13
|
+
*
|
|
14
|
+
* The file layout they rely on (verified against omp files): line 1 is a
|
|
15
|
+
* fixed-width title slot, line 2 is the `session` header carrying `id`, `cwd`
|
|
16
|
+
* and `parentSession`, and the rest are entries.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { serializeTitleSlot } from '@/server/lib/omp/session/title-slot';
|
|
20
|
+
|
|
21
|
+
export function parseJsonObject(line: string): Record<string, unknown> | null {
|
|
22
|
+
try {
|
|
23
|
+
const value: unknown = JSON.parse(line);
|
|
24
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
25
|
+
? (value as Record<string, unknown>)
|
|
26
|
+
: null;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The file's lines, minus a torn tail.
|
|
34
|
+
*
|
|
35
|
+
* A snapshot taken while the writer is mid-append can end in a partial line;
|
|
36
|
+
* keeping it would make a resumed child fail to load the transcript.
|
|
37
|
+
*/
|
|
38
|
+
export function completeLines(text: string): string[] {
|
|
39
|
+
const lines = text.split('\n');
|
|
40
|
+
if (lines[lines.length - 1] === '') lines.pop();
|
|
41
|
+
const last = lines[lines.length - 1];
|
|
42
|
+
if (last !== undefined && parseJsonObject(last) === null) lines.pop();
|
|
43
|
+
return lines;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The transcript's leaf: the id of its last entry. */
|
|
47
|
+
export function lastEntryId(lines: string[]): string | null {
|
|
48
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
49
|
+
const record = parseJsonObject(lines[index]);
|
|
50
|
+
if (record && typeof record.id === 'string') return record.id;
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The title slot line, padded to the fixed slot omp rewrites in place, with
|
|
56
|
+
* the trailing newline removed (callers join the lines themselves). */
|
|
57
|
+
export function buildTitleLine(title: string, source: string, updatedAt: string): string {
|
|
58
|
+
const line = serializeTitleSlot({
|
|
59
|
+
title,
|
|
60
|
+
source: source === 'auto' ? 'auto' : 'user',
|
|
61
|
+
updatedAt,
|
|
62
|
+
});
|
|
63
|
+
return line.endsWith('\n') ? line.slice(0, -1) : line;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The chat's own title, from the title slot or the header. */
|
|
67
|
+
export function transcriptTitle(lines: string[]): string {
|
|
68
|
+
for (const line of lines) {
|
|
69
|
+
const record = parseJsonObject(line);
|
|
70
|
+
if (!record) continue;
|
|
71
|
+
if (record.type === 'title' && typeof record.title === 'string') return record.title;
|
|
72
|
+
if (record.type === 'session' && typeof record.title === 'string') return record.title;
|
|
73
|
+
if (record.type === 'session') return '';
|
|
74
|
+
}
|
|
75
|
+
return '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface BranchTranscriptInput {
|
|
79
|
+
lines: string[];
|
|
80
|
+
newId: string;
|
|
81
|
+
timestamp: string;
|
|
82
|
+
title: string;
|
|
83
|
+
/** Absolute path of the file the branch came from, as omp records it. */
|
|
84
|
+
parentSessionFile: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Rewrite a source transcript as a branch under a new identity.
|
|
89
|
+
*
|
|
90
|
+
* The title slot moves to line 1 (dropping the source's slot), and the header
|
|
91
|
+
* gets the new id, the new timestamp, the branch title and the source path.
|
|
92
|
+
* Every other record is copied verbatim — including model/thinking changes,
|
|
93
|
+
* which are what make the resumed child continue with the same selections.
|
|
94
|
+
*/
|
|
95
|
+
export function branchTranscript(input: BranchTranscriptInput): string {
|
|
96
|
+
const body: string[] = [];
|
|
97
|
+
let titleDropped = false;
|
|
98
|
+
let headerWritten = false;
|
|
99
|
+
for (const line of input.lines) {
|
|
100
|
+
const record = parseJsonObject(line);
|
|
101
|
+
if (record?.type === 'title' && !titleDropped) {
|
|
102
|
+
titleDropped = true;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (record?.type === 'session' && !headerWritten) {
|
|
106
|
+
headerWritten = true;
|
|
107
|
+
body.push(
|
|
108
|
+
JSON.stringify({
|
|
109
|
+
...record,
|
|
110
|
+
id: input.newId,
|
|
111
|
+
timestamp: input.timestamp,
|
|
112
|
+
title: input.title,
|
|
113
|
+
titleSource: 'user',
|
|
114
|
+
parentSession: input.parentSessionFile,
|
|
115
|
+
}),
|
|
116
|
+
);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
body.push(line);
|
|
120
|
+
}
|
|
121
|
+
if (!headerWritten) throw new Error('Transcript has no session header');
|
|
122
|
+
return `${[buildTitleLine(input.title, 'user', input.timestamp), ...body].join('\n')}\n`;
|
|
123
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
7
|
+
import { isolateDb, releaseDb } from '@/test-support/isolated-db';
|
|
8
|
+
import { getDb } from '@/server/db.server';
|
|
9
|
+
import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
|
|
10
|
+
import {
|
|
11
|
+
agentTokenScopeForPath,
|
|
12
|
+
createAgentToken,
|
|
13
|
+
hashAgentToken,
|
|
14
|
+
initAgentTokens,
|
|
15
|
+
rememberAgentToken,
|
|
16
|
+
revokeAgentToken,
|
|
17
|
+
verifyAgentToken,
|
|
18
|
+
} from '@/server/lib/sessions/agent-token.server';
|
|
19
|
+
|
|
20
|
+
beforeEach(async () => {
|
|
21
|
+
await isolateDb();
|
|
22
|
+
await ensureSessionRelationsSchema(await getDb());
|
|
23
|
+
globalThis.__kabmoAgentTokens = undefined;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
afterEach(async () => {
|
|
27
|
+
globalThis.__kabmoAgentTokens = undefined;
|
|
28
|
+
await releaseDb();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe('agent tokens', () => {
|
|
32
|
+
test('a remembered token verifies and can be revoked', async () => {
|
|
33
|
+
const token = createAgentToken();
|
|
34
|
+
await rememberAgentToken('s1', token);
|
|
35
|
+
expect(verifyAgentToken(token)).toBe('s1');
|
|
36
|
+
expect(verifyAgentToken('other')).toBeNull();
|
|
37
|
+
|
|
38
|
+
await revokeAgentToken('s1');
|
|
39
|
+
expect(verifyAgentToken(token)).toBeNull();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test('the cache is rebuilt from the table after a restart', async () => {
|
|
43
|
+
const token = createAgentToken();
|
|
44
|
+
await rememberAgentToken('s1', token);
|
|
45
|
+
globalThis.__kabmoAgentTokens = undefined;
|
|
46
|
+
await initAgentTokens();
|
|
47
|
+
expect(verifyAgentToken(token)).toBe('s1');
|
|
48
|
+
// Only the hash is stored.
|
|
49
|
+
const rows = (await (await getDb()).all('SELECT token_hash FROM session_agent_tokens')) as {
|
|
50
|
+
token_hash: string;
|
|
51
|
+
}[];
|
|
52
|
+
expect(rows[0]?.token_hash).toBe(hashAgentToken(token));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('the path scope names the session it may touch', () => {
|
|
56
|
+
expect(agentTokenScopeForPath('/api/sessions/spawn')).toBe('any');
|
|
57
|
+
expect(agentTokenScopeForPath('/api/agent/s1')).toBe('s1');
|
|
58
|
+
expect(agentTokenScopeForPath('/api/chat/s1')).toBe('s1');
|
|
59
|
+
expect(agentTokenScopeForPath('/api/sessions/s1/fork')).toBe('s1');
|
|
60
|
+
expect(agentTokenScopeForPath('/api/sessions/s1/relations')).toBe('s1');
|
|
61
|
+
expect(agentTokenScopeForPath('/api/sessions/s1/archive')).toBeNull();
|
|
62
|
+
expect(agentTokenScopeForPath('/api/settings')).toBeNull();
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The credential an agent uses to call back into Kabmo.
|
|
8
|
+
*
|
|
9
|
+
* A browser has a cookie; a subprocess does not. Every spawned session gets one
|
|
10
|
+
* random token in its environment, and the CLI presents it as a bearer token.
|
|
11
|
+
* Only the SHA-256 hash is stored, so the database cannot be replayed as a
|
|
12
|
+
* credential.
|
|
13
|
+
*
|
|
14
|
+
* The gate is synchronous and runs on every request, so verified hashes are
|
|
15
|
+
* mirrored in memory: `initAgentTokens` loads them once at boot, mint/revoke
|
|
16
|
+
* update both sides. A restart re-reads the table, which is what makes a token
|
|
17
|
+
* outlive the process that minted it.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { getDb } from '@/server/db.server';
|
|
21
|
+
|
|
22
|
+
interface CacheEntry {
|
|
23
|
+
sessionId: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
declare global {
|
|
27
|
+
// eslint-disable-next-line no-var
|
|
28
|
+
var __kabmoAgentTokens: Map<string, CacheEntry> | undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function cache(): Map<string, CacheEntry> {
|
|
32
|
+
globalThis.__kabmoAgentTokens ??= new Map();
|
|
33
|
+
return globalThis.__kabmoAgentTokens;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function hashAgentToken(token: string): string {
|
|
37
|
+
return new Bun.CryptoHasher('sha256').update(token).digest('hex');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Load every non-revoked token hash into the gate's cache. Call once at boot. */
|
|
41
|
+
export async function initAgentTokens(): Promise<void> {
|
|
42
|
+
try {
|
|
43
|
+
const db = await getDb();
|
|
44
|
+
const rows = (await db.all(
|
|
45
|
+
'SELECT session_id, token_hash FROM session_agent_tokens WHERE revoked_at IS NULL',
|
|
46
|
+
)) as { session_id: string; token_hash: string }[];
|
|
47
|
+
const next = new Map<string, CacheEntry>();
|
|
48
|
+
for (const row of rows) next.set(row.token_hash, { sessionId: row.session_id });
|
|
49
|
+
globalThis.__kabmoAgentTokens = next;
|
|
50
|
+
} catch {
|
|
51
|
+
// A database opened before this table existed has no agent credentials;
|
|
52
|
+
// the browser path is unaffected.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A fresh token VALUE, before the session id exists. */
|
|
57
|
+
export function createAgentToken(): string {
|
|
58
|
+
return `kabmo_agent_${crypto.randomUUID().replace(/-/g, '')}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Record the token against the session the spawn actually produced. */
|
|
62
|
+
export async function rememberAgentToken(sessionId: string, token: string): Promise<void> {
|
|
63
|
+
const hash = hashAgentToken(token);
|
|
64
|
+
cache().set(hash, { sessionId });
|
|
65
|
+
const db = await getDb();
|
|
66
|
+
await db.run(
|
|
67
|
+
`INSERT INTO session_agent_tokens (session_id, token_hash, created_at, revoked_at)
|
|
68
|
+
VALUES (?, ?, ?, NULL)
|
|
69
|
+
ON CONFLICT(session_id) DO UPDATE SET token_hash = excluded.token_hash, revoked_at = NULL`,
|
|
70
|
+
[sessionId, hash, Date.now()],
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The session a bearer token identifies, or null. Synchronous by contract. */
|
|
75
|
+
export function verifyAgentToken(token: string | null): string | null {
|
|
76
|
+
if (!token) return null;
|
|
77
|
+
return cache().get(hashAgentToken(token))?.sessionId ?? null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A fresh token and the environment that carries it, for a session that has no
|
|
81
|
+
* id yet. Every spawn path uses this so even a top-level chat can delegate. */
|
|
82
|
+
export function mintAgentEnvironment(): { token: string; env: Record<string, string> } {
|
|
83
|
+
const token = createAgentToken();
|
|
84
|
+
return { token, env: agentEnvironment(token) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The value from an `Authorization: Bearer …` header, or null. */
|
|
88
|
+
export function bearerToken(request: Request): string | null {
|
|
89
|
+
const header = request.headers.get('authorization') ?? '';
|
|
90
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
|
91
|
+
return match?.[1]?.trim() || null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The environment a spawned child needs to reach this server. */
|
|
95
|
+
export function agentEnvironment(token: string): Record<string, string> {
|
|
96
|
+
const port = Number(Bun.env.PORT) || 3000;
|
|
97
|
+
return {
|
|
98
|
+
KABMO_AGENT_TOKEN: token,
|
|
99
|
+
KABMO_SERVER_URL: Bun.env.KABMO_SERVER_URL || `http://localhost:${port}`,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* What a token may touch, by path.
|
|
105
|
+
*
|
|
106
|
+
* `'any'` is only spawn: a child must be allowed to create its own children.
|
|
107
|
+
* Every other path carries the session id it names, and the token must be that
|
|
108
|
+
* session's. A token is not an admin credential.
|
|
109
|
+
*/
|
|
110
|
+
export function agentTokenScopeForPath(pathname: string): 'any' | string | null {
|
|
111
|
+
if (pathname === '/api/sessions/spawn') return 'any';
|
|
112
|
+
const direct = /^\/api\/(?:agent|chat)\/([^/]+)$/.exec(pathname);
|
|
113
|
+
if (direct) return direct[1] ?? null;
|
|
114
|
+
const sub = /^\/api\/sessions\/([^/]+)\/(?:fork|relations|answer)$/.exec(pathname);
|
|
115
|
+
return sub?.[1] ?? null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Drop the in-memory entry for a session whose rows are being purged. */
|
|
119
|
+
export function forgetAgentTokenCache(sessionId: string): void {
|
|
120
|
+
for (const [hash, entry] of cache()) {
|
|
121
|
+
if (entry.sessionId === sessionId) cache().delete(hash);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function revokeAgentToken(sessionId: string): Promise<void> {
|
|
126
|
+
const db = await getDb();
|
|
127
|
+
await db.run('UPDATE session_agent_tokens SET revoked_at = ? WHERE session_id = ?', [
|
|
128
|
+
Date.now(),
|
|
129
|
+
sessionId,
|
|
130
|
+
]);
|
|
131
|
+
for (const [hash, entry] of cache()) {
|
|
132
|
+
if (entry.sessionId === sessionId) cache().delete(hash);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
|
7
|
+
import { isolateDb, releaseDb } from '@/test-support/isolated-db';
|
|
8
|
+
import { getDb } from '@/server/db.server';
|
|
9
|
+
import { ensureSessionRelationsSchema } from '@/server/lib/sessions/schema.server';
|
|
10
|
+
import { loadSessionAnswer, saveSessionAnswer } from '@/server/lib/sessions/answers.server';
|
|
11
|
+
|
|
12
|
+
beforeEach(async () => {
|
|
13
|
+
await isolateDb();
|
|
14
|
+
await ensureSessionRelationsSchema(await getDb());
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
afterEach(async () => {
|
|
18
|
+
await releaseDb();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
describe('session answers', () => {
|
|
22
|
+
test('the last answer wins and whitespace-only text is ignored', async () => {
|
|
23
|
+
await saveSessionAnswer('s1', 'first');
|
|
24
|
+
await saveSessionAnswer('s1', ' ');
|
|
25
|
+
expect(await loadSessionAnswer('s1')).toBe('first');
|
|
26
|
+
await saveSessionAnswer('s1', 'second');
|
|
27
|
+
expect(await loadSessionAnswer('s1')).toBe('second');
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('an unknown session answers null', async () => {
|
|
31
|
+
expect(await loadSessionAnswer('missing')).toBeNull();
|
|
32
|
+
});
|
|
33
|
+
});
|