@cortex-agent/server 2026.10.15-2 → 2026.10.21
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 +70 -31
- package/defaults/board/board.css +140 -62
- package/defaults/board/scaffold.html +36 -13
- package/defaults/plugins/cortex-board/skills/board/SKILL.md +30 -22
- package/defaults/plugins/cortex-system/plugin.json +2 -2
- package/defaults/plugins/cortex-system/skills/browser/SKILL.md +56 -0
- package/dist/agent-adapter/claude/adapter.d.ts +2 -5
- package/dist/agent-adapter/claude/adapter.js +6 -5
- package/dist/agent-adapter/claude/assistant-blocks.d.ts +5 -0
- package/dist/agent-adapter/claude/assistant-blocks.js +61 -0
- package/dist/agent-adapter/claude/cache-refresh.d.ts +58 -0
- package/dist/agent-adapter/claude/cache-refresh.js +145 -0
- package/dist/agent-adapter/claude/cache-touch.d.ts +12 -0
- package/dist/agent-adapter/claude/cache-touch.js +75 -0
- package/dist/agent-adapter/claude/event-parser.d.ts +8 -3
- package/dist/agent-adapter/claude/event-parser.js +33 -17
- package/dist/agent-adapter/claude/event-translator.d.ts +2 -0
- package/dist/agent-adapter/claude/event-translator.js +2 -0
- package/dist/agent-adapter/claude/session-options.d.ts +0 -4
- package/dist/agent-adapter/claude/session-options.js +0 -9
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +2 -5
- package/dist/agent-adapter/claude/transcript-clear.d.ts +42 -0
- package/dist/agent-adapter/claude/transcript-clear.js +217 -0
- package/dist/agent-adapter/claude/turn-machine.d.ts +3 -2
- package/dist/agent-adapter/claude/turn-machine.js +21 -68
- package/dist/agent-adapter/claude/window-warmup.d.ts +13 -0
- package/dist/agent-adapter/claude/window-warmup.js +38 -0
- package/dist/agent-adapter/continuation-phase.js +3 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +8 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +1 -1
- package/dist/agent-adapter/pi/event-parser.js +43 -27
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +1 -1
- package/dist/agent-adapter/pi/pi-session.d.ts +2 -0
- package/dist/agent-adapter/pi/pi-session.js +15 -0
- package/dist/agent-adapter/pi/session-options.d.ts +2 -6
- package/dist/agent-adapter/pi/session-options.js +2 -11
- package/dist/agent-adapter/run-events.d.ts +10 -0
- package/dist/agent-adapter/run-events.js +2 -0
- package/dist/agent-adapter/types.d.ts +1 -1
- package/dist/client-bundle/manifest.json +1 -1
- package/dist/core/locales/en.d.ts +1 -0
- package/dist/core/locales/slices/commands.d.ts +1 -0
- package/dist/core/locales/slices/commands.js +2 -0
- package/dist/core/settings-spec.d.ts +25 -0
- package/dist/core/settings-spec.js +34 -0
- package/dist/domain/agents/engine-selection.js +1 -1
- package/dist/domain/agents/subagent/registry.d.ts +2 -0
- package/dist/domain/agents/subagent/registry.js +8 -0
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/browser/broker.d.ts +99 -0
- package/dist/domain/browser/broker.js +487 -0
- package/dist/domain/costs/claude-account.js +21 -0
- package/dist/domain/costs/rate-limit-throttle.js +3 -1
- package/dist/domain/costs/reset-account.d.ts +2 -0
- package/dist/domain/costs/usage-service.d.ts +1 -1
- package/dist/domain/costs/usage-service.js +20 -7
- package/dist/domain/mcp/tools/ui-file.js +1 -1
- package/dist/domain/remote/device-browser.js +1 -1
- package/dist/domain/remote/device-chrome-commands.js +2 -0
- package/dist/domain/remote/device-port.js +2 -2
- package/dist/domain/runs/builders.d.ts +2 -2
- package/dist/domain/runs/builders.js +2 -3
- package/dist/domain/runs/engine-spec.d.ts +5 -0
- package/dist/domain/runs/engine-spec.js +1 -2
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-lifecycle.d.ts +0 -4
- package/dist/domain/sessions/session-lifecycle.js +1 -1
- package/dist/domain/system/own-bin-path.d.ts +13 -0
- package/dist/domain/system/own-bin-path.js +36 -0
- package/dist/domain/system/terminal-cli/index.d.ts +58 -0
- package/dist/domain/system/terminal-cli/index.js +100 -0
- package/dist/domain/system/terminal-cli/posix-profiles.d.ts +23 -0
- package/dist/domain/system/terminal-cli/posix-profiles.js +74 -0
- package/dist/domain/system/terminal-cli/registrar.d.ts +12 -0
- package/dist/domain/system/terminal-cli/registrar.js +1 -0
- package/dist/domain/system/terminal-cli/shims.d.ts +27 -0
- package/dist/domain/system/terminal-cli/shims.js +108 -0
- package/dist/domain/system/terminal-cli/state.d.ts +7 -0
- package/dist/domain/system/terminal-cli/state.js +36 -0
- package/dist/domain/system/terminal-cli/windows-user-path.d.ts +13 -0
- package/dist/domain/system/terminal-cli/windows-user-path.js +67 -0
- package/dist/domain/tui-session/tui-session-service.js +1 -1
- package/dist/domain/tui-session/types.d.ts +1 -1
- package/dist/domain/ui-service/app-router.d.ts +17 -6
- package/dist/domain/ui-service/app-router.js +3 -1
- package/dist/domain/ui-service/assistant-snapshots.js +2 -0
- package/dist/domain/ui-service/inline-media-types.d.ts +18 -0
- package/dist/domain/ui-service/inline-media-types.js +1 -0
- package/dist/domain/ui-service/input-schemas.d.ts +17 -17
- package/dist/domain/ui-service/input-schemas.js +9 -9
- package/dist/domain/ui-service/mutate/models.d.ts +3 -0
- package/dist/domain/ui-service/mutate/models.js +21 -2
- package/dist/domain/ui-service/mutate/resolve-media.d.ts +4 -0
- package/dist/domain/ui-service/mutate/resolve-media.js +17 -0
- package/dist/domain/ui-service/mutate/sessions.js +1 -4
- package/dist/domain/ui-service/query/sessions.js +1 -1
- package/dist/domain/ui-service/types.d.ts +8 -10
- package/dist/domain/ui-service/ui-service.d.ts +9 -6
- package/dist/domain/ui-service/ui-service.js +4 -1
- package/dist/entry/app.js +23 -0
- package/dist/entry/browser-cli.d.ts +39 -0
- package/dist/entry/browser-cli.js +317 -0
- package/dist/entry/cli-help.d.ts +1 -0
- package/dist/entry/cli-help.js +30 -0
- package/dist/entry/cli.js +2 -0
- package/dist/entry/daemon.js +2 -0
- package/dist/entry/path-cli.d.ts +4 -0
- package/dist/entry/path-cli.js +65 -0
- package/dist/entry/shutdown.js +7 -0
- package/dist/entry/start-ui-http.js +8 -0
- package/dist/entry/ui-service-wiring.js +2 -0
- package/dist/events/event-types.d.ts +2 -1
- package/dist/orchestration/agent-runner.d.ts +2 -2
- package/dist/orchestration/agent-runner.js +6 -6
- package/dist/orchestration/browser-webhook.d.ts +11 -0
- package/dist/orchestration/browser-webhook.js +28 -0
- package/dist/orchestration/cache-keep-warm.d.ts +77 -0
- package/dist/orchestration/cache-keep-warm.js +213 -0
- package/dist/orchestration/claude-window-warmup.d.ts +40 -0
- package/dist/orchestration/claude-window-warmup.js +126 -0
- package/dist/orchestration/conversation-request.d.ts +4 -7
- package/dist/orchestration/conversation-request.js +1 -2
- package/dist/orchestration/delta-coalescer.d.ts +4 -2
- package/dist/orchestration/delta-coalescer.js +5 -5
- package/dist/orchestration/edit-retry.js +3 -6
- package/dist/orchestration/inline-media-eager.d.ts +13 -0
- package/dist/orchestration/inline-media-eager.js +58 -0
- package/dist/orchestration/inline-media.d.ts +22 -0
- package/dist/orchestration/inline-media.js +151 -0
- package/dist/orchestration/interactions/ask-user-resume.js +3 -7
- package/dist/orchestration/routing/commands/usage-format.js +3 -0
- package/dist/orchestration/routing/webhook.js +4 -0
- package/dist/orchestration/session-compact.js +5 -7
- package/dist/orchestration/session-events.d.ts +2 -1
- package/dist/orchestration/session-events.js +1 -0
- package/dist/orchestration/transcript-sink.d.ts +6 -0
- package/dist/orchestration/transcript-sink.js +21 -2
- package/dist/orchestration/turn/turn-prep.d.ts +0 -8
- package/dist/orchestration/turn/turn-prep.js +0 -51
- package/dist/orchestration/turn/turn.js +4 -0
- package/dist/platform/adapters/tui/ports.d.ts +1 -1
- package/dist/platform/adapters/tui/tui-transcript.js +2 -0
- package/dist/platform/browser/agent-browser.d.ts +50 -0
- package/dist/platform/browser/agent-browser.js +165 -0
- package/dist/platform/browser/managed-browser.d.ts +1 -11
- package/dist/platform/browser/managed-browser.js +4 -12
- package/dist/platform/ui-http/browser-stream.d.ts +110 -0
- package/dist/platform/ui-http/browser-stream.js +447 -0
- package/dist/platform/ui-http/ui-http-server.d.ts +12 -0
- package/dist/platform/ui-http/ui-http-server.js +23 -6
- package/dist/store/conversation-history-reader.js +8 -0
- package/dist/store/conversation-history-repo.d.ts +8 -1
- package/dist/store/conversation-history-repo.js +5 -0
- package/dist/store/session-registry-journal.d.ts +0 -8
- package/dist/store/session-registry-journal.js +5 -17
- package/dist/store/session-registry-repo.d.ts +2 -3
- package/dist/store/session-registry-repo.js +0 -2
- package/package.json +4 -2
- package/web/dist/assets/board-math-css-CB4GJ6qO.js +2 -0
- package/web/dist/assets/index-CaSZPg_H.css +1 -0
- package/web/dist/assets/index-CzOR7Edh.js +522 -0
- package/web/dist/assets/{index-DaViXAg-.js → index-cIGFv27z.js} +1 -1
- package/web/dist/index.html +3 -2
- package/web/dist/theme.css +6 -0
- package/dist/agent-adapter/browser-mcp-server.d.ts +0 -13
- package/dist/agent-adapter/browser-mcp-server.js +0 -28
- package/dist/agent-adapter/claude/browser-mcp.d.ts +0 -9
- package/dist/agent-adapter/claude/browser-mcp.js +0 -10
- package/web/dist/assets/index-Cgx3gdHV.css +0 -1
- package/web/dist/assets/index-CpZWBVHr.js +0 -494
|
@@ -8,6 +8,7 @@ export interface DeltaFlush {
|
|
|
8
8
|
text: string;
|
|
9
9
|
/** 0 for a block's first published event, +1 per event after that. Lets a consumer detect gaps. */
|
|
10
10
|
seq: number;
|
|
11
|
+
kind?: 'thinking';
|
|
11
12
|
}
|
|
12
13
|
export interface DeltaCoalescerOptions {
|
|
13
14
|
onFlush: (flush: DeltaFlush) => void;
|
|
@@ -16,7 +17,7 @@ export interface DeltaCoalescerOptions {
|
|
|
16
17
|
}
|
|
17
18
|
export interface DeltaCoalescer {
|
|
18
19
|
/** Accumulate one incremental chunk. Empty chunks are ignored. */
|
|
19
|
-
push(blockId: string, text: string): void;
|
|
20
|
+
push(blockId: string, text: string, kind?: 'thinking'): void;
|
|
20
21
|
/** Publish what is pending for `blockId` (or for every block when omitted) right now. Callers
|
|
21
22
|
* MUST do this before the block's complete message goes out, so the preview never trails the
|
|
22
23
|
* authoritative text. */
|
|
@@ -32,7 +33,7 @@ export declare function resolveFlushMs(env: Record<string, string | undefined>):
|
|
|
32
33
|
export declare function createDeltaCoalescer(opts: DeltaCoalescerOptions): DeltaCoalescer;
|
|
33
34
|
export interface SessionDeltaStream {
|
|
34
35
|
/** Feed one incremental chunk from the adapter. */
|
|
35
|
-
onDelta(text: string, blockId: string): void;
|
|
36
|
+
onDelta(text: string, blockId: string, kind?: 'thinking'): void;
|
|
36
37
|
/** Publish what is pending — call this immediately before the block's complete message. */
|
|
37
38
|
flush(blockId?: string): void;
|
|
38
39
|
/** End of turn: cancel timers, drop anything unpublished. */
|
|
@@ -62,6 +63,7 @@ export declare function createSessionDeltaStream(args: {
|
|
|
62
63
|
blockId: string;
|
|
63
64
|
text: string;
|
|
64
65
|
seq: number;
|
|
66
|
+
kind?: 'thinking';
|
|
65
67
|
}) => void;
|
|
66
68
|
flushMs?: number;
|
|
67
69
|
}): SessionDeltaStream | null;
|
|
@@ -29,7 +29,7 @@ export function createDeltaCoalescer(opts) {
|
|
|
29
29
|
}
|
|
30
30
|
if (state.pending.length === 0)
|
|
31
31
|
return;
|
|
32
|
-
const flush = { blockId, text: state.pending, seq: state.seq };
|
|
32
|
+
const flush = { blockId, text: state.pending, seq: state.seq, ...(state.kind ? { kind: state.kind } : {}) };
|
|
33
33
|
state.pending = '';
|
|
34
34
|
state.seq += 1;
|
|
35
35
|
// A failing sink is not the streaming path's problem: the block keeps accumulating and the
|
|
@@ -40,12 +40,12 @@ export function createDeltaCoalescer(opts) {
|
|
|
40
40
|
catch { /* contained on purpose */ }
|
|
41
41
|
}
|
|
42
42
|
return {
|
|
43
|
-
push(blockId, text) {
|
|
43
|
+
push(blockId, text, kind) {
|
|
44
44
|
if (disposed || !text)
|
|
45
45
|
return;
|
|
46
46
|
let state = blocks.get(blockId);
|
|
47
47
|
if (!state) {
|
|
48
|
-
state = { pending: '', seq: 0, timer: null };
|
|
48
|
+
state = { pending: '', seq: 0, timer: null, kind };
|
|
49
49
|
blocks.set(blockId, state);
|
|
50
50
|
}
|
|
51
51
|
state.pending += text;
|
|
@@ -110,10 +110,10 @@ export function createSessionDeltaStream(args) {
|
|
|
110
110
|
const publish = args.publish ?? publishSessionMessageDelta;
|
|
111
111
|
const coalescer = createDeltaCoalescer({
|
|
112
112
|
flushMs: args.flushMs,
|
|
113
|
-
onFlush: (
|
|
113
|
+
onFlush: (flush) => publish({ sessionId, channel, ...flush }),
|
|
114
114
|
});
|
|
115
115
|
return {
|
|
116
|
-
onDelta: (text, blockId) => coalescer.push(blockId, text),
|
|
116
|
+
onDelta: (text, blockId, kind) => coalescer.push(blockId, text, kind),
|
|
117
117
|
flush: (blockId) => coalescer.flush(blockId),
|
|
118
118
|
dispose: () => coalescer.dispose(),
|
|
119
119
|
};
|
|
@@ -10,7 +10,6 @@ import { buildUserProcessingMessage, writeStatus, buildStatusActionBlocks, initS
|
|
|
10
10
|
import { initTurnTracking, finishTurnTracking, consumePendingTurnSupersession, } from './turn/turn-tracking.js';
|
|
11
11
|
import { handleAgentError } from './turn/terminal.js';
|
|
12
12
|
import { openTurn } from './turn/turn.js';
|
|
13
|
-
import { withTurnBrowser } from './turn/turn-prep.js';
|
|
14
13
|
import { prepareConversationRequest } from './conversation-request.js';
|
|
15
14
|
export function reprocessMessage(channel, text, adapter, opts) {
|
|
16
15
|
trackPendingTask(+1);
|
|
@@ -70,8 +69,7 @@ export async function runRetryAgent(args) {
|
|
|
70
69
|
return;
|
|
71
70
|
const backendSessionId = session ? effectiveBackendSessionId(session) : null;
|
|
72
71
|
const projectId = session?.projectId ?? 'general';
|
|
73
|
-
|
|
74
|
-
await withTurnBrowser({ backend, browser: session?.browser ?? null }, (cdpEndpoint) => openTurn({
|
|
72
|
+
await openTurn({
|
|
75
73
|
channel, adapter, threadAnchorId: null,
|
|
76
74
|
session: { sessionId, backendSessionId, projectId, lease: leased.lease },
|
|
77
75
|
// RAW text: what the ledger recorded and what an auto-resume would replay.
|
|
@@ -83,10 +81,9 @@ export async function runRetryAgent(args) {
|
|
|
83
81
|
startTime,
|
|
84
82
|
// The retry replays a message a human wrote, on the session's live engine: a user turn.
|
|
85
83
|
prepareRequest: (ids) => prepareConversationRequest({
|
|
86
|
-
ids, channel, session, userMessage: text || '',
|
|
87
|
-
browserCdpEndpoint: cdpEndpoint, trigger: 'edit-retry',
|
|
84
|
+
ids, channel, session, userMessage: text || '', trigger: 'edit-retry',
|
|
88
85
|
}),
|
|
89
|
-
})
|
|
86
|
+
});
|
|
90
87
|
}
|
|
91
88
|
/** The retry's session lease (none for a channel without a session), or null when it could not be
|
|
92
89
|
* taken — in which case the failure is already rendered and the ledger turn closed. */
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { snapshotInlineMedia } from './inline-media.js';
|
|
2
|
+
import type { ResolveMediaInput } from '../domain/ui-service/inline-media-types.js';
|
|
3
|
+
type MessageMedia = Omit<ResolveMediaInput, 'src'> & {
|
|
4
|
+
text: string;
|
|
5
|
+
};
|
|
6
|
+
interface EagerDeps {
|
|
7
|
+
snapshot: typeof snapshotInlineMedia;
|
|
8
|
+
warn: (message: string) => void;
|
|
9
|
+
}
|
|
10
|
+
export declare function extractMediaSources(markdown: string): string[];
|
|
11
|
+
/** Called after the row is durable; an unavailable image must never fail the assistant turn. */
|
|
12
|
+
export declare function eagerSnapshotInlineMedia(message: MessageMedia, deps?: EagerDeps): Promise<void>;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createLogger } from '../core/log.js';
|
|
2
|
+
import { parseMediaSrc, snapshotInlineMedia } from './inline-media.js';
|
|
3
|
+
const log = createLogger('inline-media');
|
|
4
|
+
const defaults = { snapshot: snapshotInlineMedia, warn: message => log.warn(message) };
|
|
5
|
+
// Match web/src/lib/markdown.ts: destinations are verbatim, not CommonMark-normalized.
|
|
6
|
+
const TARGET = String.raw `(?:[^()]|\((?:[^()]|\([^()]*\))*\))+`;
|
|
7
|
+
const INLINE_MEDIA = new RegExp([
|
|
8
|
+
String.raw `\*\*[^*]+\*\*`,
|
|
9
|
+
String.raw `(?<ticks>\x60+).*?\k<ticks>`,
|
|
10
|
+
String.raw `!\[[^\]]*\]\((?<src>${TARGET})\)`,
|
|
11
|
+
String.raw `\[[^\]]+\]\(${TARGET}\)`,
|
|
12
|
+
String.raw `\*[^*]+\*`,
|
|
13
|
+
String.raw `_[^_]+_`,
|
|
14
|
+
].join('|'), 'g');
|
|
15
|
+
function withoutFencedCode(markdown) {
|
|
16
|
+
const body = [];
|
|
17
|
+
let fence;
|
|
18
|
+
for (const line of markdown.replace(/\r\n/g, '\n').split('\n')) {
|
|
19
|
+
if (fence) {
|
|
20
|
+
const trimmed = line.trim();
|
|
21
|
+
if (trimmed.length >= fence.length && [...trimmed].every(char => char === fence.marker))
|
|
22
|
+
fence = undefined;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
|
|
26
|
+
if (opening && !(opening[1][0] === '`' && opening[2].includes('`'))) {
|
|
27
|
+
fence = { marker: opening[1][0], length: opening[1].length };
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
body.push(line);
|
|
31
|
+
}
|
|
32
|
+
return body.join('\n');
|
|
33
|
+
}
|
|
34
|
+
export function extractMediaSources(markdown) {
|
|
35
|
+
const sources = new Set();
|
|
36
|
+
for (const match of withoutFencedCode(markdown).matchAll(INLINE_MEDIA)) {
|
|
37
|
+
if (match.groups?.src)
|
|
38
|
+
sources.add(match.groups.src);
|
|
39
|
+
}
|
|
40
|
+
return [...sources];
|
|
41
|
+
}
|
|
42
|
+
async function snapshotReference(message, src, deps) {
|
|
43
|
+
try {
|
|
44
|
+
const source = parseMediaSrc(src);
|
|
45
|
+
if (source.type !== 'local' && source.type !== 'device')
|
|
46
|
+
return;
|
|
47
|
+
const result = await deps.snapshot({ sessionId: message.sessionId, ts: message.ts, src });
|
|
48
|
+
if ('error' in result)
|
|
49
|
+
deps.warn(`Inline media snapshot failed (${result.error.code}): ${src}: ${result.error.reason}`);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
deps.warn(`Inline media snapshot failed: ${src}: ${String(error)}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** Called after the row is durable; an unavailable image must never fail the assistant turn. */
|
|
56
|
+
export async function eagerSnapshotInlineMedia(message, deps = defaults) {
|
|
57
|
+
await Promise.all(extractMediaSources(message.text).map(src => snapshotReference(message, src, deps)));
|
|
58
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ResolveMediaInput, ResolveMediaResult } from '../domain/ui-service/inline-media-types.js';
|
|
2
|
+
export declare const MAX_INLINE_MEDIA_BYTES: number;
|
|
3
|
+
type FileSource = {
|
|
4
|
+
type: 'local';
|
|
5
|
+
filePath: string;
|
|
6
|
+
} | {
|
|
7
|
+
type: 'device';
|
|
8
|
+
device: string;
|
|
9
|
+
filePath: string;
|
|
10
|
+
};
|
|
11
|
+
export type MediaSource = FileSource | {
|
|
12
|
+
type: 'workspace';
|
|
13
|
+
path: string;
|
|
14
|
+
} | {
|
|
15
|
+
type: 'https';
|
|
16
|
+
url: string;
|
|
17
|
+
};
|
|
18
|
+
/** Device names are configuration keys, not arbitrary URI schemes or currently-online devices. */
|
|
19
|
+
export declare function parseMediaSrc(src: string): MediaSource;
|
|
20
|
+
/** First successful snapshot wins for this message/source; failures are retryable. */
|
|
21
|
+
export declare function snapshotInlineMedia(input: ResolveMediaInput): Promise<ResolveMediaResult>;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { DATA_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
|
|
6
|
+
import { getMachineRegistry } from '../domain/remote/machine-registry.js';
|
|
7
|
+
import { fetchRemoteFile, prepareRemoteFetch } from '../domain/remote/device-file.js';
|
|
8
|
+
export const MAX_INLINE_MEDIA_BYTES = 200 * 1024 * 1024;
|
|
9
|
+
const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp', '.ico', '.avif']);
|
|
10
|
+
const VIDEO_EXTENSIONS = new Set(['.mp4', '.webm', '.mov', '.m4v']);
|
|
11
|
+
const inFlight = new Map();
|
|
12
|
+
class MediaError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, reason) {
|
|
15
|
+
super(reason);
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Device names are configuration keys, not arbitrary URI schemes or currently-online devices. */
|
|
20
|
+
export function parseMediaSrc(src) {
|
|
21
|
+
if (!src || src.includes('\0'))
|
|
22
|
+
throw new MediaError('unsupported', 'Invalid media source');
|
|
23
|
+
if (/^https:\/\//i.test(src))
|
|
24
|
+
return { type: 'https', url: new URL(src).href };
|
|
25
|
+
if (src.startsWith('workspace/')) {
|
|
26
|
+
if (!resolveWorkspaceRelPath(src))
|
|
27
|
+
throw new MediaError('unsupported', 'Invalid workspace path');
|
|
28
|
+
return { type: 'workspace', path: src };
|
|
29
|
+
}
|
|
30
|
+
return parseFileSource(src);
|
|
31
|
+
}
|
|
32
|
+
function parseFileSource(src) {
|
|
33
|
+
if (src.startsWith('~/'))
|
|
34
|
+
return { type: 'local', filePath: path.join(os.homedir(), src.slice(2)) };
|
|
35
|
+
if (path.isAbsolute(src))
|
|
36
|
+
return { type: 'local', filePath: src };
|
|
37
|
+
const device = /^([^:/\\]+):(.*)$/s.exec(src);
|
|
38
|
+
if (!device)
|
|
39
|
+
return { type: 'local', filePath: path.resolve(DATA_DIR, src) };
|
|
40
|
+
return parseDeviceSource(device[1], device[2]);
|
|
41
|
+
}
|
|
42
|
+
function parseDeviceSource(device, filePath) {
|
|
43
|
+
const registered = Object.hasOwn(getMachineRegistry(), device);
|
|
44
|
+
const absolute = path.posix.isAbsolute(filePath) || path.win32.isAbsolute(filePath);
|
|
45
|
+
if (!registered || !absolute)
|
|
46
|
+
throw new MediaError('unsupported', 'Unknown device or non-absolute device path');
|
|
47
|
+
return { type: 'device', device, filePath };
|
|
48
|
+
}
|
|
49
|
+
function mediaKind(ext) {
|
|
50
|
+
if (VIDEO_EXTENSIONS.has(ext))
|
|
51
|
+
return 'video';
|
|
52
|
+
if (IMAGE_EXTENSIONS.has(ext))
|
|
53
|
+
return 'image';
|
|
54
|
+
throw new MediaError('unsupported', 'Unsupported image or video extension');
|
|
55
|
+
}
|
|
56
|
+
/** Remote transport predates structured errors; translate its boundary messages in one place. */
|
|
57
|
+
function mediaFailure(error) {
|
|
58
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
59
|
+
if (error instanceof MediaError)
|
|
60
|
+
return { error: { code: error.code, reason } };
|
|
61
|
+
const codes = [
|
|
62
|
+
[/not online|disconnected|offline/i, 'offline'],
|
|
63
|
+
[/ENOENT|ENOTDIR|File not found|Not a file/i, 'not_found'],
|
|
64
|
+
[/over the \d+-byte limit/i, 'too_large'],
|
|
65
|
+
[/client too old/i, 'unsupported'],
|
|
66
|
+
];
|
|
67
|
+
const code = codes.find(([pattern]) => pattern.test(reason))?.[1] ?? 'load_failed';
|
|
68
|
+
return { error: { code, reason } };
|
|
69
|
+
}
|
|
70
|
+
async function assertMediaFile(filePath) {
|
|
71
|
+
const stat = await fs.stat(filePath);
|
|
72
|
+
if (!stat.isFile())
|
|
73
|
+
throw new MediaError('not_found', 'Not a file');
|
|
74
|
+
if (stat.size > MAX_INLINE_MEDIA_BYTES)
|
|
75
|
+
throw new MediaError('too_large', 'Media exceeds the 200 MiB limit');
|
|
76
|
+
}
|
|
77
|
+
/** First successful snapshot wins for this message/source; failures are retryable. */
|
|
78
|
+
export async function snapshotInlineMedia(input) {
|
|
79
|
+
try {
|
|
80
|
+
if (!/^[\w-]+$/.test(input.sessionId))
|
|
81
|
+
throw new MediaError('unsupported', 'Invalid session ID');
|
|
82
|
+
const source = parseMediaSrc(input.src);
|
|
83
|
+
if (source.type === 'https')
|
|
84
|
+
throw new MediaError('unsupported', 'HTTPS media must be loaded directly by the browser');
|
|
85
|
+
return await resolveSource(input, source);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
return mediaFailure(error);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async function resolveSource(input, source) {
|
|
92
|
+
const filePath = source.type === 'workspace' ? source.path : source.filePath;
|
|
93
|
+
const name = filePath.split(/[/\\]/).pop();
|
|
94
|
+
const ext = path.extname(name).toLowerCase();
|
|
95
|
+
const kind = mediaKind(ext);
|
|
96
|
+
if (source.type === 'workspace') {
|
|
97
|
+
await assertMediaFile(resolveWorkspaceRelPath(source.path));
|
|
98
|
+
return { path: source.path, name, kind };
|
|
99
|
+
}
|
|
100
|
+
const hash = createHash('sha1').update(input.ts + input.src).digest('hex').slice(0, 16);
|
|
101
|
+
const relPath = `workspace/outputs/${input.sessionId}/inline/${hash}${ext}`;
|
|
102
|
+
const pending = inFlight.get(relPath);
|
|
103
|
+
if (pending)
|
|
104
|
+
return pending;
|
|
105
|
+
const result = landSnapshot(source, relPath).then(() => ({ path: relPath, name, kind }));
|
|
106
|
+
inFlight.set(relPath, result);
|
|
107
|
+
try {
|
|
108
|
+
return await result;
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
inFlight.delete(relPath);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function exists(filePath) {
|
|
115
|
+
try {
|
|
116
|
+
await assertMediaFile(filePath);
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (error.code === 'ENOENT')
|
|
121
|
+
return false;
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Like outputs-store's local copy, but deterministic naming and staging preserve message versions. */
|
|
126
|
+
async function landSnapshot(source, relPath) {
|
|
127
|
+
const destPath = resolveWorkspaceRelPath(relPath);
|
|
128
|
+
if (await exists(destPath))
|
|
129
|
+
return;
|
|
130
|
+
await fs.mkdir(path.dirname(destPath), { recursive: true });
|
|
131
|
+
const partial = `${destPath}.part`;
|
|
132
|
+
try {
|
|
133
|
+
await receiveSource(source, partial);
|
|
134
|
+
// A local producer may have grown the file between stat and copy.
|
|
135
|
+
await assertMediaFile(partial);
|
|
136
|
+
await fs.rename(partial, destPath);
|
|
137
|
+
}
|
|
138
|
+
finally {
|
|
139
|
+
await fs.rm(partial, { force: true }).catch(() => { });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function receiveSource(source, destPath) {
|
|
143
|
+
if (source.type === 'local') {
|
|
144
|
+
await assertMediaFile(source.filePath);
|
|
145
|
+
await fs.copyFile(source.filePath, destPath);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const args = { device: source.device, filePath: source.filePath, maxBytes: MAX_INLINE_MEDIA_BYTES };
|
|
149
|
+
const stat = await prepareRemoteFetch(args);
|
|
150
|
+
await fetchRemoteFile({ ...args, destPath, stat });
|
|
151
|
+
}
|
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
import { createLogger } from '../../core/log.js';
|
|
2
2
|
import { sessionStore, effectiveBackendSessionId } from '../../store/session-registry-repo.js';
|
|
3
3
|
import { acquireSessionUse } from '../../domain/sessions/session-use.js';
|
|
4
|
-
import { resolveBackendForChannel } from '../../domain/agents/index.js';
|
|
5
4
|
import { openTurn } from '../turn/turn.js';
|
|
6
|
-
import { withTurnBrowser } from '../turn/turn-prep.js';
|
|
7
5
|
import { prepareConversationRequest } from '../conversation-request.js';
|
|
8
6
|
import * as askUserQuestion from './ask-user-question.js';
|
|
9
7
|
const log = createLogger('ask-user-resume');
|
|
@@ -41,8 +39,7 @@ async function openAnswerTurn(adapter, group, responseText, lease) {
|
|
|
41
39
|
const { channel } = group;
|
|
42
40
|
// Cost/execution attribution uses the session's bound project, NOT a re-derivation from the text.
|
|
43
41
|
const session = await sessionStore.getById(group.sessionId);
|
|
44
|
-
|
|
45
|
-
await withTurnBrowser({ backend, browser: session?.browser ?? null }, (cdpEndpoint) => openTurn({
|
|
42
|
+
await openTurn({
|
|
46
43
|
channel, adapter, threadAnchorId: null,
|
|
47
44
|
session: {
|
|
48
45
|
sessionId: group.sessionId,
|
|
@@ -54,8 +51,7 @@ async function openAnswerTurn(adapter, group, responseText, lease) {
|
|
|
54
51
|
ledger: null,
|
|
55
52
|
trigger: 'ask-user-question',
|
|
56
53
|
prepareRequest: (ids) => prepareConversationRequest({
|
|
57
|
-
ids, channel, session, userMessage: responseText,
|
|
58
|
-
browserCdpEndpoint: cdpEndpoint, trigger: 'ask-user-question',
|
|
54
|
+
ids, channel, session, userMessage: responseText, trigger: 'ask-user-question',
|
|
59
55
|
}),
|
|
60
|
-
})
|
|
56
|
+
});
|
|
61
57
|
}
|
|
@@ -24,6 +24,9 @@ function formatEpoch(epochSeconds) {
|
|
|
24
24
|
export function windowLabel(window) {
|
|
25
25
|
if (window.type === 'model_scoped' && window.label)
|
|
26
26
|
return window.label;
|
|
27
|
+
if (window.type === 'seven_day_overage_included' && window.label) {
|
|
28
|
+
return t('cmd.usage.window.sevenDayModel', { model: window.label });
|
|
29
|
+
}
|
|
27
30
|
const key = WINDOW_LABEL_KEYS[window.type];
|
|
28
31
|
return key ? t(key) : window.label ?? window.type;
|
|
29
32
|
}
|
|
@@ -17,6 +17,7 @@ import { getCurrentPlanFilePath } from '../../agent-adapter/claude/event-parser.
|
|
|
17
17
|
import { handleSubagentWebhook } from '../subagent-webhook.js';
|
|
18
18
|
import { handleTeamWebhook } from '../team-webhook.js';
|
|
19
19
|
import { handleBoardWebhook } from '../board-webhook.js';
|
|
20
|
+
import { handleBrowserWebhook } from '../browser-webhook.js';
|
|
20
21
|
import { handleBenchmarkSessionWebhook } from '../benchmark-session-webhook.js';
|
|
21
22
|
import { sendAgentFiles } from '../agent-file-send.js';
|
|
22
23
|
import { sendAgentView } from '../agent-view-send.js';
|
|
@@ -375,6 +376,9 @@ const POST_ROUTES = {
|
|
|
375
376
|
'/webhook/team': replyRoute(handleTeamWebhook),
|
|
376
377
|
// board_open and cortex_context's board field. Never touches board.html after the scaffold.
|
|
377
378
|
'/webhook/board': replyRoute((data) => handleBoardWebhook(data)),
|
|
379
|
+
// cortex-browser: `lease` starts or renews the session's browser and returns how to reach it;
|
|
380
|
+
// `report` follows each finished command so the UI shows the page it left behind.
|
|
381
|
+
'/webhook/browser': replyRoute((data) => handleBrowserWebhook(data)),
|
|
378
382
|
// Benchmark launcher: `start` returns once the session exists and its task is handed over;
|
|
379
383
|
// `status` is polled.
|
|
380
384
|
'/webhook/benchmark-session': replyRoute(handleBenchmarkSessionWebhook),
|
|
@@ -5,7 +5,6 @@ import { compactAgentContext, isSessionCompactionSupported } from '../domain/run
|
|
|
5
5
|
import { conduitQueues, enqueueAndWait } from './conduit-queue.js';
|
|
6
6
|
import { conversationEngineRequest } from './conversation-request.js';
|
|
7
7
|
import { publishSessionContextCompacted } from './session-events.js';
|
|
8
|
-
import { withTurnBrowser } from './turn/turn-prep.js';
|
|
9
8
|
const defaultDeps = {
|
|
10
9
|
sessions: sessionStore,
|
|
11
10
|
engineBusy: (session) => channelEngineBusy(session.channel, session.sessionId),
|
|
@@ -20,22 +19,21 @@ const defaultDeps = {
|
|
|
20
19
|
};
|
|
21
20
|
/**
|
|
22
21
|
* Compaction asks the pool for the session's engine exactly as the session's next turn would: the
|
|
23
|
-
* same request (agent, selection, policy, route)
|
|
24
|
-
*
|
|
25
|
-
* and leaving the next turn to respawn it again.
|
|
22
|
+
* same request (agent, selection, policy, route). Anything else is a different identity, and the pool
|
|
23
|
+
* would respawn the process — compacting a fresh one and leaving the next turn to respawn it again.
|
|
26
24
|
*/
|
|
27
25
|
function compactLiveEngine(session, backendSessionId) {
|
|
28
26
|
const { backend, channel } = session;
|
|
29
|
-
return
|
|
27
|
+
return compactAgentContext({
|
|
30
28
|
backend: backend,
|
|
31
29
|
request: conversationEngineRequest({
|
|
32
30
|
ids: {
|
|
33
31
|
sessionId: session.sessionId, backendSessionId,
|
|
34
32
|
projectId: session.projectId ?? 'general',
|
|
35
33
|
},
|
|
36
|
-
channel, session,
|
|
34
|
+
channel, session, trigger: 'manual-compact',
|
|
37
35
|
}),
|
|
38
|
-
})
|
|
36
|
+
});
|
|
39
37
|
}
|
|
40
38
|
function currentUsage(session) {
|
|
41
39
|
return session.contextUsage ?? null;
|
|
@@ -7,7 +7,7 @@ export interface SessionMessagePayload {
|
|
|
7
7
|
sessionId: string;
|
|
8
8
|
channel: string;
|
|
9
9
|
/** `worker-progress`: a team worker's interim reply, shown in its lead's chat (see `worker`). */
|
|
10
|
-
role: 'user' | 'assistant' | 'tool' | 'worker-progress';
|
|
10
|
+
role: 'user' | 'assistant' | 'thinking' | 'tool' | 'worker-progress';
|
|
11
11
|
text: string;
|
|
12
12
|
/** User messages only: Cortex authored this turn (resume signal, backgrounded agent result,
|
|
13
13
|
* waitpoint signal, team hand-off) rather than a human. Chat surfaces render it as a hint
|
|
@@ -102,6 +102,7 @@ export declare function publishSessionMessageDelta(p: {
|
|
|
102
102
|
text: string;
|
|
103
103
|
/** 0-based, per blockId; lets a client notice it missed one. */
|
|
104
104
|
seq: number;
|
|
105
|
+
kind?: 'thinking';
|
|
105
106
|
}): void;
|
|
106
107
|
/** Emit a `session.message.delivered` event: a message injected into a turn already in flight has
|
|
107
108
|
* now been consumed by the model (or its injection window closed without that happening). The
|
|
@@ -33,11 +33,17 @@ export interface TranscriptSinkDeps extends ToolImageDeps {
|
|
|
33
33
|
appendToolResult: (sessionId: string, opts: Parameters<typeof conversationHistory.appendToolResult>[1]) => Promise<void>;
|
|
34
34
|
appendSubagentEnd: (sessionId: string, opts: Parameters<typeof conversationHistory.appendSubagentEnd>[1]) => Promise<void>;
|
|
35
35
|
appendAssistant: (sessionId: string, opts: Parameters<typeof conversationHistory.appendAssistant>[1]) => Promise<void>;
|
|
36
|
+
appendThinking: (sessionId: string, opts: Parameters<typeof conversationHistory.appendThinking>[1]) => Promise<void>;
|
|
36
37
|
setTodos: (sessionId: string, snapshot: TodoSnapshot) => void;
|
|
37
38
|
publishMessage: typeof publishSessionMessage;
|
|
38
39
|
publishTodos: typeof publishSessionTodos;
|
|
39
40
|
publishDebugUpdated: typeof publishSessionDebugUpdated;
|
|
40
41
|
persistContextUsage: typeof persistSessionContextUsage;
|
|
42
|
+
snapshotMedia: (message: {
|
|
43
|
+
sessionId: string;
|
|
44
|
+
ts: string;
|
|
45
|
+
text: string;
|
|
46
|
+
}) => void;
|
|
41
47
|
/** The worker that raised a request a lead's `worker_answer` names, when known. */
|
|
42
48
|
workerForRequest: (requestId: string) => string | null;
|
|
43
49
|
}
|
|
@@ -9,6 +9,7 @@ import { publishSessionContextUsage, publishSessionDebugUpdated, publishSessionM
|
|
|
9
9
|
import { subagentPayloadFields, subagentRowRef } from './subagent-rows.js';
|
|
10
10
|
import { writeToolImages } from '../store/tool-image-files.js';
|
|
11
11
|
import { workerNameForRequest } from './team-state.js';
|
|
12
|
+
import { eagerSnapshotInlineMedia } from './inline-media-eager.js';
|
|
12
13
|
const log = createLogger('transcript-sink');
|
|
13
14
|
const defaultContextUsagePersistence = {
|
|
14
15
|
now: () => new Date().toISOString(),
|
|
@@ -48,16 +49,20 @@ const DEFAULT_DEPS = {
|
|
|
48
49
|
appendToolResult: (sessionId, opts) => conversationHistory.appendToolResult(sessionId, opts),
|
|
49
50
|
appendSubagentEnd: (sessionId, opts) => conversationHistory.appendSubagentEnd(sessionId, opts),
|
|
50
51
|
appendAssistant: (sessionId, opts) => conversationHistory.appendAssistant(sessionId, opts),
|
|
52
|
+
appendThinking: (sessionId, opts) => conversationHistory.appendThinking(sessionId, opts),
|
|
51
53
|
setTodos: (sessionId, snapshot) => sessionTodos.set(sessionId, snapshot),
|
|
52
54
|
publishMessage: publishSessionMessage,
|
|
53
55
|
publishTodos: publishSessionTodos,
|
|
54
56
|
publishDebugUpdated: publishSessionDebugUpdated,
|
|
55
57
|
persistContextUsage: persistSessionContextUsage,
|
|
58
|
+
snapshotMedia: message => {
|
|
59
|
+
void eagerSnapshotInlineMedia(message).catch(error => log.warn('Inline media snapshot failed:', String(error)));
|
|
60
|
+
},
|
|
56
61
|
workerForRequest: (requestId) => workerNameForRequest(requestId),
|
|
57
62
|
};
|
|
58
63
|
/** The event kinds this sink writes as transcript rows (context usage is stored beside them). */
|
|
59
64
|
const ROW_EVENT_TYPES = new Set([
|
|
60
|
-
'assistant_text', 'tool_use', 'tool_result', 'todo_update', 'subagent_end', 'context_usage',
|
|
65
|
+
'assistant_text', 'assistant_thinking', 'tool_use', 'tool_result', 'todo_update', 'subagent_end', 'context_usage',
|
|
61
66
|
]);
|
|
62
67
|
/** A background-phase event this sink would write: what a hold or the injection ledger forwards. */
|
|
63
68
|
export function isBackgroundRowEvent(event) {
|
|
@@ -140,6 +145,17 @@ export function createTranscriptSink(opts) {
|
|
|
140
145
|
subagentId: parentToolUseId, subagentEnded: status,
|
|
141
146
|
});
|
|
142
147
|
}
|
|
148
|
+
function persistThinking(text, blockId) {
|
|
149
|
+
if (blockId)
|
|
150
|
+
opts.flushDelta?.(blockId);
|
|
151
|
+
if (!text)
|
|
152
|
+
return;
|
|
153
|
+
const ts = new Date().toISOString();
|
|
154
|
+
recordHistory(deps.appendThinking(sessionId, { text, ts, ...(blockId ? { blockId } : {}) }));
|
|
155
|
+
deps.publishMessage({
|
|
156
|
+
sessionId, channel, role: 'thinking', text, ts, ...(blockId ? { blockId } : {}),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
143
159
|
function persistAssistant(text, blockId, noticeLevel, noticeAction, subagent, phase) {
|
|
144
160
|
// Drain this block's preview FIRST: the authoritative message must never be overtaken by
|
|
145
161
|
// a delta still sitting in the coalescer, or the UI would replace the row and then append
|
|
@@ -165,7 +181,7 @@ export function createTranscriptSink(opts) {
|
|
|
165
181
|
text, ts, noticeLevel, noticeAction,
|
|
166
182
|
...(ref ? { subagent: ref } : {}),
|
|
167
183
|
...(attributedSpawn ? { subagentSpawns: [attributedSpawn] } : {}),
|
|
168
|
-
}));
|
|
184
|
+
}), () => deps.snapshotMedia({ sessionId, ts, text }));
|
|
169
185
|
deps.publishMessage({
|
|
170
186
|
sessionId, channel, role: 'assistant', text, ts,
|
|
171
187
|
...(blockId ? { blockId } : {}),
|
|
@@ -206,6 +222,9 @@ export function createTranscriptSink(opts) {
|
|
|
206
222
|
if (event.phase === 'foreground')
|
|
207
223
|
opts.onTodoUpdate?.(event.snapshot);
|
|
208
224
|
return;
|
|
225
|
+
case 'assistant_thinking':
|
|
226
|
+
persistThinking(event.text, event.blockId);
|
|
227
|
+
return;
|
|
209
228
|
case 'assistant_text':
|
|
210
229
|
persistAssistant(event.text, event.blockId, event.noticeLevel, event.noticeAction, event.subagent, event.phase);
|
|
211
230
|
return;
|
|
@@ -31,11 +31,3 @@ export interface TurnFiles {
|
|
|
31
31
|
* Feishu-sent picture simply vanished from the transcript.
|
|
32
32
|
*/
|
|
33
33
|
export declare function collectTurnFiles(message: IncomingMessage, loadPlatformFiles: () => Promise<InboundFiles>): Promise<TurnFiles>;
|
|
34
|
-
/** Run one turn holding the browser its session opted into (`session.browser`), released when the
|
|
35
|
-
* turn is over. The turn receives the CDP endpoint, or null when it runs without one. */
|
|
36
|
-
export declare function withTurnBrowser<T>(args: {
|
|
37
|
-
backend: string;
|
|
38
|
-
browser: {
|
|
39
|
-
device: string;
|
|
40
|
-
} | null;
|
|
41
|
-
}, turn: (cdpEndpoint: string | null) => Promise<T>): Promise<T>;
|
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
import { inboundAttachmentMeta } from '../attachments-store.js';
|
|
2
|
-
import { createLogger } from '../../core/log.js';
|
|
3
2
|
import { resolveWorkspaceRelPath } from '../../core/paths.js';
|
|
4
3
|
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
5
4
|
import { acquireSessionUse } from '../../domain/sessions/session-use.js';
|
|
6
|
-
import { acquireBrowser, releaseBrowser, backendSupportsBrowser, BROWSER_DEVICE_SERVER } from '../../platform/browser/managed-browser.js';
|
|
7
|
-
import { acquireDeviceBrowser, releaseDeviceBrowser } from '../../domain/remote/device-browser.js';
|
|
8
|
-
const log = createLogger('turn-prep');
|
|
9
5
|
/** Take the session's use lease, or null when the record is gone / pending deletion. The lease is
|
|
10
6
|
* what stops retention from deleting a session out from under a turn that is still opening. */
|
|
11
7
|
export async function acquireSessionUseLease(sessionId) {
|
|
@@ -46,50 +42,3 @@ export async function collectTurnFiles(message, loadPlatformFiles) {
|
|
|
46
42
|
failures,
|
|
47
43
|
};
|
|
48
44
|
}
|
|
49
|
-
/**
|
|
50
|
-
* A browser-enabled session holds the shared Chrome for the duration of its turn. Acquiring outside
|
|
51
|
-
* the adapter keeps the spawn path synchronous and gives us one obvious place to pair with a
|
|
52
|
-
* release. A browser that cannot start degrades the turn to "no browser tools" instead of failing
|
|
53
|
-
* it — the session is still worth running.
|
|
54
|
-
*/
|
|
55
|
-
async function acquireTurnBrowser(args) {
|
|
56
|
-
const { backend, browser } = args;
|
|
57
|
-
if (!browser)
|
|
58
|
-
return { held: null, cdpEndpoint: null };
|
|
59
|
-
if (!backendSupportsBrowser(backend)) {
|
|
60
|
-
log.warn(`session opted into the browser but the ${backend} backend cannot use it — skipping`);
|
|
61
|
-
return { held: null, cdpEndpoint: null };
|
|
62
|
-
}
|
|
63
|
-
const device = browser.device;
|
|
64
|
-
try {
|
|
65
|
-
// `server` is this host's own Chrome; anything else is a Chrome the device launches for us,
|
|
66
|
-
// reachable only because the reverse channel maps its debugging port onto a local one. Both
|
|
67
|
-
// hand back a plain http://127.0.0.1:<port>, so nothing downstream knows the difference.
|
|
68
|
-
const cdpEndpoint = device === BROWSER_DEVICE_SERVER
|
|
69
|
-
? (await acquireBrowser()).cdpEndpoint
|
|
70
|
-
: (await acquireDeviceBrowser(device)).cdpEndpoint;
|
|
71
|
-
return { held: device, cdpEndpoint };
|
|
72
|
-
}
|
|
73
|
-
catch (error) {
|
|
74
|
-
log.warn(`browser session requested on "${device}" but Chrome could not start: ${error.message}`);
|
|
75
|
-
return { held: null, cdpEndpoint: null };
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
/** Release whatever {@link acquireTurnBrowser} took. No-op when it took nothing. */
|
|
79
|
-
function releaseTurnBrowser(held) {
|
|
80
|
-
if (held === BROWSER_DEVICE_SERVER)
|
|
81
|
-
releaseBrowser();
|
|
82
|
-
else if (held)
|
|
83
|
-
releaseDeviceBrowser(held);
|
|
84
|
-
}
|
|
85
|
-
/** Run one turn holding the browser its session opted into (`session.browser`), released when the
|
|
86
|
-
* turn is over. The turn receives the CDP endpoint, or null when it runs without one. */
|
|
87
|
-
export async function withTurnBrowser(args, turn) {
|
|
88
|
-
const browser = await acquireTurnBrowser(args);
|
|
89
|
-
try {
|
|
90
|
-
return await turn(browser.cdpEndpoint);
|
|
91
|
-
}
|
|
92
|
-
finally {
|
|
93
|
-
releaseTurnBrowser(browser.held);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
@@ -178,6 +178,10 @@ export class Turn {
|
|
|
178
178
|
// Platform tool trace first, then the sink — the background hold keeps the same order.
|
|
179
179
|
callbacks.onToolUse?.(event.name, event.input, event.toolUseId, event.subagent);
|
|
180
180
|
return sink.onEvent(event);
|
|
181
|
+
case 'assistant_thinking_delta':
|
|
182
|
+
if (event.phase === 'foreground')
|
|
183
|
+
deltaStream?.onDelta(event.text, event.blockId, 'thinking');
|
|
184
|
+
return;
|
|
181
185
|
case 'assistant_delta':
|
|
182
186
|
if (event.phase === 'foreground')
|
|
183
187
|
deltaStream?.onDelta(event.text, event.blockId);
|