@atlaswork/atlascode 0.1.126 → 0.1.128

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.
Files changed (36) hide show
  1. package/dist/atlasweb-carrier.json +3 -3
  2. package/dist/cli.js +31 -7
  3. package/dist/web-contract/index.d.ts +8 -0
  4. package/dist/web-contract/index.js +5 -2
  5. package/dist/web-session-runtime/atlascode/web/limits.d.ts +2 -0
  6. package/dist/web-session-runtime/atlascode/web/projection.d.ts +6 -0
  7. package/dist/web-session-runtime/atlascode/web/readonlyRuntime.d.ts +24 -0
  8. package/dist/web-session-runtime/atlascode/web/replayPaging.d.ts +27 -0
  9. package/dist/web-session-runtime/engine/session/load.d.ts +47 -0
  10. package/dist/web-session-runtime/engine/session/predicates.d.ts +1 -1
  11. package/dist/web-session-runtime/engine/session/readonly.d.ts +2 -0
  12. package/dist/web-session-runtime/engine/session/replayScan.d.ts +45 -0
  13. package/dist/web-session-runtime/engine/session/types.d.ts +1 -1
  14. package/dist/web-session-runtime/index.js +373 -4
  15. package/dist/web-session-runtime/kernel/protocol/webSessionV0.d.ts +8 -0
  16. package/dist/web-session-runtime/shared/index.d.ts +1 -1
  17. package/dist/web-session-runtime-execution/atlascode/web/entry.d.ts +2 -0
  18. package/dist/web-session-runtime-execution/atlascode/web/limits.d.ts +2 -0
  19. package/dist/web-session-runtime-execution/atlascode/web/projection.d.ts +6 -0
  20. package/dist/web-session-runtime-execution/atlascode/web/readonlyRuntime.d.ts +24 -0
  21. package/dist/web-session-runtime-execution/atlascode/web/replayPaging.d.ts +27 -0
  22. package/dist/web-session-runtime-execution/engine/session/load.d.ts +47 -0
  23. package/dist/web-session-runtime-execution/engine/session/predicates.d.ts +1 -1
  24. package/dist/web-session-runtime-execution/engine/session/readonly.d.ts +2 -0
  25. package/dist/web-session-runtime-execution/engine/session/replayScan.d.ts +45 -0
  26. package/dist/web-session-runtime-execution/engine/session/types.d.ts +1 -1
  27. package/dist/web-session-runtime-execution/index.js +662 -8
  28. package/dist/web-session-runtime-execution/kernel/execution/executionComposition.d.ts +18 -0
  29. package/dist/web-session-runtime-execution/kernel/execution/executionKernel.d.ts +77 -0
  30. package/dist/web-session-runtime-execution/kernel/protocol/webSessionV0.d.ts +8 -0
  31. package/dist/web-session-runtime-execution/shared/index.d.ts +1 -1
  32. package/package.json +2 -2
  33. package/dist/web-session-runtime/atlascode/web/entry.d.ts +0 -21
  34. package/dist/web-session-runtime/atlascode/web/executionOutlet.d.ts +0 -60
  35. package/dist/web-session-runtime/kernel/execution/executionOutlet.d.ts +0 -60
  36. package/dist/web-session-runtime/kernel/protocol/webExecutionV0.d.ts +0 -542
@@ -950,6 +950,175 @@ async function loadTranscriptFile(filePath, opts) {
950
950
  leafUuids
951
951
  };
952
952
  }
953
+ // src/engine/session/replayScan.ts
954
+ import { constants as fsConstants2 } from "node:fs";
955
+ import { open as open2 } from "fs/promises";
956
+ function stripContent(content) {
957
+ if (typeof content === "string") {
958
+ return content.length > 0 ? "\x00" : "";
959
+ }
960
+ if (!Array.isArray(content))
961
+ return;
962
+ return content.map((item) => {
963
+ if (!item || typeof item !== "object")
964
+ return item;
965
+ const rec = item;
966
+ switch (rec.type) {
967
+ case "text":
968
+ return {
969
+ type: "text",
970
+ text: typeof rec.text === "string" && rec.text.length > 0 ? "\x00" : ""
971
+ };
972
+ case "tool_use":
973
+ return { type: "tool_use", id: rec.id };
974
+ case "tool_result":
975
+ return { type: "tool_result", tool_use_id: rec.tool_use_id };
976
+ default:
977
+ return { type: rec.type };
978
+ }
979
+ });
980
+ }
981
+ function stripToSkeleton(entry) {
982
+ const type = entry.type;
983
+ if (type !== "user" && type !== "assistant" && type !== "attachment" && type !== "system") {
984
+ return;
985
+ }
986
+ const message = entry.message;
987
+ const skeleton = {
988
+ uuid: entry.uuid,
989
+ parentUuid: entry.parentUuid ?? null,
990
+ type,
991
+ timestamp: entry.timestamp ?? null
992
+ };
993
+ if (typeof entry.isSidechain === "boolean")
994
+ skeleton.isSidechain = entry.isSidechain;
995
+ if (entry.compactMetadata !== undefined)
996
+ skeleton.compactMetadata = entry.compactMetadata;
997
+ if (typeof entry.subtype === "string")
998
+ skeleton.subtype = entry.subtype;
999
+ if (entry.snipMetadata !== undefined)
1000
+ skeleton.snipMetadata = entry.snipMetadata;
1001
+ if (message && typeof message === "object") {
1002
+ const m = message;
1003
+ const out = {};
1004
+ if (typeof m.id === "string")
1005
+ out.id = m.id;
1006
+ const content = stripContent(m.content);
1007
+ if (content !== undefined)
1008
+ out.content = content;
1009
+ skeleton.message = out;
1010
+ }
1011
+ return skeleton;
1012
+ }
1013
+ async function openReplayPageReader(filePath, opts) {
1014
+ const noFollow = fsConstants2.O_NOFOLLOW ?? 0;
1015
+ const fd = await open2(filePath, fsConstants2.O_RDONLY | noFollow);
1016
+ try {
1017
+ const fst = await fd.stat();
1018
+ if (opts?.expectIno !== undefined && fst.ino !== opts.expectIno) {
1019
+ throw new TranscriptChangedDuringReadError;
1020
+ }
1021
+ if (opts?.maxBytes !== undefined && fst.size > opts.maxBytes) {
1022
+ throw new TranscriptTooLargeError(fst.size, opts.maxBytes);
1023
+ }
1024
+ const skeletons = new Map;
1025
+ const ranges = new Map;
1026
+ const progressBridge = new Map;
1027
+ const buf = Buffer.allocUnsafe(TRANSCRIPT_READ_CHUNK_SIZE);
1028
+ let carry = Buffer.alloc(0);
1029
+ let carryFileStart = 0;
1030
+ let readPos = 0;
1031
+ let firstChunk = true;
1032
+ const processLine = (line, fileOffset) => {
1033
+ const text = line.toString("utf8").trim();
1034
+ if (!text)
1035
+ return;
1036
+ let entry;
1037
+ try {
1038
+ entry = JSON.parse(text);
1039
+ } catch {
1040
+ return;
1041
+ }
1042
+ if (!entry || typeof entry !== "object")
1043
+ return;
1044
+ const rec = entry;
1045
+ if (isLegacyProgressEntry(entry)) {
1046
+ const parent = rec.parentUuid;
1047
+ progressBridge.set(rec.uuid, parent && progressBridge.has(parent) ? progressBridge.get(parent) ?? null : parent);
1048
+ return;
1049
+ }
1050
+ const skeleton = stripToSkeleton(rec);
1051
+ if (!skeleton)
1052
+ return;
1053
+ if (skeleton.parentUuid && progressBridge.has(skeleton.parentUuid)) {
1054
+ skeleton.parentUuid = progressBridge.get(skeleton.parentUuid) ?? null;
1055
+ }
1056
+ skeletons.set(skeleton.uuid, skeleton);
1057
+ ranges.set(skeleton.uuid, { offset: fileOffset, length: line.length });
1058
+ };
1059
+ for (;; ) {
1060
+ const { bytesRead } = await fd.read(buf, 0, buf.length, readPos);
1061
+ if (bytesRead <= 0)
1062
+ break;
1063
+ const chunkFileStart = readPos;
1064
+ readPos += bytesRead;
1065
+ let chunk = buf.subarray(0, bytesRead);
1066
+ let contentSkip = 0;
1067
+ if (firstChunk) {
1068
+ firstChunk = false;
1069
+ if (bytesRead >= 3 && buf[0] === 239 && buf[1] === 187 && buf[2] === 191) {
1070
+ contentSkip = 3;
1071
+ chunk = chunk.subarray(3);
1072
+ }
1073
+ }
1074
+ const data = carry.length > 0 ? Buffer.concat([carry, chunk]) : Buffer.from(chunk);
1075
+ const dataFileStart = chunkFileStart + contentSkip - carry.length;
1076
+ let lineStart = 0;
1077
+ for (;; ) {
1078
+ const nl = data.indexOf(10, lineStart);
1079
+ if (nl < 0)
1080
+ break;
1081
+ processLine(data.subarray(lineStart, nl), dataFileStart + lineStart);
1082
+ lineStart = nl + 1;
1083
+ }
1084
+ carry = Buffer.from(data.subarray(lineStart));
1085
+ carryFileStart = dataFileStart + lineStart;
1086
+ }
1087
+ if (carry.length > 0) {
1088
+ processLine(carry, carryFileStart);
1089
+ }
1090
+ const asTranscriptMap = skeletons;
1091
+ applyPreservedSegmentRelinks(asTranscriptMap);
1092
+ applySnipRemovals(asTranscriptMap);
1093
+ return {
1094
+ skeletons,
1095
+ ranges,
1096
+ ino: fst.ino,
1097
+ size: fst.size,
1098
+ readRanges: async (list) => {
1099
+ const out = [];
1100
+ for (const r of list) {
1101
+ const b = Buffer.alloc(r.length);
1102
+ let filled = 0;
1103
+ while (filled < r.length) {
1104
+ const { bytesRead: n } = await fd.read(b, filled, r.length - filled, r.offset + filled);
1105
+ if (n <= 0)
1106
+ throw new TranscriptChangedDuringReadError;
1107
+ filled += n;
1108
+ }
1109
+ out.push(b);
1110
+ }
1111
+ return out;
1112
+ },
1113
+ close: async () => {
1114
+ await fd.close();
1115
+ }
1116
+ };
1117
+ } catch (e) {
1118
+ await fd.close().catch(() => {});
1119
+ throw e;
1120
+ }
1121
+ }
953
1122
 
954
1123
  // src/engine/session/readonly.ts
955
1124
  async function loadTranscriptFull(filePath, opts) {
@@ -1075,6 +1244,8 @@ var HARD_MAX_SCAN_SESSIONS = 16384;
1075
1244
  var HARD_MAX_SCOPES_PER_RUNTIME = 128;
1076
1245
  var DEFAULT_PAGE_SIZE = 50;
1077
1246
  var HARD_MAX_PAGE_SIZE = 200;
1247
+ var DEFAULT_MAX_REPLAY_PAGE_BYTES = 4 * MIB;
1248
+ var HARD_MAX_REPLAY_PAGE_BYTES = 16 * MIB;
1078
1249
  var DEFAULT_MAX_RECORD_BYTES = MIB;
1079
1250
  var HARD_MAX_RECORD_BYTES = 8 * MIB;
1080
1251
  var DEFAULT_MAX_PARSE_RECORDS = 1e5;
@@ -1844,9 +2015,179 @@ function createFollowSubscription(deps) {
1844
2015
  };
1845
2016
  }
1846
2017
 
2018
+ // src/atlascode/web/replayPaging.ts
2019
+ import { createHash } from "node:crypto";
2020
+ function encodePageToken(t) {
2021
+ return Buffer.from(JSON.stringify(t), "utf8").toString("base64url");
2022
+ }
2023
+ function decodePageToken(token) {
2024
+ const invalid = () => new WebSessionError("invalidRequest", "malformed replay pageToken");
2025
+ let raw;
2026
+ try {
2027
+ raw = Buffer.from(token, "base64url").toString("utf8");
2028
+ } catch {
2029
+ throw invalid();
2030
+ }
2031
+ let parsed;
2032
+ try {
2033
+ parsed = JSON.parse(raw);
2034
+ } catch {
2035
+ throw invalid();
2036
+ }
2037
+ if (!parsed || typeof parsed !== "object")
2038
+ throw invalid();
2039
+ const t = parsed;
2040
+ if (t.v !== 1 || typeof t.scopeId !== "string" || typeof t.sessionId !== "string" || typeof t.offset !== "number" || !Number.isInteger(t.offset) || t.offset < 0 || typeof t.anchor !== "string" || !/^[0-9a-f]{16}$/.test(t.anchor)) {
2041
+ throw invalid();
2042
+ }
2043
+ return t;
2044
+ }
2045
+ function chainPrefixFingerprint(uuids) {
2046
+ return createHash("sha256").update(uuids.join(`
2047
+ `), "utf8").digest("hex").slice(0, 16);
2048
+ }
2049
+ function renderRecord(raw) {
2050
+ let entry;
2051
+ try {
2052
+ entry = JSON.parse(Buffer.from(raw).toString("utf8"));
2053
+ } catch {
2054
+ throw new WebSessionError("ioUnavailable", "paged record unreadable (snapshot inconsistency)", true);
2055
+ }
2056
+ const source = {
2057
+ uuid: entry.uuid,
2058
+ parentUuid: entry.parentUuid ?? null,
2059
+ type: entry.type,
2060
+ timestamp: entry.timestamp ?? null,
2061
+ ...entry.message !== undefined ? { message: entry.message } : {}
2062
+ };
2063
+ return {
2064
+ id: source.uuid,
2065
+ role: source.type,
2066
+ createdAt: source.timestamp ?? null,
2067
+ blocks: projectBlocks(source)
2068
+ };
2069
+ }
2070
+ async function loadReplayPage(deps, scopeId, sessionId, req, signal) {
2071
+ const { adapter, engine, limits: L } = deps;
2072
+ let tok;
2073
+ if (req.pageToken !== undefined) {
2074
+ tok = decodePageToken(req.pageToken);
2075
+ if (tok.scopeId !== scopeId || tok.sessionId !== sessionId) {
2076
+ throw new WebSessionError("invalidRequest", "replay pageToken domain mismatch (scopeId/sessionId bound)");
2077
+ }
2078
+ }
2079
+ const pageSize = Math.max(1, Math.min(req.pageSize ?? L.pageSize, L.pageSize));
2080
+ const stPre = await adapter.statTranscript(scopeId, sessionId);
2081
+ if (!stPre) {
2082
+ throw new WebSessionError("notFound", `session not found: ${sessionId}`);
2083
+ }
2084
+ const entries = await adapter.listSessionFiles(scopeId);
2085
+ const entry = entries.find((e) => e.sessionId === sessionId);
2086
+ if (!entry) {
2087
+ throw new WebSessionError("ioUnavailable", `session listed at stat but missing at scan: ${sessionId}`, true);
2088
+ }
2089
+ const filePath = entry.filePath;
2090
+ let reader;
2091
+ try {
2092
+ reader = await engine.openReplayPageReader(filePath, {
2093
+ maxBytes: HARD_MAX_TRANSCRIPT_BYTES,
2094
+ expectIno: stPre.ino
2095
+ });
2096
+ } catch (e) {
2097
+ if (e instanceof TranscriptTooLargeError) {
2098
+ throw new WebSessionError("resourceLimit", `transcript exceeds limit (${e.size} > ${e.maxBytes} bytes)`);
2099
+ }
2100
+ if (e instanceof TranscriptChangedDuringReadError) {
2101
+ throw new WebSessionError("ioUnavailable", e.message, true);
2102
+ }
2103
+ throw e;
2104
+ }
2105
+ try {
2106
+ const skeletons = reader.skeletons;
2107
+ const leafUuids = computeLeafUuids(skeletons);
2108
+ let leaf;
2109
+ for (const uuid of leafUuids) {
2110
+ const m = skeletons.get(uuid);
2111
+ if (!m)
2112
+ continue;
2113
+ if (!leaf || (m.timestamp ?? "") >= (leaf.timestamp ?? "")) {
2114
+ leaf = m;
2115
+ }
2116
+ }
2117
+ const chain = leaf ? engine.buildConversationChain(skeletons, leaf) : [];
2118
+ const effective = chain.filter((m) => (m.type === "user" || m.type === "assistant") && projectBlocks(m).length > 0);
2119
+ const offset = tok?.offset ?? 0;
2120
+ if (offset > effective.length) {
2121
+ throw new WebSessionError("cursorExpired", `replay pageToken offset ${offset} beyond effective chain length ${effective.length}`);
2122
+ }
2123
+ if (tok) {
2124
+ const anchor = chainPrefixFingerprint(effective.slice(0, offset).map((m) => m.uuid));
2125
+ if (anchor !== tok.anchor) {
2126
+ throw new WebSessionError("cursorExpired", "replay pageToken anchor drift (chain rewritten or compacted)");
2127
+ }
2128
+ }
2129
+ const messages = [];
2130
+ let bytesSum = 0;
2131
+ let count = 0;
2132
+ let i = offset;
2133
+ for (;i < effective.length && count < pageSize; i++) {
2134
+ if (signal?.aborted) {
2135
+ throw new WebSessionError("cancelled", "operation aborted");
2136
+ }
2137
+ const range = reader.ranges.get(effective[i].uuid);
2138
+ if (!range) {
2139
+ throw new WebSessionError("ioUnavailable", "paged chain member has no byte range (snapshot inconsistency)", true);
2140
+ }
2141
+ const [raw] = await reader.readRanges([range]);
2142
+ const msg = renderRecord(raw);
2143
+ const b = Buffer.byteLength(JSON.stringify(msg));
2144
+ const projected = 2 + bytesSum + b + count;
2145
+ if (projected > L.maxReplayPageBytes) {
2146
+ if (count === 0) {
2147
+ throw new WebSessionError("resourceLimit", `single record exceeds replay page limit (${projected} > ${L.maxReplayPageBytes} bytes)`);
2148
+ }
2149
+ break;
2150
+ }
2151
+ messages.push(msg);
2152
+ bytesSum += b;
2153
+ count++;
2154
+ }
2155
+ const nextOffset = offset + count;
2156
+ const hasMore = nextOffset < effective.length;
2157
+ let nextPageToken;
2158
+ if (hasMore) {
2159
+ nextPageToken = encodePageToken({
2160
+ v: 1,
2161
+ scopeId,
2162
+ sessionId,
2163
+ offset: nextOffset,
2164
+ anchor: chainPrefixFingerprint(effective.slice(0, nextOffset).map((m) => m.uuid))
2165
+ });
2166
+ }
2167
+ const stPost = await adapter.statTranscript(scopeId, sessionId);
2168
+ if (!stPost || stPost.ino !== stPre.ino || stPost.sizeBytes !== stPre.sizeBytes || stPost.mtimeMs !== stPre.mtimeMs) {
2169
+ throw new WebSessionError("ioUnavailable", "transcript changed during replay page (snapshot inconsistency)", true);
2170
+ }
2171
+ return {
2172
+ projection: {
2173
+ sessionId,
2174
+ productId: deps.productId,
2175
+ scopeId,
2176
+ semantics: "persisted-effective-conversation",
2177
+ messages,
2178
+ truncated: false
2179
+ },
2180
+ hasMore,
2181
+ ...nextPageToken !== undefined ? { nextPageToken } : {}
2182
+ };
2183
+ } finally {
2184
+ await reader.close().catch(() => {});
2185
+ }
2186
+ }
2187
+
1847
2188
  // src/atlascode/web/sessionStoreAdapter.ts
1848
- import { constants as fsConstants2 } from "node:fs";
1849
- import { lstat, open as open2, readdir, realpath, stat as stat2 } from "node:fs/promises";
2189
+ import { constants as fsConstants3 } from "node:fs";
2190
+ import { lstat, open as open3, readdir, realpath, stat as stat2 } from "node:fs/promises";
1850
2191
  import { isAbsolute, join, resolve, sep } from "node:path";
1851
2192
  var SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
1852
2193
  function assertSessionIdShape(sessionId) {
@@ -1900,7 +2241,7 @@ function createNodeFsSessionStoreAdapter(options) {
1900
2241
  }
1901
2242
  let fh;
1902
2243
  try {
1903
- fh = await open2(filePath, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
2244
+ fh = await open3(filePath, fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW);
1904
2245
  } catch (e) {
1905
2246
  mapFsError(e, "transcript open");
1906
2247
  }
@@ -2330,6 +2671,7 @@ function createReadonlySessionRuntime(options) {
2330
2671
  maxRecordBytes: validateBoundedInt("maxRecordBytes", options.limits?.maxRecordBytes, DEFAULT_MAX_RECORD_BYTES, HARD_MAX_RECORD_BYTES),
2331
2672
  maxParseRecords: validateBoundedInt("maxParseRecords", options.limits?.maxParseRecords, DEFAULT_MAX_PARSE_RECORDS, HARD_MAX_PARSE_RECORDS),
2332
2673
  maxProjectionBytes: validateBoundedInt("maxProjectionBytes", options.limits?.maxProjectionBytes, DEFAULT_MAX_PROJECTION_BYTES, HARD_MAX_PROJECTION_BYTES),
2674
+ maxReplayPageBytes: validateBoundedInt("maxReplayPageBytes", options.limits?.maxReplayPageBytes, DEFAULT_MAX_REPLAY_PAGE_BYTES, HARD_MAX_REPLAY_PAGE_BYTES),
2333
2675
  maxSubscriptions: validateBoundedInt("maxSubscriptions", options.limits?.maxSubscriptions, DEFAULT_MAX_SUBSCRIPTIONS, HARD_MAX_SUBSCRIPTIONS),
2334
2676
  maxConcurrentReads: validateBoundedInt("maxConcurrentReads", options.limits?.maxConcurrentReads, DEFAULT_MAX_CONCURRENT_READS, HARD_MAX_CONCURRENT_READS),
2335
2677
  maxPendingEvents: validateBoundedInt("maxPendingEvents", options.limits?.maxPendingEvents, DEFAULT_MAX_PENDING_EVENTS, HARD_MAX_PENDING_EVENTS),
@@ -2558,6 +2900,32 @@ function createReadonlySessionRuntime(options) {
2558
2900
  async replaySession(req, signal) {
2559
2901
  assertStarted("replay session");
2560
2902
  assertScope(req.scopeId);
2903
+ if ("pageSize" in req || "pageToken" in req) {
2904
+ const open = options.engine.openReplayPageReader;
2905
+ if (!open) {
2906
+ throw new WebSessionError("invalidRequest", "replay paging not supported by injected engine");
2907
+ }
2908
+ acquireRead();
2909
+ try {
2910
+ const paged = await loadReplayPage({
2911
+ adapter,
2912
+ engine: {
2913
+ openReplayPageReader: open,
2914
+ buildConversationChain: options.engine.buildConversationChain
2915
+ },
2916
+ limits: L,
2917
+ productId: options.productId
2918
+ }, req.scopeId, req.sessionId, req, signal);
2919
+ return {
2920
+ of: "replaySession",
2921
+ projection: paged.projection,
2922
+ hasMore: paged.hasMore,
2923
+ ...paged.nextPageToken !== undefined ? { nextPageToken: paged.nextPageToken } : {}
2924
+ };
2925
+ } finally {
2926
+ releaseRead();
2927
+ }
2928
+ }
2561
2929
  const projection = await loadProjection(req.scopeId, req.sessionId, signal);
2562
2930
  return { of: "replaySession", projection };
2563
2931
  },
@@ -2622,7 +2990,8 @@ function atlasWebSessionEngine() {
2622
2990
  leafUuids: loaded.leafUuids
2623
2991
  };
2624
2992
  },
2625
- buildConversationChain: (messages, leaf) => buildConversationChain(messages, leaf)
2993
+ buildConversationChain: (messages, leaf) => buildConversationChain(messages, leaf),
2994
+ openReplayPageReader: (filePath, opts) => openReplayPageReader(filePath, opts)
2626
2995
  };
2627
2996
  }
2628
2997
  function createDefaultReadonlySessionRuntime(options) {
@@ -5591,7 +5960,7 @@ function bucketFor(state, inst) {
5591
5960
  return bucket;
5592
5961
  }
5593
5962
  var handoff;
5594
- var open3 = [];
5963
+ var open4 = [];
5595
5964
  var memo = {
5596
5965
  alloc(_inst, payload, empty) {
5597
5966
  const bucket = handoff;
@@ -5600,7 +5969,7 @@ var memo = {
5600
5969
  handoff = undefined;
5601
5970
  const entry = { value: empty, issues: null };
5602
5971
  bucket.set(payload.value, entry);
5603
- open3.push(entry);
5972
+ open4.push(entry);
5604
5973
  return empty;
5605
5974
  },
5606
5975
  guard(inst) {
@@ -5671,10 +6040,10 @@ var memo = {
5671
6040
  return payload;
5672
6041
  }
5673
6042
  handoff = bucket;
5674
- const depth = open3.length;
6043
+ const depth = open4.length;
5675
6044
  const result = base(payload, ctx);
5676
6045
  handoff = undefined;
5677
- const entry = open3.length > depth ? open3.pop() : undefined;
6046
+ const entry = open4.length > depth ? open4.pop() : undefined;
5678
6047
  if (result instanceof Promise) {
5679
6048
  return result.then((r) => {
5680
6049
  if (entry)
@@ -8381,6 +8750,290 @@ function createExecutionOutlet(options) {
8381
8750
  }
8382
8751
  };
8383
8752
  }
8753
+ // src/kernel/execution/executionKernel.ts
8754
+ var EXECUTION_QUEUE_DEPTH = 16;
8755
+ var EXECUTION_APPROVAL_TIMEOUT_MS = 300000;
8756
+ var EXECUTION_MAX_TEXT_BYTES = 2 * 1024 * 1024;
8757
+ var EXECUTION_FOLLOW_BUFFER_LIMIT = 1e4;
8758
+ var EXECUTION_MAX_DELTA_BYTES = 256 * 1024;
8759
+ var streamKey = (ws, s) => `${ws}\x00${s}`;
8760
+ function createExecutionKernel(options) {
8761
+ const now = options.now ?? (() => Date.now());
8762
+ const actorId = options.actorId ?? (() => "kernel");
8763
+ const queueDepth = options.queueDepth ?? EXECUTION_QUEUE_DEPTH;
8764
+ const approvalTimeoutMs = options.approvalTimeoutMs ?? EXECUTION_APPROVAL_TIMEOUT_MS;
8765
+ const maxTextBytes = options.maxTextBytes ?? EXECUTION_MAX_TEXT_BYTES;
8766
+ const followBufferLimit = options.followBufferLimit ?? EXECUTION_FOLLOW_BUFFER_LIMIT;
8767
+ const maxDeltaBytes = EXECUTION_MAX_DELTA_BYTES;
8768
+ const streams = new Map;
8769
+ const approvals = new Map;
8770
+ const subscribers = new Set;
8771
+ const turnStates = new Map;
8772
+ let turnCounter = 0;
8773
+ let approvalCounter = 0;
8774
+ const streamOf = (ws, s) => {
8775
+ const key = streamKey(ws, s);
8776
+ let st = streams.get(key);
8777
+ if (!st) {
8778
+ st = {
8779
+ cursor: 0,
8780
+ buffer: [],
8781
+ overflowed: false,
8782
+ queue: [],
8783
+ running: undefined,
8784
+ turns: new Map,
8785
+ idempotency: new Map
8786
+ };
8787
+ streams.set(key, st);
8788
+ }
8789
+ return st;
8790
+ };
8791
+ const err = (code, message, retryable = false) => ({
8792
+ code,
8793
+ message,
8794
+ retryable
8795
+ });
8796
+ const emit = (st, bind, type, payload) => {
8797
+ st.cursor += 1;
8798
+ if (st.buffer.length >= followBufferLimit) {
8799
+ st.overflowed = true;
8800
+ st.buffer.shift();
8801
+ }
8802
+ const event = {
8803
+ v: 0,
8804
+ id: crypto.randomUUID(),
8805
+ ts: now(),
8806
+ type,
8807
+ bind,
8808
+ cursor: String(st.cursor).padStart(16, "0"),
8809
+ payload
8810
+ };
8811
+ st.buffer.push(event);
8812
+ for (const cb of subscribers)
8813
+ cb(event);
8814
+ return event;
8815
+ };
8816
+ const settleApproval = (a, decision) => {
8817
+ if (a.settled)
8818
+ return;
8819
+ a.settled = true;
8820
+ if (a.timer)
8821
+ clearTimeout(a.timer);
8822
+ approvals.delete(a.approvalId);
8823
+ const st = streamOf(a.workspaceId, a.sessionId);
8824
+ const event = emit(st, { workspaceId: a.workspaceId, sessionId: a.sessionId, turnId: a.turnId }, "approval.settled", { approvalId: a.approvalId, decision, actorId: actorId(), timestamp: now() });
8825
+ a.resolve(decision);
8826
+ return event;
8827
+ };
8828
+ const settleTurn = (st, turn, terminal, failedMessage) => {
8829
+ if (turn.state === "completed" || turn.state === "failed" || turn.state === "cancelled") {
8830
+ return;
8831
+ }
8832
+ turn.state = terminal;
8833
+ turnStates.set(turn.turnId, terminal);
8834
+ if (terminal === "cancelled") {
8835
+ for (const a of [...approvals.values()]) {
8836
+ if (a.turnId === turn.turnId && !a.settled)
8837
+ settleApproval(a, "voidedByCancel");
8838
+ }
8839
+ }
8840
+ st.running = st.running?.turnId === turn.turnId ? undefined : st.running;
8841
+ const event = emit(st, { workspaceId: streamWs(st), sessionId: streamSess(st), turnId: turn.turnId }, `turn.${terminal}`, terminal === "failed" ? { message: failedMessage ?? "turn failed" } : {});
8842
+ pump(streamWs(st), streamSess(st));
8843
+ return event;
8844
+ };
8845
+ const wsByStream = new Map;
8846
+ const sessByStream = new Map;
8847
+ const streamWs = (st) => wsByStream.get(st) ?? "";
8848
+ const streamSess = (st) => sessByStream.get(st) ?? "";
8849
+ const origStreamOf = streamOf;
8850
+ const streamOfTracked = (ws, s) => {
8851
+ const st = origStreamOf(ws, s);
8852
+ if (!wsByStream.has(st)) {
8853
+ wsByStream.set(st, ws);
8854
+ sessByStream.set(st, s);
8855
+ }
8856
+ return st;
8857
+ };
8858
+ const pump = (ws, s) => {
8859
+ const st = streamOfTracked(ws, s);
8860
+ if (st.running || st.queue.length === 0)
8861
+ return;
8862
+ const turn = st.queue.shift();
8863
+ turn.state = "running";
8864
+ turnStates.set(turn.turnId, "running");
8865
+ turn.controller = new AbortController;
8866
+ st.running = turn;
8867
+ emit(st, { workspaceId: ws, sessionId: s, turnId: turn.turnId }, "turn.started", {});
8868
+ (async () => {
8869
+ let outcome;
8870
+ try {
8871
+ outcome = await options.runTurn({
8872
+ bind: { workspaceId: ws, sessionId: s, turnId: turn.turnId },
8873
+ text: turn.text,
8874
+ signal: turn.controller.signal,
8875
+ emitDelta: (text) => {
8876
+ if (turn.state !== "running" || turn.controller?.signal.aborted)
8877
+ return;
8878
+ if (Buffer.byteLength(text, "utf8") > maxDeltaBytes) {
8879
+ settleTurn(st, turn, "failed", `turn.delta 超 ${maxDeltaBytes} 字节上限(合同 §8)`);
8880
+ return;
8881
+ }
8882
+ emit(st, { workspaceId: ws, sessionId: s, turnId: turn.turnId }, "turn.delta", { text });
8883
+ },
8884
+ requestApproval: () => {
8885
+ const approvalId = `appr-${++approvalCounter}`;
8886
+ return new Promise((resolve) => {
8887
+ const approval = {
8888
+ approvalId,
8889
+ turnId: turn.turnId,
8890
+ workspaceId: ws,
8891
+ sessionId: s,
8892
+ requestedAt: now(),
8893
+ settled: false,
8894
+ timer: undefined,
8895
+ resolve
8896
+ };
8897
+ approvals.set(approvalId, approval);
8898
+ emit(st, { workspaceId: ws, sessionId: s, turnId: turn.turnId }, "approval.requested", { approvalId });
8899
+ approval.timer = setTimeout(() => {
8900
+ settleApproval(approval, "expired");
8901
+ }, approvalTimeoutMs);
8902
+ approval.timer.unref?.();
8903
+ });
8904
+ }
8905
+ });
8906
+ } catch (e) {
8907
+ outcome = "failed";
8908
+ settleTurn(st, turn, "failed", e instanceof Error ? e.message : String(e));
8909
+ return;
8910
+ }
8911
+ if (outcome === "failed") {
8912
+ settleTurn(st, turn, "failed");
8913
+ } else {
8914
+ settleTurn(st, turn, outcome);
8915
+ }
8916
+ })();
8917
+ };
8918
+ const handleCommand = async (command) => {
8919
+ const ws = command.bind.workspaceId;
8920
+ const s = command.bind.sessionId;
8921
+ if (ws.includes("\x00") || s.includes("\x00")) {
8922
+ return err("invalidBind", "workspaceId/sessionId 不得含 NUL 分隔符(流键碰撞面)");
8923
+ }
8924
+ if (command.type === "turn.submit") {
8925
+ const st = streamOfTracked(ws, s);
8926
+ const recorded = st.idempotency.get(command.payload.submitId);
8927
+ if (recorded)
8928
+ return recorded;
8929
+ if (Buffer.byteLength(command.payload.text, "utf8") > maxTextBytes) {
8930
+ const rejection = err("resourceLimit", `turn.submit 超过 ${maxTextBytes} 字节上限(合同 §8)`);
8931
+ st.idempotency.set(command.payload.submitId, rejection);
8932
+ return rejection;
8933
+ }
8934
+ if (st.queue.length + (st.running ? 1 : 0) >= queueDepth) {
8935
+ const rejection = err("queueFull", `会话队列已满(深度 ${queueDepth},合同 §8)`, true);
8936
+ st.idempotency.set(command.payload.submitId, rejection);
8937
+ return rejection;
8938
+ }
8939
+ const turn = {
8940
+ turnId: `turn-${++turnCounter}`,
8941
+ submitId: command.payload.submitId,
8942
+ text: command.payload.text,
8943
+ state: "queued"
8944
+ };
8945
+ st.turns.set(turn.turnId, turn);
8946
+ turnStates.set(turn.turnId, "queued");
8947
+ st.queue.push(turn);
8948
+ const accepted = emit(st, { workspaceId: ws, sessionId: s, turnId: turn.turnId }, "turn.accepted", { submitId: command.payload.submitId });
8949
+ st.idempotency.set(command.payload.submitId, accepted);
8950
+ pump(ws, s);
8951
+ return accepted;
8952
+ }
8953
+ if (command.type === "turn.cancel" || command.type === "queue.remove") {
8954
+ const st = streamOfTracked(ws, s);
8955
+ const turn = st.turns.get(command.payload.targetTurnId);
8956
+ if (!turn)
8957
+ return err("notFound", `目标回合不存在:${command.payload.targetTurnId}`);
8958
+ if (turn.state === "queued") {
8959
+ st.queue = st.queue.filter((t) => t.turnId !== turn.turnId);
8960
+ turn.state = "cancelled";
8961
+ turnStates.set(turn.turnId, "cancelled");
8962
+ return emit(st, { workspaceId: ws, sessionId: s, turnId: turn.turnId }, "turn.cancelled", {});
8963
+ }
8964
+ if (turn.state === "running") {
8965
+ turn.controller?.abort();
8966
+ turn.state = "cancelled";
8967
+ turnStates.set(turn.turnId, "cancelled");
8968
+ const event = emit(st, { workspaceId: ws, sessionId: s, turnId: turn.turnId }, "turn.cancelled", {});
8969
+ for (const a of [...approvals.values()]) {
8970
+ if (a.turnId === turn.turnId && !a.settled)
8971
+ settleApproval(a, "voidedByCancel");
8972
+ }
8973
+ st.running = st.running?.turnId === turn.turnId ? undefined : st.running;
8974
+ pump(ws, s);
8975
+ return event;
8976
+ }
8977
+ return err("alreadySettled", `回合已终态(${turn.state}),边界错误不改状态(合同 §4)`);
8978
+ }
8979
+ if (command.type === "approval.decide") {
8980
+ const a = approvals.get(command.payload.approvalId);
8981
+ if (!a)
8982
+ return err("notFound", `待批操作不存在或已结算:${command.payload.approvalId}`);
8983
+ if (command.bind.turnId !== a.turnId || command.bind.workspaceId !== a.workspaceId || command.bind.sessionId !== a.sessionId) {
8984
+ return err("approvalBindMismatch", `decide bind 三元组与审批归属不一致(合同 §5)`);
8985
+ }
8986
+ if (a.settled || now() - a.requestedAt >= approvalTimeoutMs) {
8987
+ if (!a.settled)
8988
+ settleApproval(a, "expired");
8989
+ return err("alreadySettled", "待批操作已结算(过期/已决),边界错误(合同 §5)");
8990
+ }
8991
+ return settleApproval(a, command.payload.decision);
8992
+ }
8993
+ return err("notImplemented", "follow.resume 于 S4 切片落地(合同 §6)");
8994
+ };
8995
+ return {
8996
+ handleCommand,
8997
+ replaySince: (workspaceId, sessionId, cursor) => {
8998
+ const st = streams.get(streamKey(workspaceId, sessionId));
8999
+ const headCursor = String(st?.cursor ?? 0).padStart(16, "0");
9000
+ if (!st || !cursor)
9001
+ return { kind: "baseline", events: [], headCursor };
9002
+ if (st.overflowed)
9003
+ return { kind: "expired", events: [], headCursor };
9004
+ const idx = st.buffer.findIndex((e) => e.cursor === cursor);
9005
+ if (idx < 0)
9006
+ return { kind: "expired", events: [], headCursor };
9007
+ return { kind: "delta", events: st.buffer.slice(idx + 1), headCursor };
9008
+ },
9009
+ onEvent: (cb) => {
9010
+ subscribers.add(cb);
9011
+ return () => subscribers.delete(cb);
9012
+ },
9013
+ turnStates,
9014
+ bufferState: (workspaceId, sessionId) => {
9015
+ const st = streams.get(streamKey(workspaceId, sessionId));
9016
+ return st ? { overflowed: st.overflowed, kept: st.buffer.length } : { overflowed: false, kept: 0 };
9017
+ }
9018
+ };
9019
+ }
9020
+
9021
+ // src/kernel/execution/executionComposition.ts
9022
+ function createExecutionComposition(options = {}) {
9023
+ const kernel = createExecutionKernel({
9024
+ runTurn: options.runTurn ?? (async () => {
9025
+ throw new Error("执行能力 runTurn 真体未接线(B0 执行出口波 S4 落地细化附注:引擎深缝候后续切片;能力开关 fail-closed off 时不可达)");
9026
+ }),
9027
+ actorId: options.actorId ?? (() => "atlas-local-ambient"),
9028
+ ...options.now !== undefined ? { now: options.now } : {}
9029
+ });
9030
+ const outlet = createExecutionOutlet({
9031
+ isExecutionEnabled: () => process.env.ATLAS_WEB_EXECUTION_ENABLED === "1",
9032
+ dispatchCommand: (command) => kernel.handleCommand(command),
9033
+ resumeExecution: (bind, cursor) => kernel.replaySince(bind.workspaceId, bind.sessionId, cursor)
9034
+ });
9035
+ return { kernel, outlet };
9036
+ }
8384
9037
  export {
8385
9038
  EXECUTION_CAPABILITY_DISABLED_CODE,
8386
9039
  EXECUTION_PROTOCOL_VERSION,
@@ -8391,6 +9044,7 @@ export {
8391
9044
  WebExecutionEventSchema,
8392
9045
  WebSessionError,
8393
9046
  createDefaultReadonlySessionRuntime,
9047
+ createExecutionComposition,
8394
9048
  createExecutionOutlet,
8395
9049
  createReadonlySessionRuntime
8396
9050
  };