@osovv/vv-opencode 2.0.1 → 2.1.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/CHANGELOG.md +42 -0
- package/README.md +87 -86
- package/dist/commands/completion.js +0 -1
- package/dist/commands/completion.js.map +1 -1
- package/dist/commands/doctor.js +6 -9
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/init.d.ts +2 -1
- package/dist/commands/init.js +7 -12
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/install.d.ts +4 -0
- package/dist/commands/install.js +40 -37
- package/dist/commands/install.js.map +1 -1
- package/dist/commands/launch.d.ts +2 -1
- package/dist/commands/launch.js +18 -14
- package/dist/commands/launch.js.map +1 -1
- package/dist/commands/patch-provider.d.ts +225 -307
- package/dist/commands/patch-provider.js +92 -296
- package/dist/commands/patch-provider.js.map +1 -1
- package/dist/commands/status.js +7 -10
- package/dist/commands/status.js.map +1 -1
- package/dist/commands/sync.d.ts +4 -0
- package/dist/commands/sync.js +38 -35
- package/dist/commands/sync.js.map +1 -1
- package/dist/index.d.ts +25 -5
- package/dist/index.js +73 -34
- package/dist/index.js.map +1 -1
- package/dist/lib/agent-tool-catalog.d.ts +1 -1
- package/dist/lib/agent-tool-catalog.js +3 -6
- package/dist/lib/agent-tool-catalog.js.map +1 -1
- package/dist/lib/agent-tool-contract.d.ts +22 -13
- package/dist/lib/agent-tool-contract.js +20 -20
- package/dist/lib/agent-tool-contract.js.map +1 -1
- package/dist/lib/analytics/types.d.ts +7 -1
- package/dist/lib/analytics/types.js +2 -2
- package/dist/lib/analytics/types.js.map +1 -1
- package/dist/lib/config-layers.d.ts +28 -6
- package/dist/lib/config-layers.js +268 -73
- package/dist/lib/config-layers.js.map +1 -1
- package/dist/lib/managed-agents.d.ts +24 -2
- package/dist/lib/managed-agents.js +45 -15
- package/dist/lib/managed-agents.js.map +1 -1
- package/dist/lib/model-roles.d.ts +5 -0
- package/dist/lib/model-roles.js +22 -1
- package/dist/lib/model-roles.js.map +1 -1
- package/dist/lib/opencode/agent-registrations.d.ts +4 -4
- package/dist/lib/opencode/agent-registrations.js +386 -197
- package/dist/lib/opencode/agent-registrations.js.map +1 -1
- package/dist/lib/opencode/inspection.d.ts +13 -13
- package/dist/lib/opencode/inspection.js +69 -106
- package/dist/lib/opencode/inspection.js.map +1 -1
- package/dist/lib/opencode/model-overrides.d.ts +2 -2
- package/dist/lib/opencode/model-overrides.js +192 -47
- package/dist/lib/opencode/model-overrides.js.map +1 -1
- package/dist/lib/opencode/paths.d.ts +6 -2
- package/dist/lib/opencode/paths.js +12 -11
- package/dist/lib/opencode/paths.js.map +1 -1
- package/dist/lib/opencode/plugin-registration.d.ts +10 -11
- package/dist/lib/opencode/plugin-registration.js +76 -138
- package/dist/lib/opencode/plugin-registration.js.map +1 -1
- package/dist/lib/opencode/shared-utils.d.ts +47 -3
- package/dist/lib/opencode/shared-utils.js +346 -15
- package/dist/lib/opencode/shared-utils.js.map +1 -1
- package/dist/lib/opencode.d.ts +5 -6
- package/dist/lib/opencode.js +10 -10
- package/dist/lib/opencode.js.map +1 -1
- package/dist/lib/vvoc-config.js +4 -4
- package/dist/lib/vvoc-config.js.map +1 -1
- package/dist/lib/vvoc-paths.d.ts +7 -0
- package/dist/lib/vvoc-paths.js +15 -1
- package/dist/lib/vvoc-paths.js.map +1 -1
- package/dist/lib/vvoc-preset-registry.d.ts +38 -50
- package/dist/lib/vvoc-preset-registry.js +38 -48
- package/dist/lib/vvoc-preset-registry.js.map +1 -1
- package/dist/plugins/analytics/index.d.ts +20 -14
- package/dist/plugins/analytics/index.js +281 -133
- package/dist/plugins/analytics/index.js.map +1 -1
- package/dist/plugins/guardian/index.d.ts +63 -42
- package/dist/plugins/guardian/index.js +217 -759
- package/dist/plugins/guardian/index.js.map +1 -1
- package/dist/plugins/hashline-edit/index.d.ts +145 -31
- package/dist/plugins/hashline-edit/index.js +679 -244
- package/dist/plugins/hashline-edit/index.js.map +1 -1
- package/dist/plugins/hashline-edit/schemas.d.ts +1 -1
- package/dist/plugins/hashline-edit/schemas.js +3 -3
- package/dist/plugins/hashline-edit/schemas.js.map +1 -1
- package/dist/plugins/model-roles/index.d.ts +18 -4
- package/dist/plugins/model-roles/index.js +44 -181
- package/dist/plugins/model-roles/index.js.map +1 -1
- package/dist/plugins/peak-hours/index.d.ts +23 -23
- package/dist/plugins/peak-hours/index.js +211 -180
- package/dist/plugins/peak-hours/index.js.map +1 -1
- package/dist/plugins/secrets-redaction/deep.js +35 -51
- package/dist/plugins/secrets-redaction/deep.js.map +1 -1
- package/dist/plugins/secrets-redaction/index.d.ts +96 -8
- package/dist/plugins/secrets-redaction/index.js +290 -102
- package/dist/plugins/secrets-redaction/index.js.map +1 -1
- package/dist/plugins/secrets-redaction/session.d.ts +9 -0
- package/dist/plugins/secrets-redaction/session.js +21 -4
- package/dist/plugins/secrets-redaction/session.js.map +1 -1
- package/dist/plugins/secrets-redaction/stream.d.ts +92 -0
- package/dist/plugins/secrets-redaction/stream.js +772 -0
- package/dist/plugins/secrets-redaction/stream.js.map +1 -0
- package/dist/plugins/spec-guard/index.d.ts +49 -18
- package/dist/plugins/spec-guard/index.js +231 -129
- package/dist/plugins/spec-guard/index.js.map +1 -1
- package/dist/plugins/system-context-injection/index.d.ts +10 -4
- package/dist/plugins/system-context-injection/index.js +271 -78
- package/dist/plugins/system-context-injection/index.js.map +1 -1
- package/dist/plugins/tool-history-compaction/index.d.ts +26 -4
- package/dist/plugins/tool-history-compaction/index.js +170 -32
- package/dist/plugins/tool-history-compaction/index.js.map +1 -1
- package/dist/plugins/tool-history-compaction/transform.d.ts +47 -16
- package/dist/plugins/tool-history-compaction/transform.js +173 -55
- package/dist/plugins/tool-history-compaction/transform.js.map +1 -1
- package/dist/plugins/web-tools/fetch-service.d.ts +51 -13
- package/dist/plugins/web-tools/fetch-service.js +106 -75
- package/dist/plugins/web-tools/fetch-service.js.map +1 -1
- package/dist/plugins/web-tools/index.d.ts +58 -16
- package/dist/plugins/web-tools/index.js +202 -91
- package/dist/plugins/web-tools/index.js.map +1 -1
- package/dist/plugins/web-tools/media-loader.d.ts +3 -3
- package/dist/plugins/web-tools/media-loader.js +3 -3
- package/dist/plugins/web-tools/media-loader.js.map +1 -1
- package/dist/plugins/web-tools/providers/native-fetch.d.ts +2 -2
- package/dist/plugins/web-tools/providers/native-fetch.js +1 -1
- package/dist/plugins/web-tools/providers/native-fetch.js.map +1 -1
- package/dist/plugins/web-tools/providers/spider.d.ts +2 -2
- package/dist/plugins/web-tools/providers/spider.js +1 -1
- package/dist/plugins/web-tools/providers/spider.js.map +1 -1
- package/dist/plugins/web-tools/providers/zai.d.ts +2 -2
- package/dist/plugins/web-tools/providers/zai.js +1 -1
- package/dist/plugins/web-tools/providers/zai.js.map +1 -1
- package/dist/plugins/web-tools/schemas.d.ts +1 -1
- package/dist/plugins/web-tools/schemas.js +3 -3
- package/dist/plugins/web-tools/schemas.js.map +1 -1
- package/dist/plugins/web-tools/search-service.d.ts +81 -12
- package/dist/plugins/web-tools/search-service.js +104 -57
- package/dist/plugins/web-tools/search-service.js.map +1 -1
- package/dist/plugins/workflow/authorization.d.ts +44 -10
- package/dist/plugins/workflow/authorization.js +113 -73
- package/dist/plugins/workflow/authorization.js.map +1 -1
- package/dist/plugins/workflow/cancellation.d.ts +86 -0
- package/dist/plugins/workflow/cancellation.js +202 -0
- package/dist/plugins/workflow/cancellation.js.map +1 -0
- package/dist/plugins/workflow/checkpoints.d.ts +7 -1
- package/dist/plugins/workflow/checkpoints.js +141 -21
- package/dist/plugins/workflow/checkpoints.js.map +1 -1
- package/dist/plugins/workflow/delegated.d.ts +14 -0
- package/dist/plugins/workflow/delegated.js +6 -5
- package/dist/plugins/workflow/delegated.js.map +1 -1
- package/dist/plugins/workflow/host.d.ts +81 -0
- package/dist/plugins/workflow/host.js +189 -0
- package/dist/plugins/workflow/host.js.map +1 -0
- package/dist/plugins/workflow/index.d.ts +69 -4
- package/dist/plugins/workflow/index.js +1391 -1026
- package/dist/plugins/workflow/index.js.map +1 -1
- package/dist/plugins/workflow/recovery.d.ts +3 -5
- package/dist/plugins/workflow/recovery.js +18 -33
- package/dist/plugins/workflow/recovery.js.map +1 -1
- package/dist/plugins/workflow/repair.d.ts +31 -5
- package/dist/plugins/workflow/repair.js +116 -48
- package/dist/plugins/workflow/repair.js.map +1 -1
- package/dist/plugins/workflow/results.d.ts +31 -31
- package/dist/plugins/workflow/results.js +4 -4
- package/dist/plugins/workflow/results.js.map +1 -1
- package/dist/plugins/workflow/schemas.d.ts +3 -3
- package/dist/plugins/workflow/schemas.js +5 -5
- package/dist/plugins/workflow/schemas.js.map +1 -1
- package/dist/plugins/workflow/system-instruction.md +4 -0
- package/dist/plugins/workflow/tooling.d.ts +6 -0
- package/dist/plugins/workflow/tooling.js +3 -1
- package/dist/plugins/workflow/tooling.js.map +1 -1
- package/dist/runtime/auxiliary.d.ts +13 -0
- package/dist/runtime/auxiliary.js +108 -0
- package/dist/runtime/auxiliary.js.map +1 -0
- package/dist/runtime/client.d.ts +88 -0
- package/dist/runtime/client.js +174 -0
- package/dist/runtime/client.js.map +1 -0
- package/dist/runtime/context-inspection-contract.d.ts +397 -0
- package/dist/runtime/context-inspection-contract.js +622 -0
- package/dist/runtime/context-inspection-contract.js.map +1 -0
- package/dist/runtime/context-inspection.d.ts +52 -0
- package/dist/runtime/context-inspection.js +324 -0
- package/dist/runtime/context-inspection.js.map +1 -0
- package/dist/runtime/context.d.ts +192 -0
- package/dist/runtime/context.js +1246 -0
- package/dist/runtime/context.js.map +1 -0
- package/dist/runtime/coordination.d.ts +40 -0
- package/dist/runtime/coordination.js +87 -0
- package/dist/runtime/coordination.js.map +1 -0
- package/dist/runtime/model-registry.d.ts +34 -0
- package/dist/runtime/model-registry.js +227 -0
- package/dist/runtime/model-registry.js.map +1 -0
- package/dist/runtime/permissions.d.ts +20 -0
- package/dist/runtime/permissions.js +250 -0
- package/dist/runtime/permissions.js.map +1 -0
- package/dist/runtime/snapshot-config.d.ts +80 -0
- package/dist/runtime/snapshot-config.js +268 -0
- package/dist/runtime/snapshot-config.js.map +1 -0
- package/dist/runtime/snapshot-store.d.ts +25 -0
- package/dist/runtime/snapshot-store.js +519 -0
- package/dist/runtime/snapshot-store.js.map +1 -0
- package/dist/runtime/snapshots.d.ts +59 -0
- package/dist/runtime/snapshots.js +721 -0
- package/dist/runtime/snapshots.js.map +1 -0
- package/dist/runtime/types.d.ts +713 -0
- package/dist/runtime/types.js +190 -0
- package/dist/runtime/types.js.map +1 -0
- package/dist/tui/analytics/indicator.d.ts +25 -26
- package/dist/tui/analytics/indicator.js +66 -74
- package/dist/tui/analytics/indicator.js.map +1 -1
- package/dist/tui/branding/footer.d.ts +7 -12
- package/dist/tui/branding/footer.js +16 -24
- package/dist/tui/branding/footer.js.map +1 -1
- package/dist/tui/context/analyze.d.ts +20 -9
- package/dist/tui/context/analyze.js +295 -257
- package/dist/tui/context/analyze.js.map +1 -1
- package/dist/tui/context/collect.d.ts +29 -3
- package/dist/tui/context/collect.js +450 -66
- package/dist/tui/context/collect.js.map +1 -1
- package/dist/tui/context/plugin.d.ts +21 -7
- package/dist/tui/context/plugin.js +65 -70
- package/dist/tui/context/plugin.js.map +1 -1
- package/dist/tui/context/types.d.ts +174 -43
- package/dist/tui/context/types.js +25 -19
- package/dist/tui/context/types.js.map +1 -1
- package/dist/tui/context/view.d.ts +33 -7
- package/dist/tui/context/view.js +136 -81
- package/dist/tui/context/view.js.map +1 -1
- package/dist/tui/peak-hours/banner.d.ts +13 -11
- package/dist/tui/peak-hours/banner.js +48 -80
- package/dist/tui/peak-hours/banner.js.map +1 -1
- package/dist/tui/policy.d.ts +69 -0
- package/dist/tui/policy.js +169 -0
- package/dist/tui/policy.js.map +1 -0
- package/dist/tui.d.ts +3 -8
- package/dist/tui.js +72 -68
- package/dist/tui.js.map +1 -1
- package/package.json +19 -15
- package/schemas/vvoc/v3.json +1 -1
- package/server.js +3 -5
- package/templates/agents/enhancer.md +10 -5
- package/templates/agents/guardian.md +10 -4
- package/templates/agents/investigator.md +4 -2
- package/templates/agents/vv-code-reviewer.md +4 -2
- package/templates/agents/vv-spec-reviewer.md +4 -2
- package/templates/skills/vv-execute/references/tool-contracts.md +1 -1
- package/tui.js +3 -5
- package/dist/plugins/analytics/v2.d.ts +0 -21
- package/dist/plugins/analytics/v2.js +0 -133
- package/dist/plugins/analytics/v2.js.map +0 -1
- package/dist/plugins/guardian/v2.d.ts +0 -13
- package/dist/plugins/guardian/v2.js +0 -204
- package/dist/plugins/guardian/v2.js.map +0 -1
- package/dist/plugins/hashline-edit/v2.d.ts +0 -12
- package/dist/plugins/hashline-edit/v2.js +0 -145
- package/dist/plugins/hashline-edit/v2.js.map +0 -1
- package/dist/plugins/model-roles/v2.d.ts +0 -24
- package/dist/plugins/model-roles/v2.js +0 -274
- package/dist/plugins/model-roles/v2.js.map +0 -1
- package/dist/plugins/peak-hours/v2.d.ts +0 -12
- package/dist/plugins/peak-hours/v2.js +0 -99
- package/dist/plugins/peak-hours/v2.js.map +0 -1
- package/dist/plugins/secrets-redaction/v2.d.ts +0 -19
- package/dist/plugins/secrets-redaction/v2.js +0 -138
- package/dist/plugins/secrets-redaction/v2.js.map +0 -1
- package/dist/plugins/spec-guard/v2.d.ts +0 -12
- package/dist/plugins/spec-guard/v2.js +0 -139
- package/dist/plugins/spec-guard/v2.js.map +0 -1
- package/dist/plugins/system-context-injection/agent-contexts.d.ts +0 -5
- package/dist/plugins/system-context-injection/agent-contexts.js +0 -164
- package/dist/plugins/system-context-injection/agent-contexts.js.map +0 -1
- package/dist/plugins/system-context-injection/v2.d.ts +0 -13
- package/dist/plugins/system-context-injection/v2.js +0 -60
- package/dist/plugins/system-context-injection/v2.js.map +0 -1
- package/dist/plugins/tool-history-compaction/v2.d.ts +0 -11
- package/dist/plugins/tool-history-compaction/v2.js +0 -56
- package/dist/plugins/tool-history-compaction/v2.js.map +0 -1
- package/dist/plugins/v2-runtime/config-watcher.d.ts +0 -26
- package/dist/plugins/v2-runtime/config-watcher.js +0 -111
- package/dist/plugins/v2-runtime/config-watcher.js.map +0 -1
- package/dist/plugins/v2-runtime/index.d.ts +0 -50
- package/dist/plugins/v2-runtime/index.js +0 -114
- package/dist/plugins/v2-runtime/index.js.map +0 -1
- package/dist/plugins/v2-runtime/location-config.d.ts +0 -51
- package/dist/plugins/v2-runtime/location-config.js +0 -91
- package/dist/plugins/v2-runtime/location-config.js.map +0 -1
- package/dist/plugins/v2-runtime/setup.d.ts +0 -48
- package/dist/plugins/v2-runtime/setup.js +0 -174
- package/dist/plugins/v2-runtime/setup.js.map +0 -1
- package/dist/plugins/web-tools/v2.d.ts +0 -11
- package/dist/plugins/web-tools/v2.js +0 -99
- package/dist/plugins/web-tools/v2.js.map +0 -1
- package/dist/plugins/workflow/v2.d.ts +0 -76
- package/dist/plugins/workflow/v2.js +0 -283
- package/dist/plugins/workflow/v2.js.map +0 -1
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
// FILE: src/plugins/secrets-redaction/stream.ts
|
|
2
|
+
// VERSION: 2.1.0
|
|
3
|
+
// START_MODULE_CONTRACT
|
|
4
|
+
// PURPOSE: Restore placeholders that arrive split across streamed provider text deltas while preserving opaque, binary and tool-protocol frames byte-for-byte.
|
|
5
|
+
// SCOPE: Bounded carry-aware text restoration, SSE `data:` event decoding for recognized OpenAI chat/Responses, Anthropic and Gemini text shapes (streaming and non-streaming), per-lane carries scoped by response/choice/block/item/channel identity, lane-scoped terminal handling (block/choice/item end flushes only that lane; [DONE]/response.completed/message_stop ends the response), minimal single-lane carry synthesis that never duplicates sibling lanes, bounded line/lane/pending buffers, WebSocket TEXT-frame restoration that shares one long-lived line stream across frames (a partial line, event or lane carry survives frame boundaries; reset only on a recognized global terminal), and safe buffered restoration for non-SSE JSON/text responses. Unknown or unrecognized frames and original separators pass through unchanged; the module never regex-rewrites a whole JSON document and never appends free text to a protocol stream.
|
|
6
|
+
// DEPENDS: [src/plugins/secrets-redaction/session.ts, src/plugins/secrets-redaction/restore.ts]
|
|
7
|
+
// LINKS: [M-PLUGIN-SECRETS-REDACTION, V-M-PLUGIN-SECRETS-REDACTION, DF-SECRETS-REDACTION]
|
|
8
|
+
// ROLE: RUNTIME
|
|
9
|
+
// MAP_MODE: EXPORTS
|
|
10
|
+
// END_MODULE_CONTRACT
|
|
11
|
+
//
|
|
12
|
+
// START_MODULE_MAP
|
|
13
|
+
// PLACEHOLDER_PREFIX_TOKEN - Placeholder prefix used to detect split placeholders.
|
|
14
|
+
// TextDeltaRestorer - Carry-aware text restorer that withholds an incomplete placeholder tail.
|
|
15
|
+
// SseRestoreStream - Line-buffered SSE transformer with lane-scoped carries and terminals.
|
|
16
|
+
// createSseRestoreStream - Build an SSE restore transformer for one session's mapping.
|
|
17
|
+
// restoreNonSseBody - Restore recognized text in a complete non-SSE JSON/text body.
|
|
18
|
+
// createResponseByteTransform - Pick SSE or buffered JSON/text restoration by content type.
|
|
19
|
+
// FrameRestoreState - Persistent per-connection frame carries reset only on a recognized terminal.
|
|
20
|
+
// createFrameRestoreState - Build per-connection frame restore state.
|
|
21
|
+
// restoreProviderFrame - Restore one WebSocket TEXT frame over a long-lived line/lane carry.
|
|
22
|
+
// createSseByteTransform - Byte-level SSE transform stream restoring split placeholders.
|
|
23
|
+
// END_MODULE_MAP
|
|
24
|
+
//
|
|
25
|
+
// START_CHANGE_SUMMARY
|
|
26
|
+
// LAST_CHANGE: [C-OPENCODE-V2-NATIVE T-009 - Placeholder recognizers now accept the full token-safe category grammar ([A-Za-z0-9_]+) so split lowercase/digit/punctuation/Unicode/long-category placeholders restore across SSE and WebSocket frames.]
|
|
27
|
+
// PREVIOUS: [C-OPENCODE-V2-NATIVE wi-7 - WebSocket TEXT frames now share one long-lived line stream: a partial line/event/lane carry survives frame boundaries and is reset only on a recognized global terminal, so a placeholder split across frames restores and no newline is injected into a mid-line frame; a complete unterminated `data:` JSON line is re-serialized with its canonical newline.]
|
|
28
|
+
// END_CHANGE_SUMMARY
|
|
29
|
+
import { restoreText } from "./restore.js";
|
|
30
|
+
/** Placeholder prefix used to detect split placeholders. */
|
|
31
|
+
export const PLACEHOLDER_PREFIX_TOKEN = "__VVOC_SECRET_";
|
|
32
|
+
const MAX_CARRY_CHARS = 96;
|
|
33
|
+
const MAX_LINE_BUFFER_CHARS = 64 * 1024;
|
|
34
|
+
const MAX_PENDING_TERMINAL_CHARS = 64 * 1024;
|
|
35
|
+
const MAX_LANES = 64;
|
|
36
|
+
const MAX_BUFFERED_RESPONSE_CHARS = 8 * 1024 * 1024;
|
|
37
|
+
const COMPLETE_PLACEHOLDER_RE = /^__VVOC_SECRET_[A-Za-z0-9_]+_[0-9a-f]{12}(?:_\d+)?__$/;
|
|
38
|
+
const PARTIAL_PLACEHOLDER_RE = /^__VVOC_SECRET_[A-Za-z0-9_]*(?:_[0-9a-f]{0,12}(?:_\d{0,6})?_{0,2})?$/;
|
|
39
|
+
const GLOBAL_PLACEHOLDER_RE = /__VVOC_SECRET_[A-Za-z0-9_]+_[0-9a-f]{12}(?:_\d+)?__/g;
|
|
40
|
+
// START_BLOCK_TEXT_RESTORER
|
|
41
|
+
/** True when `value` is a non-empty, incomplete prefix of a valid placeholder. */
|
|
42
|
+
function isPlaceholderFragment(value) {
|
|
43
|
+
if (value.length === 0 || value.length > MAX_CARRY_CHARS)
|
|
44
|
+
return false;
|
|
45
|
+
if (COMPLETE_PLACEHOLDER_RE.test(value))
|
|
46
|
+
return false;
|
|
47
|
+
if (PLACEHOLDER_PREFIX_TOKEN.startsWith(value))
|
|
48
|
+
return true;
|
|
49
|
+
if (!value.startsWith(PLACEHOLDER_PREFIX_TOKEN))
|
|
50
|
+
return false;
|
|
51
|
+
return PARTIAL_PLACEHOLDER_RE.test(value);
|
|
52
|
+
}
|
|
53
|
+
/** End index of the last complete placeholder in `value`, or 0. */
|
|
54
|
+
function lastCompletePlaceholderEnd(value) {
|
|
55
|
+
let end = 0;
|
|
56
|
+
GLOBAL_PLACEHOLDER_RE.lastIndex = 0;
|
|
57
|
+
let match;
|
|
58
|
+
while ((match = GLOBAL_PLACEHOLDER_RE.exec(value)) !== null) {
|
|
59
|
+
end = match.index + match[0].length;
|
|
60
|
+
}
|
|
61
|
+
return end;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Longest suffix that is an incomplete placeholder fragment, scanning only past
|
|
65
|
+
* the last complete placeholder so the closing `__` of a complete placeholder is
|
|
66
|
+
* never mistaken for a new partial prefix.
|
|
67
|
+
*/
|
|
68
|
+
function findCarryStart(value) {
|
|
69
|
+
const from = lastCompletePlaceholderEnd(value);
|
|
70
|
+
for (let index = from; index < value.length; index += 1) {
|
|
71
|
+
if (value.length - index > MAX_CARRY_CHARS)
|
|
72
|
+
continue;
|
|
73
|
+
if (isPlaceholderFragment(value.slice(index)))
|
|
74
|
+
return index;
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Carry-aware text restorer. Emits restored text up to the longest safe
|
|
80
|
+
* boundary and retains an incomplete trailing placeholder prefix until the next
|
|
81
|
+
* push (or flush) completes or abandons it. A complete trailing placeholder is
|
|
82
|
+
* always emitted restored, never carried.
|
|
83
|
+
*/
|
|
84
|
+
export class TextDeltaRestorer {
|
|
85
|
+
session;
|
|
86
|
+
carry = "";
|
|
87
|
+
constructor(session) {
|
|
88
|
+
this.session = session;
|
|
89
|
+
}
|
|
90
|
+
push(text) {
|
|
91
|
+
const combined = this.carry + text;
|
|
92
|
+
const start = findCarryStart(combined);
|
|
93
|
+
if (start === undefined) {
|
|
94
|
+
this.carry = "";
|
|
95
|
+
return restoreText(combined, this.session);
|
|
96
|
+
}
|
|
97
|
+
this.carry = combined.slice(start);
|
|
98
|
+
return restoreText(combined.slice(0, start), this.session);
|
|
99
|
+
}
|
|
100
|
+
flush() {
|
|
101
|
+
if (this.carry === "")
|
|
102
|
+
return "";
|
|
103
|
+
const pending = restoreText(this.carry, this.session);
|
|
104
|
+
this.carry = "";
|
|
105
|
+
return pending;
|
|
106
|
+
}
|
|
107
|
+
get pending() {
|
|
108
|
+
return this.carry !== "";
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function isObject(value) {
|
|
112
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
113
|
+
}
|
|
114
|
+
function isArray(value) {
|
|
115
|
+
return Array.isArray(value);
|
|
116
|
+
}
|
|
117
|
+
function asString(value) {
|
|
118
|
+
return typeof value === "string" ? value : undefined;
|
|
119
|
+
}
|
|
120
|
+
/** Drop undefined fields so a synthesized frame carries only real protocol fields. */
|
|
121
|
+
function compact(value) {
|
|
122
|
+
const result = {};
|
|
123
|
+
for (const [key, item] of Object.entries(value)) {
|
|
124
|
+
if (item !== undefined)
|
|
125
|
+
result[key] = item;
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|
|
129
|
+
function setByPath(root, path, value) {
|
|
130
|
+
let cursor = root;
|
|
131
|
+
for (let index = 0; index < path.length - 1; index += 1) {
|
|
132
|
+
if (cursor === null || typeof cursor !== "object")
|
|
133
|
+
return;
|
|
134
|
+
cursor = cursor[path[index]];
|
|
135
|
+
}
|
|
136
|
+
if (cursor === null || typeof cursor !== "object")
|
|
137
|
+
return;
|
|
138
|
+
cursor[path[path.length - 1]] = value;
|
|
139
|
+
}
|
|
140
|
+
function getByPath(root, path) {
|
|
141
|
+
let cursor = root;
|
|
142
|
+
for (const segment of path) {
|
|
143
|
+
if (cursor === null || typeof cursor !== "object")
|
|
144
|
+
return undefined;
|
|
145
|
+
cursor = cursor[segment];
|
|
146
|
+
}
|
|
147
|
+
return cursor;
|
|
148
|
+
}
|
|
149
|
+
/** Collect recognized provider text fields with a lane-scoped path and minimal frame builder. */
|
|
150
|
+
function collectTextTargets(obj) {
|
|
151
|
+
const targets = [];
|
|
152
|
+
const type = obj.type;
|
|
153
|
+
// OpenAI Responses streaming and event shapes.
|
|
154
|
+
if (typeof type === "string" && type.startsWith("response.") && typeof obj.delta === "string") {
|
|
155
|
+
const identity = asString(obj.item_id) ?? asString(obj.output_index) ?? "";
|
|
156
|
+
const content = asString(obj.content_index) ?? "";
|
|
157
|
+
targets.push({
|
|
158
|
+
lane: `responses:${identity}:${content}:${type}`,
|
|
159
|
+
path: ["delta"],
|
|
160
|
+
makeFrame: (text) => compact({
|
|
161
|
+
type,
|
|
162
|
+
item_id: obj.item_id,
|
|
163
|
+
output_index: obj.output_index,
|
|
164
|
+
content_index: obj.content_index,
|
|
165
|
+
delta: text,
|
|
166
|
+
}),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
// OpenAI Responses non-streaming output array.
|
|
170
|
+
if (isArray(obj.output)) {
|
|
171
|
+
obj.output.forEach((item, itemIndex) => {
|
|
172
|
+
if (!isObject(item) || !isArray(item.content))
|
|
173
|
+
return;
|
|
174
|
+
item.content.forEach((part, partIndex) => {
|
|
175
|
+
if (!isObject(part) || typeof part.text !== "string")
|
|
176
|
+
return;
|
|
177
|
+
targets.push({
|
|
178
|
+
lane: `responses-out:${itemIndex}:${partIndex}`,
|
|
179
|
+
path: ["output", itemIndex, "content", partIndex, "text"],
|
|
180
|
+
makeFrame: (text) => ({
|
|
181
|
+
output: [{ content: [{ type: "output_text", text }] }],
|
|
182
|
+
}),
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
// OpenAI chat streaming deltas and non-streaming messages.
|
|
188
|
+
if (isArray(obj.choices)) {
|
|
189
|
+
obj.choices.forEach((choice, choiceIndex) => {
|
|
190
|
+
if (!isObject(choice))
|
|
191
|
+
return;
|
|
192
|
+
const delta = choice.delta;
|
|
193
|
+
if (isObject(delta)) {
|
|
194
|
+
if (typeof delta.content === "string") {
|
|
195
|
+
targets.push({
|
|
196
|
+
lane: `chat:${choiceIndex}:content`,
|
|
197
|
+
path: ["choices", choiceIndex, "delta", "content"],
|
|
198
|
+
makeFrame: (text) => compact({
|
|
199
|
+
id: obj.id,
|
|
200
|
+
object: obj.object,
|
|
201
|
+
created: obj.created,
|
|
202
|
+
model: obj.model,
|
|
203
|
+
choices: [{ index: choiceIndex, delta: { content: text }, finish_reason: null }],
|
|
204
|
+
}),
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
if (typeof delta.reasoning_content === "string") {
|
|
208
|
+
targets.push({
|
|
209
|
+
lane: `chat:${choiceIndex}:reasoning`,
|
|
210
|
+
path: ["choices", choiceIndex, "delta", "reasoning_content"],
|
|
211
|
+
makeFrame: (text) => compact({
|
|
212
|
+
id: obj.id,
|
|
213
|
+
object: obj.object,
|
|
214
|
+
created: obj.created,
|
|
215
|
+
model: obj.model,
|
|
216
|
+
choices: [
|
|
217
|
+
{ index: choiceIndex, delta: { reasoning_content: text }, finish_reason: null },
|
|
218
|
+
],
|
|
219
|
+
}),
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const message = choice.message;
|
|
224
|
+
if (isObject(message)) {
|
|
225
|
+
if (typeof message.content === "string") {
|
|
226
|
+
targets.push({
|
|
227
|
+
lane: `chat-msg:${choiceIndex}:content`,
|
|
228
|
+
path: ["choices", choiceIndex, "message", "content"],
|
|
229
|
+
makeFrame: (text) => compact({
|
|
230
|
+
id: obj.id,
|
|
231
|
+
object: obj.object,
|
|
232
|
+
created: obj.created,
|
|
233
|
+
model: obj.model,
|
|
234
|
+
choices: [
|
|
235
|
+
{
|
|
236
|
+
index: choiceIndex,
|
|
237
|
+
message: { role: asString(message.role) ?? "assistant", content: text },
|
|
238
|
+
finish_reason: asString(choice.finish_reason) ?? "stop",
|
|
239
|
+
},
|
|
240
|
+
],
|
|
241
|
+
}),
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
if (typeof message.reasoning_content === "string") {
|
|
245
|
+
targets.push({
|
|
246
|
+
lane: `chat-msg:${choiceIndex}:reasoning`,
|
|
247
|
+
path: ["choices", choiceIndex, "message", "reasoning_content"],
|
|
248
|
+
makeFrame: (text) => compact({
|
|
249
|
+
id: obj.id,
|
|
250
|
+
object: obj.object,
|
|
251
|
+
created: obj.created,
|
|
252
|
+
model: obj.model,
|
|
253
|
+
choices: [
|
|
254
|
+
{
|
|
255
|
+
index: choiceIndex,
|
|
256
|
+
message: {
|
|
257
|
+
role: asString(message.role) ?? "assistant",
|
|
258
|
+
reasoning_content: text,
|
|
259
|
+
},
|
|
260
|
+
finish_reason: asString(choice.finish_reason) ?? "stop",
|
|
261
|
+
},
|
|
262
|
+
],
|
|
263
|
+
}),
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
// Anthropic streaming content_block_delta and non-streaming content blocks.
|
|
270
|
+
const delta = obj.delta;
|
|
271
|
+
if (isObject(delta)) {
|
|
272
|
+
if (delta.type === "text_delta" && typeof delta.text === "string") {
|
|
273
|
+
targets.push({
|
|
274
|
+
lane: `anthropic:${asString(obj.index) ?? "0"}:text`,
|
|
275
|
+
path: ["delta", "text"],
|
|
276
|
+
makeFrame: (text) => ({
|
|
277
|
+
type: "content_block_delta",
|
|
278
|
+
index: obj.index,
|
|
279
|
+
delta: { type: "text_delta", text },
|
|
280
|
+
}),
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
if (delta.type === "thinking_delta" && typeof delta.thinking === "string") {
|
|
284
|
+
targets.push({
|
|
285
|
+
lane: `anthropic:${asString(obj.index) ?? "0"}:thinking`,
|
|
286
|
+
path: ["delta", "thinking"],
|
|
287
|
+
makeFrame: (text) => ({
|
|
288
|
+
type: "content_block_delta",
|
|
289
|
+
index: obj.index,
|
|
290
|
+
delta: { type: "thinking_delta", thinking: text },
|
|
291
|
+
}),
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (isArray(obj.content)) {
|
|
296
|
+
obj.content.forEach((block, blockIndex) => {
|
|
297
|
+
if (!isObject(block) || block.type !== "text" || typeof block.text !== "string")
|
|
298
|
+
return;
|
|
299
|
+
targets.push({
|
|
300
|
+
lane: `anthropic-msg:${blockIndex}`,
|
|
301
|
+
path: ["content", blockIndex, "text"],
|
|
302
|
+
makeFrame: (text) => ({
|
|
303
|
+
type: "content_block_delta",
|
|
304
|
+
index: blockIndex,
|
|
305
|
+
delta: { type: "text_delta", text },
|
|
306
|
+
}),
|
|
307
|
+
});
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
// Gemini streaming and non-streaming candidates.
|
|
311
|
+
if (isArray(obj.candidates)) {
|
|
312
|
+
obj.candidates.forEach((candidate, candidateIndex) => {
|
|
313
|
+
if (!isObject(candidate) ||
|
|
314
|
+
!isObject(candidate.content) ||
|
|
315
|
+
!isArray(candidate.content.parts)) {
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
candidate.content.parts.forEach((part, partIndex) => {
|
|
319
|
+
if (!isObject(part) || typeof part.text !== "string")
|
|
320
|
+
return;
|
|
321
|
+
targets.push({
|
|
322
|
+
lane: `gemini:${candidateIndex}:${partIndex}`,
|
|
323
|
+
path: ["candidates", candidateIndex, "content", "parts", partIndex, "text"],
|
|
324
|
+
makeFrame: (text) => ({
|
|
325
|
+
candidates: [{ content: { parts: [{ text }] } }],
|
|
326
|
+
}),
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
return targets;
|
|
332
|
+
}
|
|
333
|
+
/** Lane keys ended by a non-global block/choice/item terminal frame. */
|
|
334
|
+
function endedLaneKeys(obj) {
|
|
335
|
+
const lanes = [];
|
|
336
|
+
if (obj.type === "content_block_stop") {
|
|
337
|
+
const index = asString(obj.index) ?? "0";
|
|
338
|
+
lanes.push(`anthropic:${index}:text`, `anthropic:${index}:thinking`);
|
|
339
|
+
}
|
|
340
|
+
if (isArray(obj.choices)) {
|
|
341
|
+
obj.choices.forEach((choice, choiceIndex) => {
|
|
342
|
+
if (!isObject(choice) ||
|
|
343
|
+
choice.finish_reason === null ||
|
|
344
|
+
choice.finish_reason === undefined) {
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
lanes.push(`chat:${choiceIndex}:content`, `chat:${choiceIndex}:reasoning`, `chat-msg:${choiceIndex}:content`, `chat-msg:${choiceIndex}:reasoning`);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
if (obj.type === "response.output_text.done" || obj.type === "response.content_part.done") {
|
|
351
|
+
const identity = asString(obj.item_id) ?? asString(obj.output_index) ?? "";
|
|
352
|
+
const content = asString(obj.content_index) ?? "";
|
|
353
|
+
lanes.push(`responses:${identity}:${content}:response.output_text.delta`);
|
|
354
|
+
}
|
|
355
|
+
return lanes;
|
|
356
|
+
}
|
|
357
|
+
/** True when a recognized provider JSON object terminates the whole response. */
|
|
358
|
+
function isGlobalTerminalObject(obj) {
|
|
359
|
+
const type = obj.type;
|
|
360
|
+
return type === "response.completed" || type === "message_stop";
|
|
361
|
+
}
|
|
362
|
+
/** Restore every recognized text field in a complete (non-streaming) JSON body. */
|
|
363
|
+
function restoreCompleteJson(obj, session) {
|
|
364
|
+
let changed = false;
|
|
365
|
+
for (const target of collectTextTargets(obj)) {
|
|
366
|
+
const value = getByPath(obj, target.path);
|
|
367
|
+
if (typeof value !== "string")
|
|
368
|
+
continue;
|
|
369
|
+
const restored = restoreText(value, session);
|
|
370
|
+
if (restored !== value) {
|
|
371
|
+
setByPath(obj, target.path, restored);
|
|
372
|
+
changed = true;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return changed;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Line-buffered SSE transform. Only recognized `data:` JSON events are
|
|
379
|
+
* re-serialized with restored text; every other line (event names, ids,
|
|
380
|
+
* comments, opaque or malformed payloads) is emitted with its original bytes
|
|
381
|
+
* and separator. Carries are scoped by lane identity. A block/choice/item end
|
|
382
|
+
* flushes only that lane as a minimal single-lane delta before the terminal
|
|
383
|
+
* frame; only `[DONE]`/`response.completed`/`message_stop` ends the response and
|
|
384
|
+
* holds a bounded tail. No free text is ever appended to the protocol stream.
|
|
385
|
+
*/
|
|
386
|
+
export class SseRestoreStream {
|
|
387
|
+
session;
|
|
388
|
+
lineBuffer = "";
|
|
389
|
+
pendingTerminal = "";
|
|
390
|
+
pendingEventLine;
|
|
391
|
+
terminalSeen = false;
|
|
392
|
+
currentEventName;
|
|
393
|
+
restorers = new Map();
|
|
394
|
+
templates = new Map();
|
|
395
|
+
constructor(session) {
|
|
396
|
+
this.session = session;
|
|
397
|
+
}
|
|
398
|
+
restorerFor(lane) {
|
|
399
|
+
let restorer = this.restorers.get(lane);
|
|
400
|
+
if (restorer === undefined) {
|
|
401
|
+
restorer = new TextDeltaRestorer(this.session);
|
|
402
|
+
this.restorers.set(lane, restorer);
|
|
403
|
+
}
|
|
404
|
+
return restorer;
|
|
405
|
+
}
|
|
406
|
+
flushLane(lane) {
|
|
407
|
+
const restorer = this.restorers.get(lane);
|
|
408
|
+
const template = this.templates.get(lane);
|
|
409
|
+
if (restorer === undefined || template === undefined || !restorer.pending)
|
|
410
|
+
return "";
|
|
411
|
+
const pending = restorer.flush();
|
|
412
|
+
if (pending === "")
|
|
413
|
+
return "";
|
|
414
|
+
const prefix = template.eventName === undefined ? "" : `event: ${template.eventName}\n`;
|
|
415
|
+
return `${prefix}data: ${JSON.stringify(template.makeFrame(pending))}\n\n`;
|
|
416
|
+
}
|
|
417
|
+
flushLanes(keys) {
|
|
418
|
+
let output = "";
|
|
419
|
+
for (const lane of keys)
|
|
420
|
+
output += this.flushLane(lane);
|
|
421
|
+
return output;
|
|
422
|
+
}
|
|
423
|
+
flushLanesByPrefix(prefix) {
|
|
424
|
+
let output = "";
|
|
425
|
+
for (const lane of this.restorers.keys()) {
|
|
426
|
+
if (lane.startsWith(prefix))
|
|
427
|
+
output += this.flushLane(lane);
|
|
428
|
+
}
|
|
429
|
+
return output;
|
|
430
|
+
}
|
|
431
|
+
flushAllLanes() {
|
|
432
|
+
return this.flushLanes(this.restorers.keys());
|
|
433
|
+
}
|
|
434
|
+
evictLanesIfNeeded() {
|
|
435
|
+
if (this.restorers.size < MAX_LANES)
|
|
436
|
+
return "";
|
|
437
|
+
// Flush pending suffixes before eviction so no ordinary text is dropped.
|
|
438
|
+
return this.flushAllLanes();
|
|
439
|
+
}
|
|
440
|
+
transformDataLine(line, terminator) {
|
|
441
|
+
const match = /^(data:(?: )?)(.*)$/.exec(line);
|
|
442
|
+
const unchanged = { prefix: "", output: `${line}${terminator}` };
|
|
443
|
+
if (match === null)
|
|
444
|
+
return unchanged;
|
|
445
|
+
const payload = match[2] ?? "";
|
|
446
|
+
if (payload === "" || payload === "[DONE]")
|
|
447
|
+
return unchanged;
|
|
448
|
+
let parsed;
|
|
449
|
+
try {
|
|
450
|
+
parsed = JSON.parse(payload);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
return unchanged;
|
|
454
|
+
}
|
|
455
|
+
if (!isObject(parsed))
|
|
456
|
+
return unchanged;
|
|
457
|
+
const targets = collectTextTargets(parsed);
|
|
458
|
+
const ended = endedLaneKeys(parsed);
|
|
459
|
+
let prefix = ended.length === 0 ? "" : this.flushLanes(ended);
|
|
460
|
+
if (targets.length === 0)
|
|
461
|
+
return { prefix, output: `${line}${terminator}` };
|
|
462
|
+
prefix += this.evictLanesIfNeeded();
|
|
463
|
+
for (const target of targets) {
|
|
464
|
+
const value = getByPath(parsed, target.path);
|
|
465
|
+
if (typeof value !== "string")
|
|
466
|
+
continue;
|
|
467
|
+
setByPath(parsed, target.path, this.restorerFor(target.lane).push(value));
|
|
468
|
+
this.templates.set(target.lane, {
|
|
469
|
+
eventName: this.currentEventName,
|
|
470
|
+
makeFrame: target.makeFrame,
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
return { prefix, output: `${match[1]}${JSON.stringify(parsed)}${terminator}` };
|
|
474
|
+
}
|
|
475
|
+
/** Emit a held `event:` line so it stays adjacent to its own `data:` line. */
|
|
476
|
+
takePendingEventLine() {
|
|
477
|
+
if (this.pendingEventLine === undefined)
|
|
478
|
+
return "";
|
|
479
|
+
const line = `${this.pendingEventLine}\n`;
|
|
480
|
+
this.pendingEventLine = undefined;
|
|
481
|
+
return line;
|
|
482
|
+
}
|
|
483
|
+
isGlobalTerminalLine(line) {
|
|
484
|
+
if (line.startsWith("event: message_stop"))
|
|
485
|
+
return true;
|
|
486
|
+
const match = /^data:(?: )?(.*)$/.exec(line);
|
|
487
|
+
if (match === null)
|
|
488
|
+
return false;
|
|
489
|
+
const payload = match[1] ?? "";
|
|
490
|
+
if (payload === "[DONE]")
|
|
491
|
+
return true;
|
|
492
|
+
try {
|
|
493
|
+
const parsed = JSON.parse(payload);
|
|
494
|
+
return isObject(parsed) && isGlobalTerminalObject(parsed);
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
return false;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
push(chunk) {
|
|
501
|
+
this.lineBuffer += chunk;
|
|
502
|
+
let output = "";
|
|
503
|
+
for (;;) {
|
|
504
|
+
const newlineIndex = this.lineBuffer.indexOf("\n");
|
|
505
|
+
if (newlineIndex < 0)
|
|
506
|
+
break;
|
|
507
|
+
const rawLine = this.lineBuffer.slice(0, newlineIndex);
|
|
508
|
+
this.lineBuffer = this.lineBuffer.slice(newlineIndex + 1);
|
|
509
|
+
const terminator = rawLine.endsWith("\r") ? "\r\n" : "\n";
|
|
510
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
511
|
+
if (this.terminalSeen) {
|
|
512
|
+
this.pendingTerminal += `${rawLine}\n`;
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (this.isGlobalTerminalLine(line)) {
|
|
516
|
+
// Emit every lane's carry before holding the bounded response tail.
|
|
517
|
+
output += this.flushAllLanes();
|
|
518
|
+
this.terminalSeen = true;
|
|
519
|
+
this.pendingTerminal += `${rawLine}\n`;
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
if (/^event:(?: |$)/.test(line)) {
|
|
523
|
+
output += this.takePendingEventLine();
|
|
524
|
+
this.pendingEventLine = rawLine;
|
|
525
|
+
this.currentEventName = line.slice(line.indexOf(":") + 1).trim() || undefined;
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
if (line === "") {
|
|
529
|
+
output += this.takePendingEventLine();
|
|
530
|
+
this.currentEventName = undefined;
|
|
531
|
+
output += `${rawLine}\n`;
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (/^data:(?: |$)/.test(line)) {
|
|
535
|
+
const transformed = this.transformDataLine(line, terminator);
|
|
536
|
+
output += transformed.prefix;
|
|
537
|
+
output += this.takePendingEventLine();
|
|
538
|
+
output += transformed.output;
|
|
539
|
+
continue;
|
|
540
|
+
}
|
|
541
|
+
output += this.takePendingEventLine();
|
|
542
|
+
output += `${rawLine}\n`;
|
|
543
|
+
}
|
|
544
|
+
if (this.lineBuffer.length > MAX_LINE_BUFFER_CHARS) {
|
|
545
|
+
output += this.lineBuffer;
|
|
546
|
+
this.lineBuffer = "";
|
|
547
|
+
}
|
|
548
|
+
if (this.pendingTerminal.length > MAX_PENDING_TERMINAL_CHARS) {
|
|
549
|
+
output += this.pendingTerminal;
|
|
550
|
+
this.pendingTerminal = "";
|
|
551
|
+
}
|
|
552
|
+
return output;
|
|
553
|
+
}
|
|
554
|
+
/** True once a global response terminal (`[DONE]`/completed/message_stop) was seen. */
|
|
555
|
+
get terminal() {
|
|
556
|
+
return this.terminalSeen;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Process the trailing buffered line only when it is already a complete,
|
|
560
|
+
* recognized `data:` payload. Used by frame-oriented transports (WebSocket)
|
|
561
|
+
* where a complete JSON line may arrive without a terminating newline; the
|
|
562
|
+
* line is re-serialized with its canonical newline, never with raw bytes
|
|
563
|
+
* spliced into a mid-line frame. Incomplete or unrecognized buffers are left
|
|
564
|
+
* untouched so streaming carry survives until the real terminal/end.
|
|
565
|
+
*/
|
|
566
|
+
drainUnterminatedLine() {
|
|
567
|
+
if (this.terminalSeen)
|
|
568
|
+
return "";
|
|
569
|
+
const line = this.lineBuffer;
|
|
570
|
+
if (line === "" || line.includes("\n"))
|
|
571
|
+
return "";
|
|
572
|
+
const match = /^data:(?: )?(.*)$/.exec(line);
|
|
573
|
+
if (match === null)
|
|
574
|
+
return "";
|
|
575
|
+
const payload = match[1] ?? "";
|
|
576
|
+
if (payload !== "[DONE]") {
|
|
577
|
+
try {
|
|
578
|
+
if (!isObject(JSON.parse(payload)))
|
|
579
|
+
return "";
|
|
580
|
+
}
|
|
581
|
+
catch {
|
|
582
|
+
return "";
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
this.lineBuffer = "";
|
|
586
|
+
if (this.isGlobalTerminalLine(line)) {
|
|
587
|
+
const output = this.flushAllLanes();
|
|
588
|
+
this.terminalSeen = true;
|
|
589
|
+
this.pendingTerminal += `${line}\n`;
|
|
590
|
+
return output;
|
|
591
|
+
}
|
|
592
|
+
const transformed = this.transformDataLine(line, "\n");
|
|
593
|
+
return transformed.prefix + this.takePendingEventLine() + transformed.output;
|
|
594
|
+
}
|
|
595
|
+
flush() {
|
|
596
|
+
let output = this.flushAllLanes();
|
|
597
|
+
output += this.takePendingEventLine();
|
|
598
|
+
output += this.pendingTerminal;
|
|
599
|
+
this.pendingTerminal = "";
|
|
600
|
+
if (this.lineBuffer !== "") {
|
|
601
|
+
output += this.lineBuffer;
|
|
602
|
+
this.lineBuffer = "";
|
|
603
|
+
}
|
|
604
|
+
this.templates.clear();
|
|
605
|
+
this.restorers.clear();
|
|
606
|
+
this.terminalSeen = false;
|
|
607
|
+
this.currentEventName = undefined;
|
|
608
|
+
return output;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
/** Build a line-buffered SSE restore stream for one session's placeholder mapping. */
|
|
612
|
+
export function createSseRestoreStream(session) {
|
|
613
|
+
return new SseRestoreStream(session);
|
|
614
|
+
}
|
|
615
|
+
/** Build a byte-level SSE transform stream that restores split placeholders. */
|
|
616
|
+
export function createSseByteTransform(session) {
|
|
617
|
+
const decoder = new TextDecoder("utf-8");
|
|
618
|
+
const encoder = new TextEncoder();
|
|
619
|
+
const stream = new SseRestoreStream(session);
|
|
620
|
+
return new TransformStream({
|
|
621
|
+
transform(chunk, controller) {
|
|
622
|
+
const text = decoder.decode(chunk, { stream: true });
|
|
623
|
+
if (text.length > 0)
|
|
624
|
+
controller.enqueue(encoder.encode(stream.push(text)));
|
|
625
|
+
},
|
|
626
|
+
flush(controller) {
|
|
627
|
+
const tail = decoder.decode();
|
|
628
|
+
const text = tail.length > 0 ? stream.push(tail) : "";
|
|
629
|
+
const flushed = stream.flush();
|
|
630
|
+
const combined = `${text}${flushed}`;
|
|
631
|
+
if (combined.length > 0)
|
|
632
|
+
controller.enqueue(encoder.encode(combined));
|
|
633
|
+
},
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Restore a non-SSE response body. JSON bodies are parsed and recognized text
|
|
638
|
+
* fields rewritten; plain text bodies are restored directly; anything else
|
|
639
|
+
* (binary, oversized, malformed) is returned byte-for-byte unchanged.
|
|
640
|
+
*/
|
|
641
|
+
export function restoreNonSseBody(session, body) {
|
|
642
|
+
const trimmed = body.trim();
|
|
643
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
644
|
+
try {
|
|
645
|
+
const parsed = JSON.parse(body);
|
|
646
|
+
if (isObject(parsed)) {
|
|
647
|
+
return restoreCompleteJson(parsed, session) ? JSON.stringify(parsed) : body;
|
|
648
|
+
}
|
|
649
|
+
if (Array.isArray(parsed)) {
|
|
650
|
+
let changed = false;
|
|
651
|
+
for (const entry of parsed) {
|
|
652
|
+
if (isObject(entry) && restoreCompleteJson(entry, session))
|
|
653
|
+
changed = true;
|
|
654
|
+
}
|
|
655
|
+
return changed ? JSON.stringify(parsed) : body;
|
|
656
|
+
}
|
|
657
|
+
return body;
|
|
658
|
+
}
|
|
659
|
+
catch {
|
|
660
|
+
return body;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (body.includes("\u0000"))
|
|
664
|
+
return body;
|
|
665
|
+
return restoreText(body, session);
|
|
666
|
+
}
|
|
667
|
+
/** Pick SSE or buffered JSON/text restoration for one HTTP response body. */
|
|
668
|
+
export function createResponseByteTransform(session, contentType) {
|
|
669
|
+
if (contentType.toLowerCase().includes("text/event-stream")) {
|
|
670
|
+
return createSseByteTransform(session);
|
|
671
|
+
}
|
|
672
|
+
const decoder = new TextDecoder("utf-8");
|
|
673
|
+
const encoder = new TextEncoder();
|
|
674
|
+
let buffer = "";
|
|
675
|
+
let overflowed = false;
|
|
676
|
+
return new TransformStream({
|
|
677
|
+
transform(chunk, controller) {
|
|
678
|
+
if (overflowed) {
|
|
679
|
+
controller.enqueue(chunk);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
683
|
+
if (buffer.length > MAX_BUFFERED_RESPONSE_CHARS) {
|
|
684
|
+
overflowed = true;
|
|
685
|
+
controller.enqueue(encoder.encode(buffer));
|
|
686
|
+
buffer = "";
|
|
687
|
+
}
|
|
688
|
+
},
|
|
689
|
+
flush(controller) {
|
|
690
|
+
if (overflowed) {
|
|
691
|
+
const tail = decoder.decode();
|
|
692
|
+
if (tail.length > 0)
|
|
693
|
+
controller.enqueue(encoder.encode(tail));
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const tail = decoder.decode();
|
|
697
|
+
const body = `${buffer}${tail}`;
|
|
698
|
+
controller.enqueue(encoder.encode(restoreNonSseBody(session, body)));
|
|
699
|
+
},
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
/** Build persistent frame restore state for one socket connection. */
|
|
703
|
+
export function createFrameRestoreState(session) {
|
|
704
|
+
return { sse: null, text: new TextDeltaRestorer(session), restorers: new Map() };
|
|
705
|
+
}
|
|
706
|
+
function resetFrameState(state, session) {
|
|
707
|
+
state.sse = null;
|
|
708
|
+
state.text = new TextDeltaRestorer(session);
|
|
709
|
+
state.restorers.clear();
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Restore one WebSocket TEXT frame. Recognized JSON deltas restore by lane with
|
|
713
|
+
* a persistent carry so a placeholder split across frames completes; SSE-framed
|
|
714
|
+
* text reuses one long-lived line stream so a partial line, event, or lane
|
|
715
|
+
* carry survives every frame boundary until the actual terminal/end. State is
|
|
716
|
+
* reset only on a recognized global terminal, never per frame, so a split
|
|
717
|
+
* placeholder is never abandoned or re-decoded against a reset carry and no
|
|
718
|
+
* bytes (including a missing newline) are injected into a mid-line frame.
|
|
719
|
+
* Frames that match no recognized protocol shape are returned unchanged,
|
|
720
|
+
* preserving opaque/binary/tool-protocol frames.
|
|
721
|
+
*/
|
|
722
|
+
export function restoreProviderFrame(session, frame, state) {
|
|
723
|
+
// A frame that opens an SSE-over-WS stream, or any continuation frame while
|
|
724
|
+
// one is active, is fed to the single long-lived line stream. The stream is
|
|
725
|
+
// only left on a recognized global terminal, so a split line/event/carry
|
|
726
|
+
// survives frame boundaries instead of being reset per frame.
|
|
727
|
+
if (state.sse !== null || /^data:(?: |$)/m.test(frame)) {
|
|
728
|
+
state.sse ??= new SseRestoreStream(session);
|
|
729
|
+
let output = state.sse.push(frame);
|
|
730
|
+
output += state.sse.drainUnterminatedLine();
|
|
731
|
+
if (state.sse.terminal) {
|
|
732
|
+
output += state.sse.flush();
|
|
733
|
+
resetFrameState(state, session);
|
|
734
|
+
}
|
|
735
|
+
return output;
|
|
736
|
+
}
|
|
737
|
+
let parsed;
|
|
738
|
+
try {
|
|
739
|
+
parsed = JSON.parse(frame);
|
|
740
|
+
}
|
|
741
|
+
catch {
|
|
742
|
+
parsed = undefined;
|
|
743
|
+
}
|
|
744
|
+
if (isObject(parsed)) {
|
|
745
|
+
let changed = false;
|
|
746
|
+
for (const target of collectTextTargets(parsed)) {
|
|
747
|
+
const value = getByPath(parsed, target.path);
|
|
748
|
+
if (typeof value !== "string")
|
|
749
|
+
continue;
|
|
750
|
+
let restorer = state.restorers.get(target.lane);
|
|
751
|
+
if (restorer === undefined) {
|
|
752
|
+
restorer = new TextDeltaRestorer(session);
|
|
753
|
+
state.restorers.set(target.lane, restorer);
|
|
754
|
+
}
|
|
755
|
+
setByPath(parsed, target.path, restorer.push(value));
|
|
756
|
+
changed = true;
|
|
757
|
+
}
|
|
758
|
+
for (const lane of endedLaneKeys(parsed))
|
|
759
|
+
state.restorers.delete(lane);
|
|
760
|
+
const terminal = isGlobalTerminalObject(parsed);
|
|
761
|
+
const result = changed ? JSON.stringify(parsed) : frame;
|
|
762
|
+
if (terminal)
|
|
763
|
+
resetFrameState(state, session);
|
|
764
|
+
return result;
|
|
765
|
+
}
|
|
766
|
+
// Plain text frame: restore recognized placeholders with a persistent carry.
|
|
767
|
+
if (frame.includes("\u0000"))
|
|
768
|
+
return frame;
|
|
769
|
+
return state.text.push(frame);
|
|
770
|
+
}
|
|
771
|
+
// END_BLOCK_FRAME_RESTORE
|
|
772
|
+
//# sourceMappingURL=stream.js.map
|