omo-web 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -6401,6 +6401,7 @@ var emptyBody = strictObject({});
6401
6401
  var entryId = string2().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/u);
6402
6402
  var actions = discriminatedUnion("action", [
6403
6403
  strictObject({ action: literal("resume") }),
6404
+ strictObject({ action: literal("close") }),
6404
6405
  strictObject({
6405
6406
  action: literal("prompt"),
6406
6407
  message: string2().max(200000),
@@ -6444,8 +6445,36 @@ var actions = discriminatedUnion("action", [
6444
6445
  function model(value) {
6445
6446
  return value == null ? null : pick2(value, ["id", "provider", "name", "contextWindow", "maxTokens", "reasoning", "input", "supportedThinkingLevels"]);
6446
6447
  }
6447
- function message(value) {
6448
+ function nativeFileDetails(result) {
6449
+ if (result.role !== "toolResult" || result.isError !== false || result.partial === true || result.truncated === true || typeof result.errorMessage === "string" && result.errorMessage || typeof result.toolCallId !== "string" || !result.toolCallId || result.toolCallId.length > 256)
6450
+ return;
6451
+ const details = result.details;
6452
+ if (typeof details !== "object" || details === null || Array.isArray(details))
6453
+ return;
6454
+ const { diff, patch, operation, omitted } = details;
6455
+ const edit = result.toolName === "edit";
6456
+ if (!edit && !(result.toolName === "write" && (operation === "add" || operation === "update")))
6457
+ return;
6458
+ const key = typeof patch === "string" && patch ? "patch" : "diff";
6459
+ const text = key === "patch" ? patch : edit ? diff : undefined;
6460
+ const limit = 24 * 1024;
6461
+ const evidence = omitted === true || typeof text === "string" && (text.length > limit || Buffer.byteLength(JSON.stringify(text)) > limit) ? { omitted: true } : typeof text === "string" && text ? { [key]: text } : undefined;
6462
+ if (evidence)
6463
+ return edit ? evidence : { ...evidence, operation };
6464
+ }
6465
+ function message(value, includeFileChange = true) {
6448
6466
  const m = pick2(value, ["role", "content", "timestamp", "toolName", "toolCallId", "isError", "stopReason", "errorMessage", "usage", "provider", "model", "customType"]);
6467
+ if (m.role === "toolResult") {
6468
+ const raw = record2(value);
6469
+ for (const key of ["partial", "truncated"])
6470
+ if (raw[key] === true)
6471
+ m[key] = true;
6472
+ if (includeFileChange) {
6473
+ const details = nativeFileDetails(raw);
6474
+ if (details)
6475
+ m.fileChange = pick2(details, ["patch", "diff", "omitted"]);
6476
+ }
6477
+ }
6449
6478
  if (Array.isArray(m.content))
6450
6479
  m.content = m.content.flatMap((part) => {
6451
6480
  const block = record2(part);
@@ -6455,12 +6484,12 @@ function message(value) {
6455
6484
  });
6456
6485
  return m.role === "bashExecution" ? { ...m, ...pick2(value, ["command", "output", "exitCode", "cancelled", "truncated"]) } : m;
6457
6486
  }
6458
- function transcriptMessage(value) {
6487
+ function transcriptMessage(value, includeFileChange = true) {
6459
6488
  const raw = record2(value);
6460
6489
  if (raw.role === "custom" ? raw.display !== true : !["user", "assistant", "toolResult", "bashExecution"].includes(String(raw.role))) {
6461
6490
  return;
6462
6491
  }
6463
- return message(raw);
6492
+ return message(raw, includeFileChange);
6464
6493
  }
6465
6494
  var safeLabel = string2().trim().min(1).max(120).refine(noControlChars);
6466
6495
  var questionOption = object({
@@ -6555,7 +6584,7 @@ function browserEvent(value) {
6555
6584
  case "message_start":
6556
6585
  case "message_update":
6557
6586
  case "message_end": {
6558
- const visible = transcriptMessage(value.message);
6587
+ const visible = transcriptMessage(value.message, value.type === "message_end");
6559
6588
  return visible && { type: value.type, message: visible };
6560
6589
  }
6561
6590
  case "tool_execution_start":
@@ -6564,7 +6593,7 @@ function browserEvent(value) {
6564
6593
  const result = record2(value.result ?? value.partialResult);
6565
6594
  return {
6566
6595
  ...pick2(value, ["type", "toolName", "toolCallId", "args", "isError"]),
6567
- ...result.content === undefined ? {} : { result: message(result) }
6596
+ ...result.content === undefined ? {} : { result: message(result, false) }
6568
6597
  };
6569
6598
  }
6570
6599
  case "extension_ui_request":
@@ -7911,6 +7940,13 @@ function allowedRow(row, surface) {
7911
7940
  delete raw.details;
7912
7941
  if (Array.isArray(raw.content))
7913
7942
  raw.content = raw.content.flatMap((block) => isObject2(block) && block.type === "text" && typeof block.text === "string" ? [{ type: "text", text: block.text }] : []);
7943
+ } else if (row.role === "toolResult") {
7944
+ for (const key of ["partial", "truncated"])
7945
+ if (row[key] === true)
7946
+ raw[key] = true;
7947
+ const details = nativeFileDetails(row);
7948
+ if (details)
7949
+ raw.details = details;
7914
7950
  }
7915
7951
  return raw;
7916
7952
  }
@@ -9543,180 +9579,657 @@ class NativeActivity {
9543
9579
  }
9544
9580
  }
9545
9581
 
9546
- // src/session-branches.ts
9547
- import { constants as constants5 } from "fs";
9548
- import { lstat as lstat6, mkdtemp as mkdtemp2, open as open6, realpath as realpath6, rm as rm2, writeFile } from "fs/promises";
9549
- import { basename as basename2, dirname as dirname3, join as join5, resolve as resolve4 } from "path";
9582
+ // src/native-runtime-task-output.ts
9583
+ import { stripVTControlCharacters as stripVTControlCharacters3 } from "util";
9584
+ import { createHash as createHash2 } from "crypto";
9550
9585
 
9551
- // src/session-entry-pages.ts
9552
- import { randomBytes as randomBytes2 } from "crypto";
9553
- var PAGE_TAIL = 40;
9554
- var PAGE_BYTES = 262144;
9555
- var PAGE_TIMEOUT = 6000;
9556
- var MAX_CURSORS = 128;
9557
- var MAX_CURSOR_IDS = 32768;
9558
- var CURSOR_TTL = 10 * 60000;
9559
- var treeCursor = string2().regex(/^[a-f0-9]{64}$/u);
9560
- var staleTree = () => new WebError(409, "tree_stale", "\u4F1A\u8BDD\u6216\u5206\u652F\u4F4D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u52A0\u8F7D\u4F1A\u8BDD\u6811\u3002");
9561
- var malformedPage = () => new WebError(502, "tree_reply_invalid", "OmO \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u4F1A\u8BDD\u5206\u9875\u3002");
9562
- var pageTooLarge = () => new WebError(409, "tree_budget", "\u4F1A\u8BDD\u5386\u53F2\u8D85\u8FC7\u8BFB\u53D6\u9884\u7B97\u3002");
9563
- var envelope = object({
9564
- entries: unknown(),
9565
- leafId: entryId.nullable(),
9566
- hasMore: boolean2(),
9567
- next_before: entryId.optional()
9586
+ // src/native-runtime-projection.ts
9587
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
9588
+ var identity = string2().min(1).max(256).regex(/\S/u);
9589
+ var count2 = int().nonnegative();
9590
+ var timestamp2 = exports_iso.datetime().transform(Date.parse).pipe(int());
9591
+ var RUNTIME_LIST_LIMIT = 256;
9592
+ var boundedRows = (row, limit = RUNTIME_LIST_LIMIT) => preprocess((value) => Array.isArray(value) && value.length <= limit ? value : undefined, array(row));
9593
+ var malformed2 = { status: "malformed" };
9594
+ var ownershipChanged = { status: "ownership_changed" };
9595
+ var notFound2 = { status: "not_found" };
9596
+ var displayText2 = (maxBytes) => string2().max(maxBytes * 2).transform((value) => stripVTControlCharacters2(value).replace(/\s+/gu, " ").replace(/[\p{Cc}\p{Cf}\p{Cs}]/gu, "").trim()).refine((value) => value.length > 0 && Buffer.byteLength(value) <= maxBytes && !/[<>]|(?:^|[\s"'`(=])(?:~?\/(?!\s|$)|[a-z]:[\\/]|\\\\)/iu.test(value)).optional().catch(undefined);
9597
+ var title = displayText2(128);
9598
+ var description = displayText2(320);
9599
+ var model2 = string2().max(128).regex(/^(?![a-z]:\/)[a-z\d][a-z\d._:@+-]*(?:\/[a-z\d][a-z\d._:@+-]*)*$/iu);
9600
+ var configuredModel = model2.optional().catch(undefined);
9601
+ var actualReasoning = string2().trim().toLowerCase().pipe(_enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"])).optional().catch(undefined);
9602
+ var effectiveModel = object({
9603
+ provider: string2().max(48).regex(/^[a-z\d][a-z\d._-]*$/iu),
9604
+ model_id: model2,
9605
+ reasoning: unknown().optional(),
9606
+ reasoning_effort: unknown().optional()
9607
+ }).transform(({ provider, model_id, reasoning, reasoning_effort }) => ({ provider, modelId: model_id, reasoning: actualReasoning.parse(reasoning === undefined ? reasoning_effort : reasoning) })).optional().catch(undefined);
9608
+ var optionalTime = timestamp2.optional().catch(undefined);
9609
+ var agent = _enum(["explore", "librarian", "delivery-worker", "technical-writing", "quick-scan"]);
9610
+ var category = _enum([
9611
+ "quick",
9612
+ "deep-low",
9613
+ "deep-high",
9614
+ "writing",
9615
+ "visual-engineering",
9616
+ "unspecified-low",
9617
+ "unspecified-high",
9618
+ "architect",
9619
+ "artistry",
9620
+ "ultrabrain"
9621
+ ]);
9622
+ var executionMode = _enum(["in-process", "process"]);
9623
+ var taskId = string2().regex(/^st_[0-9a-f]{8}$/u).brand().optional().catch(undefined);
9624
+ var taskStatus = _enum(["pending", "running", "paused", "completed", "error", "cancelled", "interrupted", "lost"]);
9625
+ var taskRow = object({
9626
+ task_id: taskId,
9627
+ status: taskStatus,
9628
+ created_at: timestamp2,
9629
+ updated_at: timestamp2,
9630
+ agent_type: agent.optional().catch(undefined),
9631
+ category: category.optional().catch(undefined),
9632
+ execution_mode: executionMode.optional().catch(undefined),
9633
+ task_summary: title,
9634
+ description,
9635
+ model: configuredModel,
9636
+ effective_model: effectiveModel,
9637
+ description_truncated: boolean2().optional().catch(undefined)
9568
9638
  });
9569
- var entryShape = object({ id: entryId, parentId: entryId.nullable(), type: string2().min(1).max(80) });
9570
- async function readNativeLeaf(scope, timeout = PAGE_TIMEOUT) {
9571
- return (await readEntryPage(scope, { leafOnly: true, timeout })).leafId;
9572
- }
9573
- async function readEntryPage(scope, options = {}) {
9574
- if (!scope.isCurrent())
9575
- throw staleTree();
9576
- const { position } = options;
9577
- const tail = options.leafOnly ? 1 : PAGE_TAIL;
9578
- const raw = await scope.engine.requestExisting("get_entries", {
9579
- sessionId: scope.target.route,
9580
- tail,
9581
- maxBytes: PAGE_BYTES,
9582
- ...position ? { before: position.before } : {}
9583
- }, options.timeout ?? PAGE_TIMEOUT);
9584
- if (!scope.isCurrent())
9585
- throw staleTree();
9586
- const parsed = envelope.safeParse(raw);
9639
+ var taskReply = object({
9640
+ parent_session_id: identity,
9641
+ tasks: boundedRows(taskRow),
9642
+ truncated_tasks: count2.optional()
9643
+ });
9644
+ function scopedTasks(raw, owner) {
9645
+ switch (raw.kind) {
9646
+ case "unavailable":
9647
+ return { status: "unavailable", reason: "native_unavailable" };
9648
+ case "not_found":
9649
+ return ownershipChanged;
9650
+ case undefined:
9651
+ break;
9652
+ default:
9653
+ return malformed2;
9654
+ }
9655
+ const parsed = taskReply.safeParse(raw);
9587
9656
  if (!parsed.success)
9588
- throw malformedPage();
9589
- const { entries, leafId, hasMore, next_before: nextBefore } = parsed.data;
9590
- if (options.expectedLeafId !== undefined && options.expectedLeafId !== leafId)
9591
- throw staleTree();
9592
- if (!Array.isArray(entries) || entries.length > tail || raw.nextSince !== undefined || entries.length === 0 && (position !== undefined || hasMore || leafId !== null))
9593
- throw malformedPage();
9594
- const seen = new Set(position?.seen);
9595
- const page = [];
9596
- let bytes = 0;
9597
- for (const value of entries) {
9598
- const fields = entryShape.safeParse(value);
9599
- if (!fields.success)
9600
- throw malformedPage();
9601
- const { id, parentId } = fields.data;
9602
- if (id === parentId || id === position?.before || seen.has(id))
9603
- throw malformedPage();
9604
- seen.add(id);
9605
- page.push({ ...fields.data, raw: record2(value) });
9606
- if (entries.length === 1 && (options.acceptLargeSingleton || options.leafOnly))
9607
- continue;
9608
- try {
9609
- bytes += Buffer.byteLength(JSON.stringify(value), "utf8") + 1;
9610
- } catch (error) {
9611
- if (!(error instanceof RangeError))
9612
- throw error;
9613
- throw pageTooLarge();
9657
+ return malformed2;
9658
+ const { parent_session_id, tasks, truncated_tasks = 0 } = parsed.data;
9659
+ if (parent_session_id !== owner.sessionId)
9660
+ return ownershipChanged;
9661
+ if (truncated_tasks > 0 && tasks.length !== RUNTIME_LIST_LIMIT)
9662
+ return malformed2;
9663
+ const byKey = new Map;
9664
+ const rows = [];
9665
+ for (const row of tasks) {
9666
+ const key = row.task_id === undefined ? undefined : owner.taskKey(row.task_id);
9667
+ if (key !== undefined && row.task_id !== undefined) {
9668
+ if (byKey.has(key))
9669
+ return malformed2;
9670
+ byKey.set(key, { id: row.task_id, status: row.status });
9614
9671
  }
9615
- if (bytes > PAGE_BYTES)
9616
- throw entries.length === 1 ? pageTooLarge() : malformedPage();
9672
+ rows.push({ key, row });
9617
9673
  }
9618
- if (hasMore ? nextBefore === undefined || nextBefore !== page[0]?.id : nextBefore !== undefined || leafId !== null && !seen.has(leafId))
9619
- throw malformedPage();
9620
- return { entries: page, leafId, ...nextBefore === undefined ? {} : { next: { before: nextBefore, seen } } };
9621
- }
9622
- var displayTypes = new Set([
9623
- "message",
9624
- "custom",
9625
- "custom_message",
9626
- "compaction",
9627
- "branch_summary",
9628
- "model_change",
9629
- "thinking_level_change",
9630
- "session_info",
9631
- "label"
9632
- ]);
9633
- var displayRoles = new Set(["user", "assistant", "toolResult", "bashExecution"]);
9634
- function previewEntries(entries) {
9635
- return entries.map(({ id, parentId, type, raw }) => {
9636
- const { role } = record2(raw.message);
9637
- return {
9638
- id,
9639
- parentId,
9640
- type: displayTypes.has(type) ? type : "other",
9641
- ...type === "message" && typeof role === "string" && displayRoles.has(role) ? { role } : {}
9642
- };
9643
- });
9674
+ return { rows, byKey, omittedCount: truncated_tasks };
9644
9675
  }
9645
-
9646
- class TreeCursors {
9647
- #cursors = new Map;
9648
- #ids = 0;
9649
- get(scope, key) {
9650
- const cursor = this.#cursors.get(key);
9651
- if (!cursor || cursor.expires <= Date.now() || cursor.target !== scope.target || cursor.host !== scope.engine.status)
9652
- throw staleTree();
9653
- this.#cursors.delete(key);
9654
- this.#cursors.set(key, cursor);
9655
- return cursor;
9656
- }
9657
- put(scope, leafId, position) {
9658
- const count = position.seen.size;
9659
- if (count > MAX_CURSOR_IDS)
9660
- throw pageTooLarge();
9661
- for (const [key, cursor] of this.#cursors) {
9662
- if (this.#cursors.size < MAX_CURSORS && this.#ids + count <= MAX_CURSOR_IDS)
9663
- break;
9664
- this.#delete(key, cursor);
9665
- }
9666
- const key = randomBytes2(32).toString("hex");
9667
- this.#cursors.set(key, {
9668
- target: scope.target,
9669
- host: scope.engine.status,
9670
- leafId,
9671
- position,
9672
- expires: Date.now() + CURSOR_TTL
9673
- });
9674
- this.#ids += count;
9675
- return key;
9676
- }
9677
- invalidate(target) {
9678
- for (const [key, cursor] of this.#cursors)
9679
- if (cursor.target === target)
9680
- this.#delete(key, cursor);
9681
- }
9682
- #delete(key, cursor) {
9683
- this.#cursors.delete(key);
9684
- this.#ids -= cursor.position.seen.size;
9685
- }
9676
+ function projectTasks(raw, owner) {
9677
+ const result = scopedTasks(raw, owner);
9678
+ if ("status" in result)
9679
+ return result;
9680
+ if (result.rows.length === 0)
9681
+ return { status: "empty" };
9682
+ const rows = result.rows.map(({ key, row }) => ({
9683
+ key,
9684
+ status: row.status,
9685
+ createdAt: row.created_at,
9686
+ updatedAt: row.updated_at,
9687
+ agent: row.agent_type,
9688
+ category: row.category,
9689
+ executionMode: row.execution_mode,
9690
+ title: row.task_summary,
9691
+ description: row.description_truncated === true ? undefined : row.description,
9692
+ configuredModel: row.model,
9693
+ effectiveModel: row.effective_model
9694
+ }));
9695
+ return { status: "ok", rows, omittedCount: result.omittedCount };
9686
9696
  }
9687
-
9688
- // src/session-branches.ts
9689
- var entryKey = string2().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/);
9690
- var branchSelection = discriminatedUnion("kind", [
9691
- strictObject({ kind: literal("fork"), entryId: entryKey }),
9692
- strictObject({ kind: literal("clone") })
9693
- ]);
9694
- var emptyOptions = { canClone: false, forkMessages: [] };
9695
- var sessionHeader = object({
9696
- type: literal("session"),
9697
- id: string2().max(200).regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/),
9698
- version: literal(3),
9699
- cwd: string2().min(1),
9700
- timestamp: string2().min(1)
9701
- });
9702
- var sessionEntry = object({
9703
- type: string2().min(1),
9704
- id: entryKey,
9705
- parentId: entryKey.nullable()
9706
- });
9707
- var invalidSource = () => new WebError(409, "branch_source_invalid", "\u4F1A\u8BDD\u8BB0\u5F55\u65E0\u6548\uFF0C\u65E0\u6CD5\u521B\u5EFA\u5206\u652F\u3002");
9708
- var invalidOutput = () => new WebError(502, "branch_output_invalid", "OmO \u6CA1\u6709\u751F\u6210\u53EF\u786E\u8BA4\u7684\u72EC\u7ACB\u5206\u652F\u3002");
9709
- var staleBranch = () => new WebError(409, "branch_stale", "\u4F1A\u8BDD\u6216\u5206\u652F\u8D77\u70B9\u5DF2\u6539\u53D8\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002");
9710
- var branchBusy = () => new WebError(409, "session_busy", "\u4F1A\u8BDD\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u5408\u7ED3\u675F\u540E\u518D\u521B\u5EFA\u5206\u652F\u3002");
9711
- var nativeBranchError = (error) => {
9712
- if (!(error instanceof WebError))
9713
- throw error;
9714
- throw new WebError(error.status, error.status >= 500 ? "branch_engine_unavailable" : "branch_engine_refused", "OmO \u672A\u80FD\u5B8C\u6210\u5206\u652F\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD\u5E76\u91CD\u8BD5\u3002");
9697
+ var runId = templateLiteral(["dag_", uuidv4()]);
9698
+ var dagStatus = _enum(["pending", "running", "paused", "completed", "failed", "cancelled"]);
9699
+ var statusesByScope = {
9700
+ current: [dagStatus.enum.pending, dagStatus.enum.running, dagStatus.enum.paused],
9701
+ history: [dagStatus.enum.completed, dagStatus.enum.failed, dagStatus.enum.cancelled]
9715
9702
  };
9716
- async function readBranchLeaf(scope, invalidLeaf) {
9717
- if (scope.engine.capabilities.has("entries_tail")) {
9718
- try {
9719
- return await readNativeLeaf(scope, 15000);
9703
+ var dagStatuses = (scope) => statusesByScope[scope];
9704
+ var nodeState = _enum(["pending", "blocked", "scheduled", "running", "paused", "completed", "failed", "cancelled", "skipped"]);
9705
+ var optionalCount = count2.optional().catch(undefined);
9706
+ var dagRow = object({
9707
+ runId: runId.optional().catch(undefined),
9708
+ name: title,
9709
+ parentSessionId: identity,
9710
+ status: dagStatus,
9711
+ createdAt: timestamp2,
9712
+ updatedAt: timestamp2,
9713
+ counts: object({
9714
+ total: count2,
9715
+ pending: optionalCount,
9716
+ blocked: optionalCount,
9717
+ scheduled: optionalCount,
9718
+ running: optionalCount,
9719
+ paused: optionalCount,
9720
+ completed: optionalCount,
9721
+ failed: optionalCount,
9722
+ cancelled: optionalCount,
9723
+ skipped: optionalCount
9724
+ })
9725
+ });
9726
+ var dagReply = object({
9727
+ ok: literal(true),
9728
+ value: object({
9729
+ limit: literal(RUNTIME_LIST_LIMIT),
9730
+ runs: boundedRows(dagRow)
9731
+ })
9732
+ });
9733
+ function projectDagRow(row, keyForRun) {
9734
+ const { total, ...counts } = row.counts;
9735
+ const entries = Object.entries(counts).filter(([, value]) => value !== undefined && value <= total);
9736
+ return {
9737
+ status: row.status,
9738
+ name: row.name,
9739
+ createdAt: row.createdAt,
9740
+ updatedAt: row.updatedAt,
9741
+ nodeCount: total,
9742
+ ...entries.length === 0 ? {} : { counts: Object.fromEntries(entries) },
9743
+ ...row.runId === undefined ? {} : { key: keyForRun(row.runId) }
9744
+ };
9745
+ }
9746
+ var MAX_NODES = 64;
9747
+ var MAX_EDGES = MAX_NODES * (MAX_NODES - 1) / 2;
9748
+ var MAX_SNAPSHOT_BYTES = 1024 * 1024;
9749
+ var routeMetadata = discriminatedUnion("kind", [
9750
+ object({ kind: literal("agent"), agent: agent.optional().catch(undefined), model: configuredModel }),
9751
+ object({ kind: literal("category"), category: category.optional().catch(undefined) })
9752
+ ]).transform((route) => {
9753
+ switch (route.kind) {
9754
+ case "agent":
9755
+ return { agent: route.agent, configuredModel: route.model };
9756
+ case "category":
9757
+ return { category: route.category };
9758
+ }
9759
+ }).optional().catch(undefined);
9760
+ var executionTimes = { createdAt: optionalTime, startedAt: optionalTime, completedAt: optionalTime };
9761
+ var snapshot = object({ ok: literal(true), value: object({
9762
+ schemaVersion: literal(1),
9763
+ runId,
9764
+ parentSessionId: identity,
9765
+ status: dagStatus,
9766
+ name: title,
9767
+ ...executionTimes,
9768
+ counts: object({ total: count2 }),
9769
+ nodes: boundedRows(object({
9770
+ id: identity,
9771
+ state: nodeState,
9772
+ attempt: count2,
9773
+ label: title,
9774
+ taskId,
9775
+ ...executionTimes,
9776
+ lastActivityAt: optionalTime,
9777
+ dependsOn: boundedRows(identity, MAX_NODES - 1),
9778
+ route: routeMetadata
9779
+ }), MAX_NODES),
9780
+ edges: boundedRows(object({ from: identity, to: identity }), MAX_EDGES),
9781
+ waves: boundedRows(object({ index: count2, nodeIds: boundedRows(identity, MAX_NODES) }), MAX_NODES)
9782
+ }) });
9783
+ function projectDagSnapshot(raw, expected) {
9784
+ if (raw.ok === false) {
9785
+ const error = object({ code: string2() }).safeParse(raw.error);
9786
+ if (!error.success)
9787
+ return malformed2;
9788
+ switch (error.data.code) {
9789
+ case "run_not_found":
9790
+ case "run_not_owned":
9791
+ return notFound2;
9792
+ case "history_unavailable":
9793
+ return { status: "unavailable", reason: "native_unavailable" };
9794
+ default:
9795
+ return malformed2;
9796
+ }
9797
+ }
9798
+ try {
9799
+ if (Buffer.byteLength(JSON.stringify(raw)) > MAX_SNAPSHOT_BYTES)
9800
+ return malformed2;
9801
+ } catch (error) {
9802
+ if (error instanceof RangeError)
9803
+ return malformed2;
9804
+ throw error;
9805
+ }
9806
+ const parsed = snapshot.safeParse(raw);
9807
+ if (!parsed.success)
9808
+ return malformed2;
9809
+ const graph = parsed.data.value;
9810
+ if (graph.runId !== expected.runId || graph.parentSessionId !== expected.owner)
9811
+ return ownershipChanged;
9812
+ if (!dagStatuses(expected.scope).includes(graph.status))
9813
+ return notFound2;
9814
+ if (!graph.nodes.length || graph.nodes.length !== graph.counts.total || graph.waves.length > graph.nodes.length)
9815
+ return malformed2;
9816
+ const nativeNodes = new Map(graph.nodes.map((node) => [node.id, node]));
9817
+ if (nativeNodes.size !== graph.nodes.length)
9818
+ return malformed2;
9819
+ const local = new Map;
9820
+ const waves = [];
9821
+ for (const [index, wave] of graph.waves.entries()) {
9822
+ if (wave.index !== index || wave.nodeIds.length === 0)
9823
+ return malformed2;
9824
+ const nodes = [];
9825
+ for (const nativeId of wave.nodeIds) {
9826
+ if (!nativeNodes.has(nativeId) || local.has(nativeId))
9827
+ return malformed2;
9828
+ nodes.push(local.size);
9829
+ local.set(nativeId, { id: local.size, wave: index, upstream: new Set });
9830
+ }
9831
+ waves.push({ index, nodes });
9832
+ }
9833
+ if (local.size !== nativeNodes.size)
9834
+ return malformed2;
9835
+ const addEdge = (from, to) => {
9836
+ const upstream = local.get(from);
9837
+ const downstream = local.get(to);
9838
+ if (!upstream || !downstream || upstream.wave >= downstream.wave)
9839
+ return false;
9840
+ downstream.upstream.add(upstream.id);
9841
+ return true;
9842
+ };
9843
+ for (const { from, to } of graph.edges)
9844
+ if (!addEdge(from, to))
9845
+ return malformed2;
9846
+ for (const node of graph.nodes)
9847
+ for (const from of node.dependsOn)
9848
+ if (!addEdge(from, node.id))
9849
+ return malformed2;
9850
+ const nodes = [];
9851
+ for (const [nativeId, position] of local) {
9852
+ const node = nativeNodes.get(nativeId);
9853
+ if (!node)
9854
+ return malformed2;
9855
+ nodes.push({
9856
+ id: position.id,
9857
+ state: node.state,
9858
+ attempt: node.attempt,
9859
+ upstream: [...position.upstream].sort((a, b) => a - b),
9860
+ label: node.label,
9861
+ createdAt: node.createdAt,
9862
+ startedAt: node.startedAt,
9863
+ completedAt: node.completedAt,
9864
+ lastActivityAt: node.lastActivityAt,
9865
+ ...node.route,
9866
+ taskKey: node.taskId === undefined ? undefined : expected.taskKey(node.taskId)
9867
+ });
9868
+ }
9869
+ return {
9870
+ status: "ok",
9871
+ runStatus: graph.status,
9872
+ name: graph.name,
9873
+ createdAt: graph.createdAt,
9874
+ startedAt: graph.startedAt,
9875
+ completedAt: graph.completedAt,
9876
+ waves,
9877
+ nodes
9878
+ };
9879
+ }
9880
+
9881
+ // src/native-runtime-task-output.ts
9882
+ var TASK_OUTPUT_PAGE_BYTES = 8192;
9883
+ var taskOutputCursor = string2().regex(/^(?:0|[1-9]\d{0,3})\.[a-f0-9]{64}$/u);
9884
+ var nativeText = string2().max(32000);
9885
+ var snapshot2 = object({
9886
+ task_id: identity,
9887
+ parent_session_id: identity,
9888
+ status: taskStatus,
9889
+ effective_model: effectiveModel,
9890
+ final_response: nativeText.optional(),
9891
+ final_response_truncated: boolean2().optional()
9892
+ });
9893
+ var reply = discriminatedUnion("kind", [
9894
+ object({
9895
+ kind: literal("transcript"),
9896
+ mode: _enum(["full", "tail"]),
9897
+ source: _enum(["event-log", "session-jsonl", "none"]),
9898
+ transcript: nativeText,
9899
+ truncated: boolean2(),
9900
+ snapshot: snapshot2
9901
+ }),
9902
+ object({ kind: literal("status"), snapshot: snapshot2.extend({ status: literal("lost") }) })
9903
+ ]);
9904
+ var tools = new Set([
9905
+ "read",
9906
+ "write",
9907
+ "edit",
9908
+ "bash",
9909
+ "grep",
9910
+ "find",
9911
+ "glob",
9912
+ "ls",
9913
+ "apply_patch",
9914
+ "todo",
9915
+ "web_search",
9916
+ "webfetch",
9917
+ "task",
9918
+ "task_output",
9919
+ "ask_user",
9920
+ "request_user_input",
9921
+ "ctx_execute",
9922
+ "ctx_search",
9923
+ "eval"
9924
+ ]);
9925
+ var structure = /[<>]|^\s*(?:```|~~~|[{[]|(?:system|developer|user|thinking|tool(?:_result)?|error):)|\b(?:BEGIN [A-Z ]*PRIVATE KEY|(?:authorization|bearer|api[_ -]?key|password|(?:access[_ -]?)?token|secret)\s*[:=])|\b(?:Bearer\s+[\w.-]+|(?:sk-(?:proj-)?|gh[pousr]_|github_pat_|AKIA)[\w-]{12,})|(?:^|[\s"'`(=])(?:~?\/(?!\s|$)|[a-z]:[\\/]|\\\\|local:\/\/)/iu;
9926
+ var clean = (value) => stripVTControlCharacters3(value).replace(/[\p{Cf}\p{Cs}]|[^\S\r\n ]/gu, "").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/gu, "");
9927
+ function projectTaskOutput(raw, expected) {
9928
+ if (raw.kind === "not_found")
9929
+ return { status: "ownership_changed" };
9930
+ if (raw.kind === "unavailable")
9931
+ return { status: "unavailable", reason: "native_unavailable" };
9932
+ const parsed = reply.safeParse(raw);
9933
+ if (!parsed.success)
9934
+ return { status: "malformed" };
9935
+ const data = parsed.data;
9936
+ const { task_id, parent_session_id, status, final_response, final_response_truncated, effective_model } = data.snapshot;
9937
+ if (task_id !== expected.taskId || parent_session_id !== expected.parent)
9938
+ return { status: "ownership_changed" };
9939
+ if (data.kind === "transcript" && data.mode !== expected.mode)
9940
+ return { status: "malformed" };
9941
+ const records = [];
9942
+ let filtered = false;
9943
+ const add = (kind, source) => {
9944
+ const text = clean(source).trim();
9945
+ if (!text)
9946
+ return;
9947
+ if (structure.test(text) || /\[team message\b/u.test(text)) {
9948
+ filtered = true;
9949
+ return;
9950
+ }
9951
+ const chars = Array.from(text);
9952
+ const rows = [];
9953
+ for (let start = 0;start < chars.length; start += 240) {
9954
+ rows.push({ kind, text: chars.slice(start, start + 240).join("") });
9955
+ }
9956
+ records.push(rows);
9957
+ };
9958
+ if (final_response && expected.mode === "full") {
9959
+ const lines = clean(final_response).split(/\r\n?|\n/u);
9960
+ const unsafe = lines.findIndex((line) => structure.test(line) || /\[team message\b/u.test(line));
9961
+ filtered = unsafe !== -1;
9962
+ add("final", lines.slice(0, unsafe === -1 ? undefined : unsafe).join(`
9963
+ `));
9964
+ }
9965
+ if (data.kind === "transcript" && data.source !== "none") {
9966
+ let rendered = clean(data.transcript);
9967
+ const elision = /\r?\n\.\.\.\[elided \d+ chars\]\.\.\.\r?\n/u.exec(rendered);
9968
+ if (elision)
9969
+ rendered = rendered.slice(0, Math.max(0, rendered.lastIndexOf(`
9970
+ `, elision.index - 1)));
9971
+ if (elision)
9972
+ filtered = true;
9973
+ let assistant;
9974
+ const flush = () => {
9975
+ if (assistant)
9976
+ add("assistant", assistant.join(`
9977
+ `));
9978
+ assistant = undefined;
9979
+ };
9980
+ for (const line of rendered.split(/\r\n?|\n/u)) {
9981
+ if (/^(?:error:|assistant: \[team message\b)/u.test(line)) {
9982
+ filtered = true;
9983
+ break;
9984
+ }
9985
+ if (line.startsWith("assistant: ")) {
9986
+ flush();
9987
+ const text = line.slice("assistant: ".length);
9988
+ if (structure.test(text)) {
9989
+ filtered = true;
9990
+ break;
9991
+ }
9992
+ assistant = [text];
9993
+ continue;
9994
+ }
9995
+ const tool = data.source === "event-log" ? /^tool(?:\[error\])?: ([a-z][a-z\d_.-]{0,63})$/iu.exec(line)?.[1] : undefined;
9996
+ if (tool) {
9997
+ flush();
9998
+ if (tools.has(tool))
9999
+ add("tool", tool);
10000
+ else
10001
+ filtered = true;
10002
+ } else {
10003
+ if (structure.test(line) || /\[team message\b/u.test(line)) {
10004
+ filtered = true;
10005
+ break;
10006
+ }
10007
+ if (assistant)
10008
+ assistant.push(line);
10009
+ else if (line.trim() && line !== "(no transcript recorded for this task)")
10010
+ filtered = true;
10011
+ }
10012
+ }
10013
+ flush();
10014
+ }
10015
+ const hostTruncated = final_response_truncated === true || data.kind === "transcript" && data.truncated;
10016
+ return {
10017
+ status: "ok",
10018
+ taskStatus: status,
10019
+ effectiveModel: effective_model,
10020
+ hostTruncated,
10021
+ filtered,
10022
+ coverage: expected.mode === "tail" ? "recent" : "full",
10023
+ rows: (expected.mode === "tail" ? records.reverse() : records).flat()
10024
+ };
10025
+ }
10026
+ var windows = new Map;
10027
+ function rememberTaskOutput(key, data) {
10028
+ windows.delete(key);
10029
+ if (windows.size >= 32) {
10030
+ const oldest = windows.keys().next().value;
10031
+ if (oldest !== undefined)
10032
+ windows.delete(oldest);
10033
+ }
10034
+ const revision = createHash2("sha256").update(JSON.stringify(data)).digest("hex");
10035
+ windows.set(key, { data, revision, expires: Date.now() + 5 * 60000 });
10036
+ }
10037
+ function taskOutputPage(key, page) {
10038
+ const window = windows.get(key);
10039
+ if (!window || window.expires < Date.now()) {
10040
+ windows.delete(key);
10041
+ return { status: "stale" };
10042
+ }
10043
+ const { data, revision } = window;
10044
+ const { rows } = data;
10045
+ const offset = page.cursor ? Number(page.cursor.split(".", 1)[0]) : 0;
10046
+ const cursor = (index) => `${index}.${page.sign(index, revision)}`;
10047
+ const size = 6;
10048
+ if (page.cursor && (offset >= rows.length || offset % size !== 0 || page.cursor !== cursor(offset))) {
10049
+ return { status: "stale" };
10050
+ }
10051
+ return {
10052
+ ...data,
10053
+ rows: rows.slice(offset, offset + size),
10054
+ previous: offset >= size ? cursor(offset - size) : undefined,
10055
+ next: offset + size < rows.length ? cursor(offset + size) : undefined
10056
+ };
10057
+ }
10058
+
10059
+ // src/session-branches.ts
10060
+ import { constants as constants5 } from "fs";
10061
+ import { lstat as lstat6, mkdtemp as mkdtemp2, open as open6, realpath as realpath6, rm as rm2, writeFile } from "fs/promises";
10062
+ import { basename as basename2, dirname as dirname3, join as join5, resolve as resolve4 } from "path";
10063
+
10064
+ // src/session-entry-pages.ts
10065
+ import { randomBytes as randomBytes2 } from "crypto";
10066
+ var PAGE_TAIL = 40;
10067
+ var PAGE_BYTES = 262144;
10068
+ var PAGE_TIMEOUT = 6000;
10069
+ var MAX_CURSORS = 128;
10070
+ var MAX_CURSOR_IDS = 32768;
10071
+ var CURSOR_TTL = 10 * 60000;
10072
+ var treeCursor = string2().regex(/^[a-f0-9]{64}$/u);
10073
+ var staleTree = () => new WebError(409, "tree_stale", "\u4F1A\u8BDD\u6216\u5206\u652F\u4F4D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u52A0\u8F7D\u4F1A\u8BDD\u6811\u3002");
10074
+ var malformedPage = () => new WebError(502, "tree_reply_invalid", "OmO \u8FD4\u56DE\u4E86\u65E0\u6548\u7684\u4F1A\u8BDD\u5206\u9875\u3002");
10075
+ var pageTooLarge = () => new WebError(409, "tree_budget", "\u4F1A\u8BDD\u5386\u53F2\u8D85\u8FC7\u8BFB\u53D6\u9884\u7B97\u3002");
10076
+ var envelope = object({
10077
+ entries: unknown(),
10078
+ leafId: entryId.nullable(),
10079
+ hasMore: boolean2(),
10080
+ next_before: entryId.optional()
10081
+ });
10082
+ var entryShape = object({ id: entryId, parentId: entryId.nullable(), type: string2().min(1).max(80) });
10083
+ async function readNativeLeaf(scope, timeout = PAGE_TIMEOUT) {
10084
+ return (await readEntryPage(scope, { leafOnly: true, timeout })).leafId;
10085
+ }
10086
+ async function readEntryPage(scope, options = {}) {
10087
+ if (!scope.isCurrent())
10088
+ throw staleTree();
10089
+ const { position } = options;
10090
+ const tail = options.leafOnly ? 1 : PAGE_TAIL;
10091
+ const raw = await scope.engine.requestExisting("get_entries", {
10092
+ sessionId: scope.target.route,
10093
+ tail,
10094
+ maxBytes: PAGE_BYTES,
10095
+ ...position ? { before: position.before } : {}
10096
+ }, options.timeout ?? PAGE_TIMEOUT);
10097
+ if (!scope.isCurrent())
10098
+ throw staleTree();
10099
+ const parsed = envelope.safeParse(raw);
10100
+ if (!parsed.success)
10101
+ throw malformedPage();
10102
+ const { entries, leafId, hasMore, next_before: nextBefore } = parsed.data;
10103
+ if (options.expectedLeafId !== undefined && options.expectedLeafId !== leafId)
10104
+ throw staleTree();
10105
+ if (!Array.isArray(entries) || entries.length > tail || raw.nextSince !== undefined || entries.length === 0 && (position !== undefined || hasMore || leafId !== null))
10106
+ throw malformedPage();
10107
+ const seen = new Set(position?.seen);
10108
+ const page = [];
10109
+ let bytes = 0;
10110
+ for (const value of entries) {
10111
+ const fields = entryShape.safeParse(value);
10112
+ if (!fields.success)
10113
+ throw malformedPage();
10114
+ const { id, parentId } = fields.data;
10115
+ if (id === parentId || id === position?.before || seen.has(id))
10116
+ throw malformedPage();
10117
+ seen.add(id);
10118
+ page.push({ ...fields.data, raw: record2(value) });
10119
+ if (entries.length === 1 && (options.acceptLargeSingleton || options.leafOnly))
10120
+ continue;
10121
+ try {
10122
+ bytes += Buffer.byteLength(JSON.stringify(value), "utf8") + 1;
10123
+ } catch (error) {
10124
+ if (!(error instanceof RangeError))
10125
+ throw error;
10126
+ throw pageTooLarge();
10127
+ }
10128
+ if (bytes > PAGE_BYTES)
10129
+ throw entries.length === 1 ? pageTooLarge() : malformedPage();
10130
+ }
10131
+ if (hasMore ? nextBefore === undefined || nextBefore !== page[0]?.id : nextBefore !== undefined || leafId !== null && !seen.has(leafId))
10132
+ throw malformedPage();
10133
+ return { entries: page, leafId, ...nextBefore === undefined ? {} : { next: { before: nextBefore, seen } } };
10134
+ }
10135
+ var displayTypes = new Set([
10136
+ "message",
10137
+ "custom",
10138
+ "custom_message",
10139
+ "compaction",
10140
+ "branch_summary",
10141
+ "model_change",
10142
+ "thinking_level_change",
10143
+ "session_info",
10144
+ "label"
10145
+ ]);
10146
+ var displayRoles = new Set(["user", "assistant", "toolResult", "bashExecution"]);
10147
+ function previewEntries(entries) {
10148
+ return entries.map(({ id, parentId, type, raw }) => {
10149
+ const { role } = record2(raw.message);
10150
+ return {
10151
+ id,
10152
+ parentId,
10153
+ type: displayTypes.has(type) ? type : "other",
10154
+ ...type === "message" && typeof role === "string" && displayRoles.has(role) ? { role } : {}
10155
+ };
10156
+ });
10157
+ }
10158
+
10159
+ class TreeCursors {
10160
+ #cursors = new Map;
10161
+ #ids = 0;
10162
+ get(scope, key) {
10163
+ const cursor = this.#cursors.get(key);
10164
+ if (!cursor || cursor.expires <= Date.now() || cursor.target !== scope.target || cursor.host !== scope.engine.status)
10165
+ throw staleTree();
10166
+ this.#cursors.delete(key);
10167
+ this.#cursors.set(key, cursor);
10168
+ return cursor;
10169
+ }
10170
+ put(scope, leafId, position) {
10171
+ const count = position.seen.size;
10172
+ if (count > MAX_CURSOR_IDS)
10173
+ throw pageTooLarge();
10174
+ for (const [key, cursor] of this.#cursors) {
10175
+ if (this.#cursors.size < MAX_CURSORS && this.#ids + count <= MAX_CURSOR_IDS)
10176
+ break;
10177
+ this.#delete(key, cursor);
10178
+ }
10179
+ const key = randomBytes2(32).toString("hex");
10180
+ this.#cursors.set(key, {
10181
+ target: scope.target,
10182
+ host: scope.engine.status,
10183
+ leafId,
10184
+ position,
10185
+ expires: Date.now() + CURSOR_TTL
10186
+ });
10187
+ this.#ids += count;
10188
+ return key;
10189
+ }
10190
+ invalidate(target) {
10191
+ for (const [key, cursor] of this.#cursors)
10192
+ if (cursor.target === target)
10193
+ this.#delete(key, cursor);
10194
+ }
10195
+ #delete(key, cursor) {
10196
+ this.#cursors.delete(key);
10197
+ this.#ids -= cursor.position.seen.size;
10198
+ }
10199
+ }
10200
+
10201
+ // src/session-branches.ts
10202
+ var entryKey = string2().min(1).max(200).regex(/^[a-zA-Z0-9_-]+$/);
10203
+ var branchSelection = discriminatedUnion("kind", [
10204
+ strictObject({ kind: literal("fork"), entryId: entryKey }),
10205
+ strictObject({ kind: literal("clone") })
10206
+ ]);
10207
+ var emptyOptions = { canClone: false, forkMessages: [] };
10208
+ var sessionHeader = object({
10209
+ type: literal("session"),
10210
+ id: string2().max(200).regex(/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/),
10211
+ version: literal(3),
10212
+ cwd: string2().min(1),
10213
+ timestamp: string2().min(1)
10214
+ });
10215
+ var sessionEntry = object({
10216
+ type: string2().min(1),
10217
+ id: entryKey,
10218
+ parentId: entryKey.nullable()
10219
+ });
10220
+ var invalidSource = () => new WebError(409, "branch_source_invalid", "\u4F1A\u8BDD\u8BB0\u5F55\u65E0\u6548\uFF0C\u65E0\u6CD5\u521B\u5EFA\u5206\u652F\u3002");
10221
+ var invalidOutput = () => new WebError(502, "branch_output_invalid", "OmO \u6CA1\u6709\u751F\u6210\u53EF\u786E\u8BA4\u7684\u72EC\u7ACB\u5206\u652F\u3002");
10222
+ var staleBranch = () => new WebError(409, "branch_stale", "\u4F1A\u8BDD\u6216\u5206\u652F\u8D77\u70B9\u5DF2\u6539\u53D8\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002");
10223
+ var branchBusy = () => new WebError(409, "session_busy", "\u4F1A\u8BDD\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u5408\u7ED3\u675F\u540E\u518D\u521B\u5EFA\u5206\u652F\u3002");
10224
+ var nativeBranchError = (error) => {
10225
+ if (!(error instanceof WebError))
10226
+ throw error;
10227
+ throw new WebError(error.status, error.status >= 500 ? "branch_engine_unavailable" : "branch_engine_refused", "OmO \u672A\u80FD\u5B8C\u6210\u5206\u652F\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u4F1A\u8BDD\u5E76\u91CD\u8BD5\u3002");
10228
+ };
10229
+ async function readBranchLeaf(scope, invalidLeaf) {
10230
+ if (scope.engine.capabilities.has("entries_tail")) {
10231
+ try {
10232
+ return await readNativeLeaf(scope, 15000);
9720
10233
  } catch (error) {
9721
10234
  if (error instanceof WebError) {
9722
10235
  if (error.code === "tree_stale")
@@ -9979,24 +10492,33 @@ import { link, lstat as lstat7, mkdir, readFile as readFile2, readdir as readdir
9979
10492
  import { dirname as dirname4, join as join7, resolve as resolve5 } from "path";
9980
10493
 
9981
10494
  // src/command-ownership.ts
9982
- var terminalOnlyCommands = [
9983
- "scoped-models",
9984
- "favorite-models",
9985
- "task-kill",
9986
- "login",
9987
- "logout",
9988
- "trust",
9989
- "export",
9990
- "import",
9991
- "share",
9992
- "reload",
9993
- "keybindings",
9994
- "changelog",
9995
- "quit",
9996
- "exit",
9997
- "bug",
9998
- "debug"
9999
- ];
10495
+ var terminalCommandGroups = {
10496
+ account: ["login", "logout", "account", "gpt-account", "claude-account", "cursor-account"],
10497
+ settings: ["scoped-models", "favorite-models", "trust", "reload", "keybindings", "fallback", "lookat", "nested-agents", "reload-rules"],
10498
+ terminal: ["tui", "hooks", "websearch", "ttsr", "changelog", "files", "diff", "quit", "exit", "debug", "answer"],
10499
+ history: ["history", "search"],
10500
+ transfer: ["export", "import", "share", "ir", "remote"],
10501
+ task: ["task-kill"],
10502
+ memory: [
10503
+ "palace",
10504
+ "memory",
10505
+ "memfs",
10506
+ "remember",
10507
+ "init",
10508
+ "doctor",
10509
+ "recompile",
10510
+ "memory-repository",
10511
+ "sleeptime",
10512
+ "reflect",
10513
+ "dream",
10514
+ "people",
10515
+ "facts",
10516
+ "agreements"
10517
+ ],
10518
+ runtime: ["mcp", "computer", "goal", "loop", "handoff", "btw"],
10519
+ support: ["bug", "feedback"]
10520
+ };
10521
+ var terminalOnlyCommands = Object.values(terminalCommandGroups).flat();
10000
10522
  var dedicatedCommands = [
10001
10523
  "dag",
10002
10524
  "tasks",
@@ -10005,7 +10527,10 @@ var dedicatedCommands = [
10005
10527
  "efforts",
10006
10528
  "compact",
10007
10529
  "settings",
10008
- "setting"
10530
+ "setting",
10531
+ "rules",
10532
+ "help",
10533
+ "fast"
10009
10534
  ];
10010
10535
 
10011
10536
  // src/commands.ts
@@ -10033,337 +10558,51 @@ function invocationFor(name, source) {
10033
10558
  return `/${name}`;
10034
10559
  }
10035
10560
  function projectCommands(value) {
10036
- return array2(value).flatMap((entry) => {
10037
- const raw = record2(entry);
10038
- const name = str(raw.name);
10039
- const source = raw.source;
10040
- if (!name || !isCommandSource(source))
10041
- return [];
10042
- const invocation = invocationFor(name, source);
10043
- if (!invocation)
10044
- return [];
10045
- return [{ name, description: str(raw.description), source, invocation }];
10046
- });
10047
- }
10048
- function legacySkillInvocation(name) {
10049
- if (!SKILL_NAME.test(name))
10050
- return;
10051
- return `/${name}`;
10052
- }
10053
- function resolveCommand(commands, invocation) {
10054
- const direct = commands.find((command) => command.invocation === invocation);
10055
- if (direct)
10056
- return direct;
10057
- if (invocation.startsWith("/skill:")) {
10058
- return commands.find((command) => command.source === "skill" && legacySkillInvocation(command.name) === invocation);
10059
- }
10060
- return;
10061
- }
10062
- var MAX_ARGUMENTS = 2000;
10063
- var CONTROL_CHARS = /[\0-\x1f\x7f]/;
10064
- function composeMessage(command, args) {
10065
- const invocation = command.invocation;
10066
- if (!invocation || CONTROL_CHARS.test(invocation) || !/^[//$]/.test(invocation)) {
10067
- throw new WebError(400, "invalid_command", "\u8BE5\u547D\u4EE4\u7684\u8C03\u7528\u5F62\u5F0F\u4E0D\u53EF\u7528\u3002");
10068
- }
10069
- if (args === undefined)
10070
- return invocation;
10071
- if (args.length > MAX_ARGUMENTS || CONTROL_CHARS.test(args)) {
10072
- throw new WebError(400, "invalid_arguments", "\u547D\u4EE4\u53C2\u6570\u53EA\u80FD\u662F\u5355\u884C\u6587\u672C\uFF0C\u4E14\u4E0D\u80FD\u8FC7\u957F\u3002");
10073
- }
10074
- const trimmed = args.trim();
10075
- return trimmed ? `${invocation} ${trimmed}` : invocation;
10076
- }
10077
-
10078
- // src/native-runtime.ts
10079
- import { createHmac as createHmac2, randomBytes as randomBytes3 } from "crypto";
10080
-
10081
- // src/native-runtime-projection.ts
10082
- import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
10083
- var identity = string2().min(1).max(256).regex(/\S/u);
10084
- var count2 = int().nonnegative();
10085
- var timestamp2 = exports_iso.datetime().transform(Date.parse).pipe(int());
10086
- var RUNTIME_LIST_LIMIT = 256;
10087
- var boundedRows = (row, limit = RUNTIME_LIST_LIMIT) => preprocess((value) => Array.isArray(value) && value.length <= limit ? value : undefined, array(row));
10088
- var malformed2 = { status: "malformed" };
10089
- var ownershipChanged = { status: "ownership_changed" };
10090
- var notFound2 = { status: "not_found" };
10091
- var displayText2 = (maxBytes) => string2().max(maxBytes * 2).transform((value) => stripVTControlCharacters2(value).replace(/\s+/gu, " ").replace(/[\p{Cc}\p{Cf}\p{Cs}]/gu, "").trim()).refine((value) => value.length > 0 && Buffer.byteLength(value) <= maxBytes && !/[<>]|(?:^|[\s"'`(=])(?:~?\/(?!\s|$)|[a-z]:[\\/]|\\\\)/iu.test(value)).optional().catch(undefined);
10092
- var title = displayText2(128);
10093
- var description = displayText2(320);
10094
- var model2 = string2().max(128).regex(/^(?![a-z]:\/)[a-z\d][a-z\d._:@+-]*(?:\/[a-z\d][a-z\d._:@+-]*)*$/iu);
10095
- var configuredModel = model2.optional().catch(undefined);
10096
- var effectiveModel = object({
10097
- provider: string2().max(48).regex(/^[a-z\d][a-z\d._-]*$/iu),
10098
- model_id: model2,
10099
- reasoning: string2().max(32).regex(/^[a-z\d][a-z\d_-]*$/iu).optional().catch(undefined)
10100
- }).transform(({ provider, model_id, reasoning }) => ({ provider, modelId: model_id, reasoning })).optional().catch(undefined);
10101
- var optionalTime = timestamp2.optional().catch(undefined);
10102
- var agent = _enum(["explore", "librarian", "delivery-worker", "technical-writing", "quick-scan"]);
10103
- var category = _enum([
10104
- "quick",
10105
- "deep-low",
10106
- "deep-high",
10107
- "writing",
10108
- "visual-engineering",
10109
- "unspecified-low",
10110
- "unspecified-high",
10111
- "architect",
10112
- "artistry",
10113
- "ultrabrain"
10114
- ]);
10115
- var executionMode = _enum(["in-process", "process"]);
10116
- var taskId = string2().regex(/^st_[0-9a-f]{8}$/u).brand().optional().catch(undefined);
10117
- var taskStatus = _enum(["pending", "running", "paused", "completed", "error", "cancelled", "interrupted", "lost"]);
10118
- var taskRow = object({
10119
- task_id: taskId,
10120
- status: taskStatus,
10121
- created_at: timestamp2,
10122
- updated_at: timestamp2,
10123
- agent_type: agent.optional().catch(undefined),
10124
- category: category.optional().catch(undefined),
10125
- execution_mode: executionMode.optional().catch(undefined),
10126
- task_summary: title,
10127
- description,
10128
- model: configuredModel,
10129
- effective_model: effectiveModel,
10130
- description_truncated: boolean2().optional().catch(undefined)
10131
- });
10132
- var taskReply = object({
10133
- parent_session_id: identity,
10134
- tasks: boundedRows(taskRow),
10135
- truncated_tasks: count2.optional()
10136
- });
10137
- function projectTasks(raw, owner) {
10138
- switch (raw.kind) {
10139
- case "unavailable":
10140
- return { status: "unavailable", reason: "native_unavailable" };
10141
- case "not_found":
10142
- return ownershipChanged;
10143
- case undefined:
10144
- break;
10145
- default:
10146
- return malformed2;
10147
- }
10148
- const parsed = taskReply.safeParse(raw);
10149
- if (!parsed.success)
10150
- return malformed2;
10151
- const { parent_session_id, tasks, truncated_tasks = 0 } = parsed.data;
10152
- if (parent_session_id !== owner.sessionId)
10153
- return ownershipChanged;
10154
- if (truncated_tasks > 0 && tasks.length !== RUNTIME_LIST_LIMIT)
10155
- return malformed2;
10156
- if (tasks.length === 0)
10157
- return { status: "empty" };
10158
- const keys = new Set;
10159
- const rows = [];
10160
- for (const row of tasks) {
10161
- const key = row.task_id === undefined ? undefined : owner.taskKey(row.task_id);
10162
- if (key !== undefined) {
10163
- if (keys.has(key))
10164
- return malformed2;
10165
- keys.add(key);
10166
- }
10167
- rows.push({
10168
- key,
10169
- status: row.status,
10170
- createdAt: row.created_at,
10171
- updatedAt: row.updated_at,
10172
- agent: row.agent_type,
10173
- category: row.category,
10174
- executionMode: row.execution_mode,
10175
- title: row.task_summary,
10176
- description: row.description_truncated === true ? undefined : row.description,
10177
- configuredModel: row.model,
10178
- effectiveModel: row.effective_model
10179
- });
10180
- }
10181
- return { status: "ok", rows, omittedCount: truncated_tasks };
10182
- }
10183
- var runId = templateLiteral(["dag_", uuidv4()]);
10184
- var dagStatus = _enum(["pending", "running", "paused", "completed", "failed", "cancelled"]);
10185
- var statusesByScope = {
10186
- current: [dagStatus.enum.pending, dagStatus.enum.running, dagStatus.enum.paused],
10187
- history: [dagStatus.enum.completed, dagStatus.enum.failed, dagStatus.enum.cancelled]
10188
- };
10189
- var dagStatuses = (scope) => statusesByScope[scope];
10190
- var nodeState = _enum(["pending", "blocked", "scheduled", "running", "paused", "completed", "failed", "cancelled", "skipped"]);
10191
- var optionalCount = count2.optional().catch(undefined);
10192
- var dagRow = object({
10193
- runId: runId.optional().catch(undefined),
10194
- name: title,
10195
- parentSessionId: identity,
10196
- status: dagStatus,
10197
- createdAt: timestamp2,
10198
- updatedAt: timestamp2,
10199
- counts: object({
10200
- total: count2,
10201
- pending: optionalCount,
10202
- blocked: optionalCount,
10203
- scheduled: optionalCount,
10204
- running: optionalCount,
10205
- paused: optionalCount,
10206
- completed: optionalCount,
10207
- failed: optionalCount,
10208
- cancelled: optionalCount,
10209
- skipped: optionalCount
10210
- })
10211
- });
10212
- var dagReply = object({
10213
- ok: literal(true),
10214
- value: object({
10215
- limit: literal(RUNTIME_LIST_LIMIT),
10216
- runs: boundedRows(dagRow)
10217
- })
10218
- });
10219
- function projectDagRow(row, keyForRun) {
10220
- const { total, ...counts } = row.counts;
10221
- const entries = Object.entries(counts).filter(([, value]) => value !== undefined && value <= total);
10222
- return {
10223
- status: row.status,
10224
- name: row.name,
10225
- createdAt: row.createdAt,
10226
- updatedAt: row.updatedAt,
10227
- nodeCount: total,
10228
- ...entries.length === 0 ? {} : { counts: Object.fromEntries(entries) },
10229
- ...row.runId === undefined ? {} : { key: keyForRun(row.runId) }
10230
- };
10231
- }
10232
- var MAX_NODES = 64;
10233
- var MAX_EDGES = MAX_NODES * (MAX_NODES - 1) / 2;
10234
- var MAX_SNAPSHOT_BYTES = 1024 * 1024;
10235
- var routeMetadata = discriminatedUnion("kind", [
10236
- object({ kind: literal("agent"), agent: agent.optional().catch(undefined), model: configuredModel }),
10237
- object({ kind: literal("category"), category: category.optional().catch(undefined) })
10238
- ]).transform((route) => {
10239
- switch (route.kind) {
10240
- case "agent":
10241
- return { agent: route.agent, configuredModel: route.model };
10242
- case "category":
10243
- return { category: route.category };
10244
- }
10245
- }).optional().catch(undefined);
10246
- var executionTimes = { createdAt: optionalTime, startedAt: optionalTime, completedAt: optionalTime };
10247
- var snapshot = object({ ok: literal(true), value: object({
10248
- schemaVersion: literal(1),
10249
- runId,
10250
- parentSessionId: identity,
10251
- status: dagStatus,
10252
- name: title,
10253
- ...executionTimes,
10254
- counts: object({ total: count2 }),
10255
- nodes: boundedRows(object({
10256
- id: identity,
10257
- state: nodeState,
10258
- attempt: count2,
10259
- label: title,
10260
- taskId,
10261
- ...executionTimes,
10262
- lastActivityAt: optionalTime,
10263
- dependsOn: boundedRows(identity, MAX_NODES - 1),
10264
- route: routeMetadata
10265
- }), MAX_NODES),
10266
- edges: boundedRows(object({ from: identity, to: identity }), MAX_EDGES),
10267
- waves: boundedRows(object({ index: count2, nodeIds: boundedRows(identity, MAX_NODES) }), MAX_NODES)
10268
- }) });
10269
- function projectDagSnapshot(raw, expected) {
10270
- if (raw.ok === false) {
10271
- const error = object({ code: string2() }).safeParse(raw.error);
10272
- if (!error.success)
10273
- return malformed2;
10274
- switch (error.data.code) {
10275
- case "run_not_found":
10276
- case "run_not_owned":
10277
- return notFound2;
10278
- case "history_unavailable":
10279
- return { status: "unavailable", reason: "native_unavailable" };
10280
- default:
10281
- return malformed2;
10282
- }
10283
- }
10284
- try {
10285
- if (Buffer.byteLength(JSON.stringify(raw)) > MAX_SNAPSHOT_BYTES)
10286
- return malformed2;
10287
- } catch (error) {
10288
- if (error instanceof RangeError)
10289
- return malformed2;
10290
- throw error;
10561
+ return array2(value).flatMap((entry) => {
10562
+ const raw = record2(entry);
10563
+ const name = str(raw.name);
10564
+ const source = raw.source;
10565
+ if (!name || !isCommandSource(source))
10566
+ return [];
10567
+ const invocation = invocationFor(name, source);
10568
+ if (!invocation || reservedCommands.has(invocation))
10569
+ return [];
10570
+ return [{ name, description: str(raw.description), source, invocation }];
10571
+ });
10572
+ }
10573
+ function legacySkillInvocation(name) {
10574
+ if (!SKILL_NAME.test(name))
10575
+ return;
10576
+ return `/${name}`;
10577
+ }
10578
+ function resolveCommand(commands, invocation) {
10579
+ const direct = commands.find((command) => command.invocation === invocation);
10580
+ if (direct)
10581
+ return direct;
10582
+ if (invocation.startsWith("/skill:")) {
10583
+ return commands.find((command) => command.source === "skill" && legacySkillInvocation(command.name) === invocation);
10291
10584
  }
10292
- const parsed = snapshot.safeParse(raw);
10293
- if (!parsed.success)
10294
- return malformed2;
10295
- const graph = parsed.data.value;
10296
- if (graph.runId !== expected.runId || graph.parentSessionId !== expected.owner)
10297
- return ownershipChanged;
10298
- if (!dagStatuses(expected.scope).includes(graph.status))
10299
- return notFound2;
10300
- if (!graph.nodes.length || graph.nodes.length !== graph.counts.total || graph.waves.length > graph.nodes.length)
10301
- return malformed2;
10302
- const nativeNodes = new Map(graph.nodes.map((node) => [node.id, node]));
10303
- if (nativeNodes.size !== graph.nodes.length)
10304
- return malformed2;
10305
- const local = new Map;
10306
- const waves = [];
10307
- for (const [index, wave] of graph.waves.entries()) {
10308
- if (wave.index !== index || wave.nodeIds.length === 0)
10309
- return malformed2;
10310
- const nodes = [];
10311
- for (const nativeId of wave.nodeIds) {
10312
- if (!nativeNodes.has(nativeId) || local.has(nativeId))
10313
- return malformed2;
10314
- nodes.push(local.size);
10315
- local.set(nativeId, { id: local.size, wave: index, upstream: new Set });
10316
- }
10317
- waves.push({ index, nodes });
10585
+ return;
10586
+ }
10587
+ var MAX_ARGUMENTS = 2000;
10588
+ var CONTROL_CHARS = /[\0-\x1f\x7f]/;
10589
+ function composeMessage(command, args) {
10590
+ const invocation = command.invocation;
10591
+ if (!invocation || CONTROL_CHARS.test(invocation) || !/^[//$]/.test(invocation)) {
10592
+ throw new WebError(400, "invalid_command", "\u8BE5\u547D\u4EE4\u7684\u8C03\u7528\u5F62\u5F0F\u4E0D\u53EF\u7528\u3002");
10318
10593
  }
10319
- if (local.size !== nativeNodes.size)
10320
- return malformed2;
10321
- const addEdge = (from, to) => {
10322
- const upstream = local.get(from);
10323
- const downstream = local.get(to);
10324
- if (!upstream || !downstream || upstream.wave >= downstream.wave)
10325
- return false;
10326
- downstream.upstream.add(upstream.id);
10327
- return true;
10328
- };
10329
- for (const { from, to } of graph.edges)
10330
- if (!addEdge(from, to))
10331
- return malformed2;
10332
- for (const node of graph.nodes)
10333
- for (const from of node.dependsOn)
10334
- if (!addEdge(from, node.id))
10335
- return malformed2;
10336
- const nodes = [];
10337
- for (const [nativeId, position] of local) {
10338
- const node = nativeNodes.get(nativeId);
10339
- if (!node)
10340
- return malformed2;
10341
- nodes.push({
10342
- id: position.id,
10343
- state: node.state,
10344
- attempt: node.attempt,
10345
- upstream: [...position.upstream].sort((a, b) => a - b),
10346
- label: node.label,
10347
- createdAt: node.createdAt,
10348
- startedAt: node.startedAt,
10349
- completedAt: node.completedAt,
10350
- lastActivityAt: node.lastActivityAt,
10351
- ...node.route,
10352
- taskKey: node.taskId === undefined ? undefined : expected.taskKey(node.taskId)
10353
- });
10594
+ if (args === undefined)
10595
+ return invocation;
10596
+ if (args.length > MAX_ARGUMENTS || CONTROL_CHARS.test(args)) {
10597
+ throw new WebError(400, "invalid_arguments", "\u547D\u4EE4\u53C2\u6570\u53EA\u80FD\u662F\u5355\u884C\u6587\u672C\uFF0C\u4E14\u4E0D\u80FD\u8FC7\u957F\u3002");
10354
10598
  }
10355
- return {
10356
- status: "ok",
10357
- runStatus: graph.status,
10358
- name: graph.name,
10359
- createdAt: graph.createdAt,
10360
- startedAt: graph.startedAt,
10361
- completedAt: graph.completedAt,
10362
- waves,
10363
- nodes
10364
- };
10599
+ const trimmed = args.trim();
10600
+ return trimmed ? `${invocation} ${trimmed}` : invocation;
10365
10601
  }
10366
10602
 
10603
+ // src/native-runtime.ts
10604
+ import { createHmac as createHmac2, randomBytes as randomBytes3 } from "crypto";
10605
+
10367
10606
  // src/runtime-branch.ts
10368
10607
  var TODO_STATE_TYPE = "senpi.todo-state";
10369
10608
  var NUDGED_TYPE = "omo-kibitzer:nudged";
@@ -10731,6 +10970,7 @@ function bindNativeRuntime(raw, expected) {
10731
10970
  ...state.data,
10732
10971
  route: expected.route,
10733
10972
  dagKey: (runId) => createHmac2("sha256", secret).update(runId).digest("hex"),
10973
+ taskOutputPageKey: (taskKey, offset, revision) => createHmac2("sha256", secret).update(`task-output\x00${taskKey}\x00${offset}\x00`).update(revision).digest("hex"),
10734
10974
  taskKey: (taskId) => createHmac2("sha256", secret).update("task\x00").update(taskId).digest("hex")
10735
10975
  };
10736
10976
  }
@@ -10871,6 +11111,34 @@ async function readNativeDagHistory(scope) {
10871
11111
  return typeof scope === "string" ? unavailable2(scope) : withinBinding(scope, () => readDagSection(scope, "history"));
10872
11112
  }
10873
11113
  var notFound3 = { status: "not_found" };
11114
+ async function readNativeTaskOutput(scope, key, cursor) {
11115
+ if (typeof scope === "string")
11116
+ return unavailable2(scope);
11117
+ const { target } = scope;
11118
+ const result = await withinBinding(scope, async () => {
11119
+ const tasks = await readExtension(scope, { name: "omo.task.list", data: { parent_session_id: target.sessionId } }, (raw) => scopedTasks(raw, target));
11120
+ if ("status" in tasks)
11121
+ return tasks;
11122
+ const task = tasks.byKey.get(key);
11123
+ if (!task)
11124
+ return notFound3;
11125
+ const guard = await sameBinding(scope);
11126
+ if (guard || !scope.isCurrent())
11127
+ return guard ?? ownershipChanged2;
11128
+ if (cursor)
11129
+ return { status: "cached" };
11130
+ const mode = task.status === "pending" || task.status === "running" || task.status === "paused" ? "tail" : "full";
11131
+ const data = { task_id: task.id, mode, ...mode === "tail" ? { tail_lines: 12 } : {} };
11132
+ return readExtension(scope, { name: "omo.task.output", data }, (raw) => projectTaskOutput(raw, { parent: target.sessionId, taskId: task.id, mode }));
11133
+ });
11134
+ if (result.status !== "ok" && result.status !== "cached")
11135
+ return result;
11136
+ if (!scope.isCurrent())
11137
+ return ownershipChanged2;
11138
+ if (result.status === "ok")
11139
+ rememberTaskOutput(key, result);
11140
+ return taskOutputPage(key, { cursor, sign: (offset, revision) => target.taskOutputPageKey(key, offset, revision) });
11141
+ }
10874
11142
  async function readNativeDag(scope, key, selection) {
10875
11143
  if (typeof scope === "string")
10876
11144
  return unavailable2(scope);
@@ -11342,7 +11610,7 @@ class StreamSpeed {
11342
11610
  }
11343
11611
 
11344
11612
  // src/transcript-pages.ts
11345
- import { createHash as createHash2, createHmac as createHmac3, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "crypto";
11613
+ import { createHash as createHash3, createHmac as createHmac3, randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual2 } from "crypto";
11346
11614
  import { closeSync, mkdtempSync, openSync, readSync, rmSync, writeSync } from "fs";
11347
11615
  import { tmpdir } from "os";
11348
11616
  import { join as join6 } from "path";
@@ -11498,6 +11766,10 @@ function webRow(value) {
11498
11766
  for (const key of ["isError", "cancelled", "truncated"])
11499
11767
  if (typeof row[key] !== "boolean")
11500
11768
  delete row[key];
11769
+ if (omitted && row.role === "toolResult") {
11770
+ row.truncated = true;
11771
+ delete row.fileChange;
11772
+ }
11501
11773
  if (row.exitCode !== null && typeof row.exitCode !== "number")
11502
11774
  delete row.exitCode;
11503
11775
  return { row, omitted };
@@ -11518,6 +11790,8 @@ function preview(row) {
11518
11790
  "cancelled",
11519
11791
  "truncated"
11520
11792
  ]);
11793
+ if (row.role === "toolResult")
11794
+ small.truncated = true;
11521
11795
  for (const key of Object.keys(small)) {
11522
11796
  const value = small[key];
11523
11797
  if (typeof value === "string")
@@ -11645,7 +11919,7 @@ class TranscriptCapture {
11645
11919
  this.markOmitted();
11646
11920
  }
11647
11921
  const spans = buffers.map((bytes) => {
11648
- const encoded = Buffer.concat([createHash2("sha256").update(bytes).digest(), bytes]);
11922
+ const encoded = Buffer.concat([createHash3("sha256").update(bytes).digest(), bytes]);
11649
11923
  const span = { offset: this.#head, length: encoded.length };
11650
11924
  if (writeSync(this.#fd, encoded, 0, encoded.length, this.#head % TRANSCRIPT_CAPTURE_BYTES) !== encoded.length) {
11651
11925
  throw captureFailed();
@@ -11686,7 +11960,7 @@ class TranscriptCapture {
11686
11960
  if (readSync(this.#fd, bytes, 0, bytes.length, span.offset % TRANSCRIPT_CAPTURE_BYTES) !== bytes.length)
11687
11961
  throw captureFailed();
11688
11962
  const body = bytes.subarray(DIGEST_BYTES);
11689
- if (!createHash2("sha256").update(body).digest().equals(bytes.subarray(0, DIGEST_BYTES)))
11963
+ if (!createHash3("sha256").update(body).digest().equals(bytes.subarray(0, DIGEST_BYTES)))
11690
11964
  throw captureFailed();
11691
11965
  return JSON.parse(body.toString("utf8"));
11692
11966
  } catch {
@@ -11850,6 +12124,15 @@ var instructionsReply = discriminatedUnion("exists", [
11850
12124
  var shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
11851
12125
  var sessionChanged = () => new WebError(409, "session_changed", "\u4F1A\u8BDD\u8FDE\u63A5\u5DF2\u5207\u6362\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u3002");
11852
12126
  var snapshotAborted = () => new WebError(408, "snapshot_aborted", "\u672C\u6B21\u4F1A\u8BDD\u8BFB\u53D6\u5DF2\u53D6\u6D88\u3002");
12127
+ var releaseInProgress = () => new WebError(409, "handoff_in_progress", "\u4F1A\u8BDD\u5173\u95ED\u6216\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002");
12128
+ var closeState = object({
12129
+ isStreaming: boolean2(),
12130
+ isCompacting: boolean2().optional(),
12131
+ isBashRunning: boolean2().optional(),
12132
+ runPaused: boolean2().optional(),
12133
+ pendingMessageCount: number2().int().nonnegative()
12134
+ });
12135
+ var hasActiveTurn = (current) => current.isStreaming || current.isCompacting || current.isBashRunning || current.runPaused;
11853
12136
 
11854
12137
  class Sessions {
11855
12138
  workspaces;
@@ -11862,6 +12145,8 @@ class Sessions {
11862
12145
  #opening = new Map;
11863
12146
  #writes = new Map;
11864
12147
  #releasing = new Set;
12148
+ #closing = new Map;
12149
+ #actionWrites = new Map;
11865
12150
  #modelWrites = new Set;
11866
12151
  #treeCursors = new TreeCursors;
11867
12152
  #treeWrites = new WeakMap;
@@ -12100,6 +12385,7 @@ class Sessions {
12100
12385
  nativeBranchError(error);
12101
12386
  throw error;
12102
12387
  });
12388
+ const host = this.engine.status;
12103
12389
  const route = result.sessionId;
12104
12390
  if (typeof route !== "string")
12105
12391
  throw new WebError(502, "invalid_engine_reply", "OmO \u6CA1\u6709\u8FD4\u56DE\u4F1A\u8BDD\u53E5\u67C4\u3002");
@@ -12164,6 +12450,8 @@ class Sessions {
12164
12450
  throw error;
12165
12451
  }
12166
12452
  }
12453
+ if (this.engine.status !== host || !host.online)
12454
+ throw sessionChanged();
12167
12455
  const runtime = result.attached === true ? undefined : bindNativeRuntime(initial, {
12168
12456
  route,
12169
12457
  cwd: row.cwd,
@@ -12173,6 +12461,7 @@ class Sessions {
12173
12461
  this.#transcripts.invalidate(row.id);
12174
12462
  this.#live.set(row.id, {
12175
12463
  route,
12464
+ host,
12176
12465
  runtime,
12177
12466
  speed: new StreamSpeed(initial.isCompacting === true),
12178
12467
  running: initial.isStreaming === true
@@ -12193,26 +12482,30 @@ class Sessions {
12193
12482
  return initial;
12194
12483
  }
12195
12484
  async#resume(row) {
12196
- if (this.workspaces instanceof WorkspaceAccess)
12197
- await this.#requireRowWorkspace(row);
12198
- if (this.#live.has(row.id))
12199
- return;
12200
12485
  if (this.#releasing.has(row.id))
12201
- throw new WebError(409, "handoff_in_progress", "\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002");
12486
+ throw releaseInProgress();
12202
12487
  const opening = this.#opening.get(row.id);
12203
- if (opening)
12204
- return opening;
12488
+ if (opening) {
12489
+ await opening;
12490
+ return;
12491
+ }
12205
12492
  const pending = this.#resumeOpen(row);
12206
12493
  this.#opening.set(row.id, pending);
12494
+ let opened;
12207
12495
  try {
12208
- await pending;
12496
+ opened = await pending;
12209
12497
  } finally {
12210
12498
  if (this.#opening.get(row.id) === pending)
12211
12499
  this.#opening.delete(row.id);
12212
12500
  }
12213
- this.fanout({ type: "sessions" });
12501
+ if (opened)
12502
+ this.fanout({ type: "sessions" });
12214
12503
  }
12215
12504
  async#resumeOpen(row) {
12505
+ if (this.workspaces instanceof WorkspaceAccess)
12506
+ await this.#requireRowWorkspace(row);
12507
+ if (this.#live.has(row.id))
12508
+ return false;
12216
12509
  if (row.cliBookmark) {
12217
12510
  if (!row.nativeId || !this.resolveCli) {
12218
12511
  throw new WebError(409, "resume_unavailable", "\u8BE5 CLI \u4E66\u7B7E\u7F3A\u5C11\u53EF\u7528\u7684\u6765\u6E90\u89E3\u6790\uFF0C\u8BF7\u5237\u65B0 CLI \u5386\u53F2\u540E\u91CD\u8BD5\u3002");
@@ -12220,7 +12513,7 @@ class Sessions {
12220
12513
  const resolved = await this.resolveCli(row.nativeId, row.cwd);
12221
12514
  await this.#requirePrivateHost("resume_unsupported");
12222
12515
  await this.#adoptOpen(row, { sourcePath: resolved.sourcePath, durableId: row.nativeId });
12223
- return;
12516
+ return true;
12224
12517
  }
12225
12518
  if (row.shared === true) {
12226
12519
  if (!row.nativeId || !this.resolveCli) {
@@ -12235,15 +12528,16 @@ class Sessions {
12235
12528
  await this.#requirePrivateHost("resume_unsupported");
12236
12529
  await this.#verifySharedJournal(row, sourcePath);
12237
12530
  await this.#adoptOpen(row, { sourcePath, durableId: row.nativeId });
12238
- return;
12531
+ return true;
12239
12532
  }
12240
12533
  if (row.nativeId !== undefined) {
12241
12534
  await this.#requirePrivateHost("resume_unsupported");
12242
12535
  await this.#verifyWebJournal(row);
12243
12536
  await this.#adoptOpen(row, { durableId: row.nativeId });
12244
- return;
12537
+ return true;
12245
12538
  }
12246
12539
  await this.#open(row, { publishName: true });
12540
+ return true;
12247
12541
  }
12248
12542
  async#requirePrivateHost(code) {
12249
12543
  if (this.workspaces instanceof WorkspaceAccess && !this.engine.status.online)
@@ -12373,6 +12667,16 @@ ${source.nativeSessionId}`;
12373
12667
  pending.abort.abort();
12374
12668
  this.#transcripts.stop();
12375
12669
  }
12670
+ #removeLive(id, live) {
12671
+ if (this.#live.get(id) !== live)
12672
+ return;
12673
+ this.#live.delete(id);
12674
+ this.#transcripts.invalidate(id);
12675
+ if (live.runtime)
12676
+ this.#treeCursors.invalidate(live.runtime);
12677
+ this.#snapshots.get(id)?.abort.abort(sessionChanged());
12678
+ this.fanout({ type: "sessions" });
12679
+ }
12376
12680
  event(frame) {
12377
12681
  const target = [...this.#live.entries()].find(([, live]) => frame.sessionId === live.route);
12378
12682
  if (!target)
@@ -12383,12 +12687,13 @@ ${source.nativeSessionId}`;
12383
12687
  this.fanout({ type: "sessions" });
12384
12688
  }
12385
12689
  if (frame.type === "session_closed" || frame.type === "session_parked" || frame.type === "session_released") {
12386
- this.#live.delete(sessionId);
12387
- this.#transcripts.invalidate(sessionId);
12388
- this.fanout({ type: "sessions" });
12690
+ const closing = this.#closing.get(sessionId);
12691
+ if (frame.type === "session_closed" && closing?.live === live)
12692
+ closing.ended = true;
12693
+ this.#removeLive(sessionId, live);
12389
12694
  }
12390
12695
  if (frame.type === "session_replaced") {
12391
- this.#live.set(sessionId, { route: live.route, running: live.running });
12696
+ this.#live.set(sessionId, { route: live.route, host: live.host, running: live.running });
12392
12697
  this.#transcripts.invalidate(sessionId);
12393
12698
  }
12394
12699
  if (frame.type === "compaction_end" && frame.aborted !== true && frame.success !== false && !frame.errorMessage && !frame.error) {
@@ -12499,7 +12804,7 @@ ${source.nativeSessionId}`;
12499
12804
  async#readSnapshot(id, scope, signal) {
12500
12805
  const check = () => {
12501
12806
  if (signal.aborted)
12502
- throw snapshotAborted();
12807
+ throw signal.reason instanceof WebError ? signal.reason : snapshotAborted();
12503
12808
  scope.check();
12504
12809
  };
12505
12810
  await scope.verifyWorkspace();
@@ -12705,6 +13010,9 @@ ${source.nativeSessionId}`;
12705
13010
  nativeDag(id, key, scope) {
12706
13011
  return readNativeDag(this.#runtimeRead(id), key, scope);
12707
13012
  }
13013
+ nativeTaskOutput(id, key, cursor) {
13014
+ return readNativeTaskOutput(this.#runtimeRead(id), key, cursor);
13015
+ }
12708
13016
  nativeDagHistory(id) {
12709
13017
  return readNativeDagHistory(this.#runtimeRead(id));
12710
13018
  }
@@ -12724,14 +13032,17 @@ ${source.nativeSessionId}`;
12724
13032
  }
12725
13033
  async handoff(id) {
12726
13034
  const row = this.#row(id);
13035
+ if (this.#releasing.has(id))
13036
+ throw releaseInProgress();
13037
+ const live = this.#live.get(id);
12727
13038
  if (this.workspaces instanceof WorkspaceAccess)
12728
13039
  await this.#requireRowWorkspace(row);
12729
- const live = this.#live.get(id);
13040
+ if (this.#opening.has(id) || this.#releasing.has(id))
13041
+ throw releaseInProgress();
13042
+ if (this.#live.get(id) !== live)
13043
+ throw sessionChanged();
12730
13044
  if (!live)
12731
13045
  throw new WebError(409, "session_not_open", "\u4F1A\u8BDD\u672A\u63A5\u5165\u5F15\u64CE\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD\u3002");
12732
- if (this.#opening.has(id) || this.#releasing.has(id)) {
12733
- throw new WebError(409, "handoff_in_progress", "\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002");
12734
- }
12735
13046
  this.#releasing.add(id);
12736
13047
  this.#transcripts.invalidate(id);
12737
13048
  try {
@@ -12780,6 +13091,69 @@ ${source.nativeSessionId}`;
12780
13091
  this.#releasing.delete(id);
12781
13092
  }
12782
13093
  }
13094
+ async#close(row) {
13095
+ const { id } = row;
13096
+ if (this.#opening.has(id) || this.#releasing.has(id))
13097
+ throw releaseInProgress();
13098
+ this.#releasing.add(id);
13099
+ const live = this.#live.get(id);
13100
+ const busy = () => new WebError(409, "session_busy", "\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D\u56DE\u5408\u548C\u961F\u5217\u5DF2\u505C\u6B62\uFF0C\u4F1A\u8BDD\u672A\u5173\u95ED\u3002");
13101
+ try {
13102
+ await this.#requireRowWorkspace(row);
13103
+ if (!live && !this.#live.has(id))
13104
+ return this.#view(this.#row(id));
13105
+ if (!live?.runtime)
13106
+ throw new WebError(409, "binding_unverified", "\u65E0\u6CD5\u6838\u9A8C\u8981\u5173\u95ED\u7684\u4F1A\u8BDD\u6765\u6E90\u3002");
13107
+ const { route, runtime, host } = live;
13108
+ const check = (ended = false) => {
13109
+ const current = this.#rows.get(id);
13110
+ const bound = this.#live.get(id);
13111
+ if (this.#stopping || this.engine.status !== host || !host.online || bound !== live && !(ended && bound === undefined) || current?.cwd !== row.cwd || current.workspaceKey !== row.workspaceKey || current.nativeId !== row.nativeId || [...this.#live].some(([other, binding]) => other !== id && binding.route === route))
13112
+ throw sessionChanged();
13113
+ };
13114
+ const request = (method) => {
13115
+ check();
13116
+ return this.engine.requestExisting(method, { sessionId: route }, 8000);
13117
+ };
13118
+ const readState = async () => {
13119
+ const raw = await request("get_state");
13120
+ if (raw.cwd !== runtime.cwd || raw.sessionId !== runtime.sessionId || raw.sessionFile !== runtime.sessionFile) {
13121
+ throw sessionChanged();
13122
+ }
13123
+ await this.#requireRowWorkspace(row);
13124
+ check();
13125
+ const parsed = closeState.safeParse(raw);
13126
+ if (!parsed.success)
13127
+ throw new WebError(502, "close_state_unverified", "OmO \u672A\u8FD4\u56DE\u53EF\u6838\u9A8C\u7684\u56DE\u5408\u548C\u961F\u5217\u72B6\u6001\u3002");
13128
+ return parsed.data;
13129
+ };
13130
+ check();
13131
+ const writes = this.#actionWrites.get(live);
13132
+ if (writes && (writes.size > 1 || [...writes.values()].some((method) => method !== "compact")) || this.#modelWrites.has(id) || this.#treeWrites.get(runtime)?.pending)
13133
+ throw busy();
13134
+ const before = await readState();
13135
+ const active = hasActiveTurn(before);
13136
+ if (writes?.size && !before.isCompacting)
13137
+ throw busy();
13138
+ if (before.pendingMessageCount > 0)
13139
+ await request("clear_queue");
13140
+ if (live.running || active || before.pendingMessageCount > 0) {
13141
+ await request("abort");
13142
+ const after = await readState();
13143
+ if (hasActiveTurn(after) || after.pendingMessageCount !== 0)
13144
+ throw busy();
13145
+ }
13146
+ const closing = { live, ended: false };
13147
+ this.#closing.set(id, closing);
13148
+ await request("close_session");
13149
+ check(closing.ended);
13150
+ this.#removeLive(id, live);
13151
+ return this.#view(this.#row(id));
13152
+ } finally {
13153
+ this.#closing.delete(id);
13154
+ this.#releasing.delete(id);
13155
+ }
13156
+ }
12783
13157
  async#releaseNative(route, cwd, durable, sessionFile) {
12784
13158
  const fields = { sessionId: route, reason: "takeover" };
12785
13159
  let ack;
@@ -12858,7 +13232,7 @@ ${source.nativeSessionId}`;
12858
13232
  }
12859
13233
  async branchWeb(id, selection) {
12860
13234
  if (this.#releasing.has(id))
12861
- throw new WebError(409, "handoff_in_progress", "\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002");
13235
+ throw releaseInProgress();
12862
13236
  const loaded = await this.#webBranchSource(id);
12863
13237
  if (!loaded)
12864
13238
  throw staleBranch();
@@ -13154,7 +13528,9 @@ ${source.nativeSessionId}`;
13154
13528
  async action(id, action) {
13155
13529
  const row = this.#row(id);
13156
13530
  if (this.#releasing.has(id))
13157
- throw new WebError(409, "handoff_in_progress", "\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002");
13531
+ throw releaseInProgress();
13532
+ if (action.action === "close")
13533
+ return { result: {}, session: await this.#close(row) };
13158
13534
  if (action.action === "resume") {
13159
13535
  await this.#resume(row);
13160
13536
  return { result: {}, session: this.#view(this.#row(id)) };
@@ -13163,11 +13539,35 @@ ${source.nativeSessionId}`;
13163
13539
  const result = await this.#navigate(id, action);
13164
13540
  return { result, session: this.#view(this.#row(id)) };
13165
13541
  }
13542
+ const binding = this.#live.get(id);
13543
+ const host = this.engine.status;
13166
13544
  if (this.workspaces instanceof WorkspaceAccess && action.action !== "abort") {
13167
13545
  await this.#requireRowWorkspace(row);
13168
13546
  }
13169
- const sessionId = this.#route(id);
13170
- const request = (name, fields = {}, timeout) => this.engine.requestExisting(name, { ...fields, sessionId }, timeout);
13547
+ const check = () => {
13548
+ if (this.#releasing.has(id))
13549
+ throw releaseInProgress();
13550
+ if (this.engine.status !== host || this.#live.get(id) !== binding)
13551
+ throw sessionChanged();
13552
+ };
13553
+ check();
13554
+ const live = this.#binding(id);
13555
+ const request = async (name, fields = {}, timeout) => {
13556
+ check();
13557
+ const pending = this.engine.requestExisting(name, { ...fields, sessionId: live.route }, timeout);
13558
+ if (name === "get_commands" || name === "get_state")
13559
+ return pending;
13560
+ const writes = this.#actionWrites.get(live) ?? new Map;
13561
+ this.#actionWrites.set(live, writes);
13562
+ writes.set(pending, name);
13563
+ try {
13564
+ return await pending;
13565
+ } finally {
13566
+ writes.delete(pending);
13567
+ if (!writes.size)
13568
+ this.#actionWrites.delete(live);
13569
+ }
13570
+ };
13171
13571
  let result = {};
13172
13572
  switch (action.action) {
13173
13573
  case "prompt": {
@@ -13277,9 +13677,9 @@ ${source.nativeSessionId}`;
13277
13677
 
13278
13678
  // src/send-file.ts
13279
13679
  import { constants as constants6 } from "fs";
13280
- import { lstat as lstat8, mkdir as mkdir2, open as open7, readdir as readdir4, realpath as realpath8, rename as rename2, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
13680
+ import { lstat as lstat8, mkdir as mkdir2, open as open7, readFile as readFile3, readdir as readdir4, realpath as realpath8, rename as rename2, unlink as unlink3, writeFile as writeFile3 } from "fs/promises";
13281
13681
  import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute2, join as join8, relative, resolve as resolve6, sep as sep3 } from "path";
13282
- import { createHash as createHash3, timingSafeEqual as timingSafeEqual3 } from "crypto";
13682
+ import { createHash as createHash4, timingSafeEqual as timingSafeEqual3 } from "crypto";
13283
13683
  import { Database } from "bun:sqlite";
13284
13684
 
13285
13685
  // src/attachment-range.ts
@@ -13399,7 +13799,18 @@ class AttachmentStore {
13399
13799
  }
13400
13800
  const lock = new Database(lockPath);
13401
13801
  try {
13402
- lock.exec("BEGIN EXCLUSIVE");
13802
+ lock.exec("PRAGMA busy_timeout = 300");
13803
+ try {
13804
+ lock.exec("BEGIN EXCLUSIVE");
13805
+ } catch (error) {
13806
+ if (!(error instanceof Error && ("code" in error) && error.code === "SQLITE_BUSY"))
13807
+ throw error;
13808
+ let pid = "";
13809
+ try {
13810
+ pid = (await readFile3(join8(dirname5(this.#directory), "omo-web.pid"), "utf8")).trim().match(/^\d+$/)?.[0] ?? "";
13811
+ } catch {}
13812
+ throw new WebError(409, "data_dir_in_use", `\u6570\u636E\u76EE\u5F55 ${dirname5(this.#directory)} \u5DF2\u88AB\u53E6\u4E00\u4E2A OmO Web \u8FDB\u7A0B\u5360\u7528${pid ? `\uFF08PID ${pid}\uFF09` : ""}\u3002\u8BF7\u5148\u505C\u6B62\u5DF2\u5728\u8FD0\u884C\u7684 omo-web serve\uFF0C\u518D\u91CD\u65B0\u542F\u52A8\uFF1B\u5982\u9700\u5E76\u884C\u8FD0\u884C\uFF0C\u53EF\u7528 OMO_WEB_DATA \u6307\u5B9A\u522B\u7684\u76EE\u5F55\u3002\u53E6\u4E00\u4E2A\u8FDB\u7A0B\u5DF2\u5728\u8FD0\u884C\u7684\u8BDD\uFF0C\u4E5F\u53EF\u4EE5\u76F4\u63A5\u6253\u5F00\u5B83\u8F93\u51FA\u7684\u7F51\u5740\u3002`);
13813
+ }
13403
13814
  this.#used = 0n;
13404
13815
  for (const entry of await readdir4(this.#directory, { withFileTypes: true })) {
13405
13816
  if (!entry.isFile())
@@ -13411,6 +13822,10 @@ class AttachmentStore {
13411
13822
  this.#identity = { dev: directory.dev, ino: directory.ino };
13412
13823
  await this.#verifyDirectory();
13413
13824
  this.#lock = lock;
13825
+ try {
13826
+ await writeFile3(join8(dirname5(this.#directory), "omo-web.pid"), `${process.pid}
13827
+ `, { mode: 384 });
13828
+ } catch {}
13414
13829
  } catch (error) {
13415
13830
  lock.close();
13416
13831
  throw error;
@@ -13421,6 +13836,11 @@ class AttachmentStore {
13421
13836
  this.#lock?.close();
13422
13837
  this.#lock = undefined;
13423
13838
  this.#identity = undefined;
13839
+ const pidPath = join8(dirname5(this.#directory), "omo-web.pid");
13840
+ try {
13841
+ if ((await readFile3(pidPath, "utf8")).trim() === String(process.pid))
13842
+ await unlink3(pidPath);
13843
+ } catch {}
13424
13844
  }
13425
13845
  async#verifyDirectory() {
13426
13846
  if (!this.#identity)
@@ -13558,7 +13978,7 @@ class AttachmentStore {
13558
13978
  const { name, size } = meta.data.receipt;
13559
13979
  if (!info.isFile() || info.nlink !== 1n || info.size !== BigInt(size))
13560
13980
  throw missing();
13561
- const etag = `"${createHash3("sha256").update(`${id}:${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`).digest("hex")}"`;
13981
+ const etag = `"${createHash4("sha256").update(`${id}:${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`).digest("hex")}"`;
13562
13982
  const range = selectAttachmentRange(requestHeaders, size, etag);
13563
13983
  const headers = new Headers({
13564
13984
  "Accept-Ranges": "bytes",
@@ -13637,10 +14057,10 @@ async function startSendFile(dataDir, resolveBinding, quotaBytes) {
13637
14057
  }
13638
14058
 
13639
14059
  // src/terminal-sessions.ts
13640
- import { createHash as createHash5, createHmac as createHmac4, randomBytes as randomBytes5 } from "crypto";
14060
+ import { createHash as createHash6, createHmac as createHmac4, randomBytes as randomBytes5 } from "crypto";
13641
14061
 
13642
14062
  // src/terminal-registry.ts
13643
- import { createHash as createHash4 } from "crypto";
14063
+ import { createHash as createHash5 } from "crypto";
13644
14064
  import { constants as constants7 } from "fs";
13645
14065
  import { lstat as lstat9, open as open8, opendir as opendir2 } from "fs/promises";
13646
14066
  import { tmpdir as tmpdir2 } from "os";
@@ -13652,7 +14072,7 @@ var MAX_SOCKET_PATH_BYTES = 103;
13652
14072
  var MAX_REGISTRY_BYTES = 8192;
13653
14073
  var SECRET_BYTES = 32;
13654
14074
  var uid = process.getuid?.();
13655
- var hash = (value) => createHash4("sha256").update(value).digest("hex");
14075
+ var hash = (value) => createHash5("sha256").update(value).digest("hex");
13656
14076
  var manifest = object({
13657
14077
  layout: literal(2),
13658
14078
  registry_version: literal(1),
@@ -13976,7 +14396,7 @@ class TerminalSessions {
13976
14396
  const { state } = await this.#refresh(slot.candidate, peer);
13977
14397
  this.#ensureSelected(slot);
13978
14398
  const { message, mode, clientMessageId, expectedTurnId } = checked.data;
13979
- const fingerprint = createHash5("sha256").update(JSON.stringify([mode, message, expectedTurnId])).digest("hex");
14399
+ const fingerprint = createHash6("sha256").update(JSON.stringify([mode, message, expectedTurnId])).digest("hex");
13980
14400
  const key = `${id}:${clientMessageId}`;
13981
14401
  const prior = this.#receipts.get(key);
13982
14402
  if (prior) {
@@ -14386,7 +14806,7 @@ class TerminalSessions {
14386
14806
  }
14387
14807
 
14388
14808
  // src/web-access.ts
14389
- import { createHash as createHash6, timingSafeEqual as timingSafeEqual4, X509Certificate } from "crypto";
14809
+ import { createHash as createHash7, randomBytes as randomBytes6, timingSafeEqual as timingSafeEqual4, X509Certificate } from "crypto";
14390
14810
  import { constants as constants8 } from "fs";
14391
14811
  import { open as open9 } from "fs/promises";
14392
14812
  import { isIP } from "net";
@@ -14508,6 +14928,52 @@ class WebAccessConfigError extends Error {
14508
14928
  var MAX_AUTH_FAILURES = 5;
14509
14929
  var MAX_TRACKED_ADDRESSES = 1024;
14510
14930
  var AUTH_COOLDOWN_MS = 30000;
14931
+ var SESSION_SECONDS = 12 * 60 * 60;
14932
+ var REMEMBER_SECONDS = 7 * 24 * 60 * 60;
14933
+ var MAX_SESSIONS = 1024;
14934
+ var MAX_LOGIN_BYTES = 512;
14935
+ function cookieName(origin) {
14936
+ return origin.protocol === "https:" ? "__Host-omo_web_session" : "omo_web_session";
14937
+ }
14938
+ function sessionCookie(origin, value, maxAge) {
14939
+ return `${cookieName(origin)}=${value}; Path=/; HttpOnly; SameSite=Strict` + (origin.protocol === "https:" ? "; Secure" : "") + (maxAge === undefined ? "" : `; Max-Age=${maxAge}`);
14940
+ }
14941
+ async function loginFields(request) {
14942
+ if (request.headers.get("Content-Type")?.split(";")[0]?.trim().toLowerCase() !== "application/x-www-form-urlencoded")
14943
+ return;
14944
+ const reader = request.body?.getReader();
14945
+ if (!reader)
14946
+ return;
14947
+ const bytes = new Uint8Array(MAX_LOGIN_BYTES);
14948
+ let length = 0;
14949
+ try {
14950
+ if (Number(request.headers.get("Content-Length")) > MAX_LOGIN_BYTES) {
14951
+ reader.cancel().catch(() => {});
14952
+ return;
14953
+ }
14954
+ while (true) {
14955
+ const { done, value } = await reader.read();
14956
+ if (done)
14957
+ break;
14958
+ if (length + value.length > bytes.length) {
14959
+ reader.cancel().catch(() => {});
14960
+ return;
14961
+ }
14962
+ bytes.set(value, length);
14963
+ length += value.length;
14964
+ }
14965
+ } catch {
14966
+ return;
14967
+ } finally {
14968
+ reader.releaseLock();
14969
+ }
14970
+ const form = new URLSearchParams(new TextDecoder().decode(bytes.subarray(0, length)));
14971
+ const [password, ...duplicates] = form.getAll("password");
14972
+ const [remember, ...extra] = form.getAll("remember");
14973
+ if (!password || duplicates.length || extra.length || remember !== undefined && remember !== "1" || form.size !== (remember === undefined ? 1 : 2))
14974
+ return;
14975
+ return { password, remember: remember === "1" };
14976
+ }
14511
14977
  function authFailureLimiter() {
14512
14978
  const attempts = new Map;
14513
14979
  function check(address) {
@@ -14640,9 +15106,52 @@ async function loadWebAccess(env, port) {
14640
15106
  }
14641
15107
  weakPassword = password.length < recommendedPasswordLength;
14642
15108
  const credentials = Buffer.from(`omo:${password}`).toString("base64");
14643
- digest = createHash6("sha256").update(credentials).digest();
15109
+ digest = createHash7("sha256").update(credentials).digest();
15110
+ }
15111
+ const limiter = authFailureLimiter();
15112
+ const cookies = new Map;
15113
+ function revoke(key, session) {
15114
+ cookies.delete(key);
15115
+ for (const disconnect of session.disconnects)
15116
+ disconnect();
15117
+ }
15118
+ function requestAuthority(request, expected) {
15119
+ const requestOrigin = request.headers.get("Origin");
15120
+ const authority = request.headers.get("Host");
15121
+ const matches = (url) => authority === url.host && (requestOrigin === null || requestOrigin === url.origin);
15122
+ const matched = matches(expected) ? expected : proxyOrigin && matches(proxyOrigin) ? proxyOrigin : undefined;
15123
+ if (!matched || ["cross-site", "same-site"].includes(request.headers.get("Sec-Fetch-Site") ?? "")) {
15124
+ throw new WebError(403, "origin_refused", "\u53EA\u63A5\u53D7\u540C\u6E90\u8BF7\u6C42\u3002");
15125
+ }
15126
+ return matched;
15127
+ }
15128
+ function findCookie(request, authority) {
15129
+ const prefix = `${cookieName(authority)}=`;
15130
+ const [match, duplicate] = (request.headers.get("Cookie") ?? "").split(";").map((part) => part.trim()).filter((part) => part.startsWith(prefix));
15131
+ if (!match || duplicate)
15132
+ return;
15133
+ const key = match.slice(prefix.length);
15134
+ if (!/^[A-Za-z0-9_-]{43}$/.test(key))
15135
+ return;
15136
+ const session = cookies.get(key);
15137
+ if (!session || session.origin !== authority.origin)
15138
+ return;
15139
+ if (session.expires <= Date.now()) {
15140
+ revoke(key, session);
15141
+ return;
15142
+ }
15143
+ return { key, session };
15144
+ }
15145
+ function checkWrite(request, token) {
15146
+ const provided = request.headers.get("X-OmO-Token") ?? "";
15147
+ const bytes = provided.length === token.length ? Buffer.from(provided) : undefined;
15148
+ if (!request.headers.has("Origin") || bytes?.length !== token.length || !timingSafeEqual4(bytes, token)) {
15149
+ throw new WebError(403, "token_refused", "\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5\u3002");
15150
+ }
15151
+ }
15152
+ function passwordMatches(encoded) {
15153
+ return digest !== undefined && timingSafeEqual4(createHash7("sha256").update(encoded).digest(), digest);
14644
15154
  }
14645
- const limiter = exposed && digest ? authFailureLimiter() : undefined;
14646
15155
  return {
14647
15156
  hostname: host,
14648
15157
  origin,
@@ -14650,37 +15159,66 @@ async function loadWebAccess(env, port) {
14650
15159
  unprotected,
14651
15160
  weakPassword,
14652
15161
  proxyOrigin,
14653
- authorize(request, expected, token, address) {
14654
- const requestOrigin = request.headers.get("Origin");
14655
- const authority = request.headers.get("Host");
14656
- const matches = (url) => authority === url.host && (requestOrigin === null || requestOrigin === url.origin);
14657
- if (!matches(expected) && !(proxyOrigin && matches(proxyOrigin)) || ["cross-site", "same-site"].includes(request.headers.get("Sec-Fetch-Site") ?? "")) {
15162
+ protected: digest !== undefined,
15163
+ requestAuthority,
15164
+ async login(request, authority, address) {
15165
+ if (!request.headers.has("Origin"))
14658
15166
  throw new WebError(403, "origin_refused", "\u53EA\u63A5\u53D7\u540C\u6E90\u8BF7\u6C42\u3002");
14659
- }
14660
- if (digest) {
15167
+ const form = await loginFields(request);
15168
+ const retryAfter = limiter.check(address);
15169
+ if (retryAfter !== undefined)
15170
+ return { status: 429, retryAfter };
15171
+ if (!form || !passwordPattern.test(form.password))
15172
+ return { status: 400 };
15173
+ if (!passwordMatches(Buffer.from(`omo:${form.password}`).toString("base64"))) {
15174
+ limiter.record(address);
15175
+ return { status: 401 };
15176
+ }
15177
+ const now = Date.now();
15178
+ for (const [key, session] of cookies) {
15179
+ if (session.expires <= now)
15180
+ revoke(key, session);
15181
+ }
15182
+ const previous = findCookie(request, authority);
15183
+ if (previous)
15184
+ revoke(previous.key, previous.session);
15185
+ if (cookies.size >= MAX_SESSIONS)
15186
+ return { status: 503 };
15187
+ const key = randomBytes6(32).toString("base64url");
15188
+ const lifetime = form.remember ? REMEMBER_SECONDS : SESSION_SECONDS;
15189
+ cookies.set(key, { origin: authority.origin, expires: now + lifetime * 1000, disconnects: new Set });
15190
+ return { status: 303, cookie: sessionCookie(authority, key, form.remember ? lifetime : undefined) };
15191
+ },
15192
+ logout(request, authority, token) {
15193
+ checkWrite(request, token);
15194
+ const previous = findCookie(request, authority);
15195
+ if (previous)
15196
+ revoke(previous.key, previous.session);
15197
+ return sessionCookie(authority, "", 0);
15198
+ },
15199
+ authorize(request, expected, token, address) {
15200
+ const authority = requestAuthority(request, expected);
15201
+ const session = digest && findCookie(request, authority)?.session;
15202
+ if (digest && !session) {
14661
15203
  const auth = request.headers.get("Authorization");
14662
15204
  const encoded = auth && auth.length <= 182 ? /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(auth)?.[1] : undefined;
14663
15205
  const source = address && encoded && Buffer.from(encoded, "base64").includes(58) ? address : undefined;
14664
- const retryAfter = source ? limiter?.check(source) : undefined;
15206
+ const retryAfter = source ? limiter.check(source) : undefined;
14665
15207
  if (retryAfter !== undefined) {
14666
15208
  return new Response(null, { status: 429, headers: { ...headers, "Retry-After": String(retryAfter) } });
14667
15209
  }
14668
- if (!encoded || encoded.length < 8 || encoded.length > 176 || !timingSafeEqual4(createHash6("sha256").update(encoded).digest(), digest)) {
15210
+ if (!encoded || encoded.length < 8 || encoded.length > 176 || !passwordMatches(encoded)) {
14669
15211
  if (source)
14670
- limiter?.record(source);
14671
- return new Response(null, { status: 401, headers: { ...headers, "WWW-Authenticate": 'Basic realm="OmO Web"' } });
15212
+ limiter.record(source);
15213
+ return Response.json({ code: "authentication_required", error: "\u8BF7\u767B\u5F55 OmO Web\u3002" }, { status: 401, headers });
14672
15214
  }
14673
15215
  }
14674
15216
  if (request.method === "POST") {
14675
- const provided = request.headers.get("X-OmO-Token") ?? "";
14676
- const bytes = provided.length === token.length ? Buffer.from(provided) : undefined;
14677
- if (requestOrigin === null || bytes?.length !== token.length || !timingSafeEqual4(bytes, token)) {
14678
- throw new WebError(403, "token_refused", "\u8BF7\u5237\u65B0\u9875\u9762\u540E\u91CD\u8BD5\u3002");
14679
- }
15217
+ checkWrite(request, token);
14680
15218
  } else if (request.method !== "GET") {
14681
15219
  throw new WebError(405, "method_refused", "\u8BE5 HTTP \u65B9\u6CD5\u4E0D\u53EF\u7528\u3002");
14682
15220
  }
14683
- return;
15221
+ return session;
14684
15222
  }
14685
15223
  };
14686
15224
  }
@@ -14688,6 +15226,8 @@ async function loadWebAccess(env, port) {
14688
15226
  // src/web-assets.ts
14689
15227
  var assets = {
14690
15228
  "/": "public/index.html",
15229
+ "/auth/login": "public/login.html",
15230
+ "/login.css": "public/login.css",
14691
15231
  "/styles.css": "public/styles.css",
14692
15232
  "/workbench.css": "public/workbench.css",
14693
15233
  "/tool-ledger.css": "public/tool-ledger.css",
@@ -14709,6 +15249,46 @@ async function missingWebAssets() {
14709
15249
  return webAssetPaths.filter((_, index) => !present[index]);
14710
15250
  }
14711
15251
 
15252
+ // src/web-login.ts
15253
+ async function loginPage(request, framed, status = 200, retryAfter) {
15254
+ const url = new URL(request.url);
15255
+ const requested = url.searchParams.get("lang");
15256
+ const preferred = request.headers.get("Accept-Language")?.match(/^(?:[a-z]{2,3})(?=[-,;]|$)/i)?.[0]?.toLowerCase();
15257
+ const en = requested === "en" || requested !== "zh" && preferred !== "zh";
15258
+ const tr = (zh, english) => en ? english : zh;
15259
+ const path = framed ? "/auth/reauth" : "/auth/login";
15260
+ const error = status === 401 ? tr("\u5BC6\u7801\u4E0D\u6B63\u786E\u3002\u8BF7\u91CD\u8BD5\u3002", "Incorrect password. Try again.") : status === 429 ? tr("\u5C1D\u8BD5\u6B21\u6570\u8FC7\u591A\u3002\u8BF7\u7A0D\u5019\u518D\u8BD5\u3002", "Too many attempts. Wait a moment and try again.") : status === 503 ? tr("\u767B\u5F55\u4F1A\u8BDD\u5DF2\u6EE1\u3002\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002", "Too many active sign-ins. Try again later.") : status === 400 ? tr("\u8BF7\u68C0\u67E5\u5BC6\u7801\u540E\u91CD\u8BD5\u3002", "Check your password and try again.") : "";
15261
+ const copy = {
15262
+ lang: tr("zh-CN", "en"),
15263
+ framed: framed ? " data-framed" : "",
15264
+ otherLang: tr("en", "zh-CN"),
15265
+ other: tr("English", "\u7B80\u4F53\u4E2D\u6587"),
15266
+ switch: `${path}?lang=${tr("en", "zh")}`,
15267
+ action: `${path}?lang=${tr("zh", "en")}`,
15268
+ title: framed ? tr("\u91CD\u65B0\u767B\u5F55", "Sign in again") : tr("\u767B\u5F55\u5DE5\u4F5C\u53F0", "Sign in to your workbench"),
15269
+ intro: framed ? tr("\u767B\u5F55\u5DF2\u5931\u6548\u3002\u8349\u7A3F\u4ECD\u5728\u6B64\u9875\u9762\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u53D1\u9001\u3002", "Your sign-in expired. Your draft is still on this page and won\u2019t be sent automatically.") : tr("\u8F93\u5165\u6B64 OmO Web \u5B9E\u4F8B\u914D\u7F6E\u7684\u8BBF\u95EE\u5BC6\u7801\u3002", "Enter the access password configured for this OmO Web instance."),
15270
+ password: tr("\u8BBF\u95EE\u5BC6\u7801", "Access password"),
15271
+ remember: tr("\u5728\u6B64\u8BBE\u5907\u4E0A\u4FDD\u6301\u767B\u5F55 7 \u5929", "Stay signed in on this device for 7 days"),
15272
+ submit: tr("\u767B\u5F55", "Sign in"),
15273
+ error: error ? `<p id="login-error" class="login-error" role="alert">${error}</p>` : "",
15274
+ invalid: error ? ' aria-describedby="login-error"' : ""
15275
+ };
15276
+ const template = webAsset("/auth/login");
15277
+ if (!await template.exists())
15278
+ throw new WebError(404, "missing_asset", "\u9759\u6001\u8D44\u6E90\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C bun run build\u3002");
15279
+ const html = (await template.text()).replace(/\{\{(\w+)\}\}/g, (_, key) => copy[key] ?? "");
15280
+ return new Response(html, { status, headers: {
15281
+ ...headers,
15282
+ "Content-Type": "text/html; charset=utf-8",
15283
+ "Referrer-Policy": "same-origin",
15284
+ ...framed ? {
15285
+ "Content-Security-Policy": headers["Content-Security-Policy"].replace("frame-ancestors 'none'", "frame-ancestors 'self'"),
15286
+ "X-Frame-Options": "SAMEORIGIN"
15287
+ } : {},
15288
+ ...retryAfter === undefined ? {} : { "Retry-After": String(retryAfter) }
15289
+ } });
15290
+ }
15291
+
14712
15292
  // src/server.ts
14713
15293
  var MAX_REQUEST_BYTES = 12 * 1024 * 1024;
14714
15294
  var MAX_JSON_BYTES = 512 * 1024;
@@ -14836,14 +15416,19 @@ async function startApp(settings) {
14836
15416
  }
14837
15417
  return activityResponse(data);
14838
15418
  }
14839
- const clients = new Set;
15419
+ const clients = new Map;
15420
+ const forget = (client) => {
15421
+ clients.get(client)?.cleanup();
15422
+ return clients.delete(client);
15423
+ };
14840
15424
  const disconnect = (client) => {
14841
- if (clients.delete(client))
15425
+ if (forget(client))
14842
15426
  client.close();
14843
15427
  };
14844
15428
  const publish = (chunk) => {
14845
- for (const client of clients) {
14846
- if ((client.desiredSize ?? 0) <= 0)
15429
+ const now = Date.now();
15430
+ for (const [client, { expires }] of clients) {
15431
+ if (expires <= now || (client.desiredSize ?? 0) <= 0)
14847
15432
  disconnect(client);
14848
15433
  else
14849
15434
  client.enqueue(chunk);
@@ -14933,17 +15518,61 @@ async function startApp(settings) {
14933
15518
  const fetch = async (request, listener) => {
14934
15519
  const json = (value, status = 200) => apiJson(value, status, request.method !== "GET");
14935
15520
  try {
14936
- const challenge = access.authorize(request, url, tokenBytes, listener?.requestIP(request)?.address);
14937
- if (challenge)
14938
- return challenge;
14939
- listener?.timeout(request, 240);
14940
15521
  const { pathname, searchParams } = new URL(request.url);
15522
+ const address = listener?.requestIP(request)?.address;
15523
+ const login = pathname === "/auth/login" || pathname === "/auth/reauth";
15524
+ if (access.protected && (login || pathname === "/login.css")) {
15525
+ const authority = access.requestAuthority(request, url);
15526
+ if (request.method === "GET") {
15527
+ if (login)
15528
+ return await loginPage(request, pathname === "/auth/reauth");
15529
+ const file = webAsset(pathname);
15530
+ if (!await file.exists())
15531
+ throw new WebError(404, "missing_asset", "\u9759\u6001\u8D44\u6E90\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C bun run build\u3002");
15532
+ return new Response(file, { headers: { ...headers, "Content-Type": file.type } });
15533
+ }
15534
+ if (!login || request.method !== "POST")
15535
+ throw new WebError(405, "method_refused", "\u8BE5 HTTP \u65B9\u6CD5\u4E0D\u53EF\u7528\u3002");
15536
+ const result = await access.login(request, authority, address ?? "");
15537
+ if (result.status !== 303)
15538
+ return await loginPage(request, pathname === "/auth/reauth", result.status, "retryAfter" in result ? result.retryAfter : undefined);
15539
+ return new Response(null, { status: 303, headers: {
15540
+ ...headers,
15541
+ "Set-Cookie": result.cookie,
15542
+ Location: pathname === "/auth/reauth" ? "/auth/complete" : "/"
15543
+ } });
15544
+ }
15545
+ const auth = access.authorize(request, url, tokenBytes, address);
15546
+ if (auth instanceof Response) {
15547
+ if (auth.status === 401 && pathname === "/" && request.method === "GET" && !request.headers.has("Authorization")) {
15548
+ return await loginPage(request, false);
15549
+ }
15550
+ return auth;
15551
+ }
15552
+ if (access.protected && pathname === "/auth/logout" && request.method === "POST") {
15553
+ emptyBody.parse(await payload(request));
15554
+ return new Response("{}", { headers: {
15555
+ ...headers,
15556
+ "Content-Type": "application/json",
15557
+ "Set-Cookie": access.logout(request, access.requestAuthority(request, url), tokenBytes)
15558
+ } });
15559
+ }
15560
+ listener?.timeout(request, 240);
14941
15561
  if (request.method === "GET") {
15562
+ if (access.protected && pathname === "/auth/complete") {
15563
+ return new Response("<!doctype html><title>OmO Web</title>", { headers: {
15564
+ ...headers,
15565
+ "Content-Type": "text/html",
15566
+ "X-Frame-Options": "SAMEORIGIN",
15567
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'self'"
15568
+ } });
15569
+ }
14942
15570
  const file = webAsset(pathname);
14943
- if (file) {
15571
+ if (file && !login && pathname !== "/login.css") {
14944
15572
  if (!await file.exists())
14945
15573
  throw new WebError(404, "missing_asset", "\u9759\u6001\u8D44\u6E90\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5148\u6267\u884C bun run build\u3002");
14946
- return new Response(file, { headers: { ...headers, "Content-Type": file.type } });
15574
+ const csp = pathname === "/" && access.protected ? { "Content-Security-Policy": `${headers["Content-Security-Policy"]}; frame-src 'self'` } : {};
15575
+ return new Response(file, { headers: { ...headers, ...csp, "Content-Type": file.type } });
14947
15576
  }
14948
15577
  if (pathname === "/api/bootstrap") {
14949
15578
  try {
@@ -14960,7 +15589,8 @@ async function startApp(settings) {
14960
15589
  sessions: await sessions.scopedList(),
14961
15590
  handoff: sessions.handoffSupport(),
14962
15591
  fileBrowser: { platform: workspacePlatform },
14963
- unprotected: access.unprotected
15592
+ unprotected: access.unprotected,
15593
+ ...auth ? { cookieSignIn: true } : {}
14964
15594
  });
14965
15595
  }
14966
15596
  if (pathname === "/api/sessions")
@@ -15058,20 +15688,29 @@ async function startApp(settings) {
15058
15688
  const stream = new ReadableStream({
15059
15689
  start(client) {
15060
15690
  controller = client;
15061
- clients.add(client);
15691
+ const close = () => disconnect(client);
15692
+ const expiry = auth && setTimeout(close, Math.max(0, auth.expires - Date.now()));
15693
+ auth?.disconnects.add(close);
15694
+ request.signal.addEventListener("abort", close, { once: true });
15695
+ clients.set(client, { expires: auth?.expires ?? Infinity, cleanup: () => {
15696
+ if (expiry)
15697
+ clearTimeout(expiry);
15698
+ auth?.disconnects.delete(close);
15699
+ request.signal.removeEventListener("abort", close);
15700
+ } });
15701
+ if (request.signal.aborted) {
15702
+ close();
15703
+ return;
15704
+ }
15062
15705
  const ready = sseFrame({ type: "ready", engine: browserEngineStatus(engine.status) });
15063
15706
  if (ready)
15064
15707
  client.enqueue(ready);
15065
15708
  },
15066
15709
  cancel() {
15067
15710
  if (controller)
15068
- clients.delete(controller);
15711
+ forget(controller);
15069
15712
  }
15070
15713
  }, { highWaterMark: 1024 * 1024, size: (chunk) => chunk?.byteLength ?? 0 });
15071
- request.signal.addEventListener("abort", () => {
15072
- if (controller)
15073
- disconnect(controller);
15074
- }, { once: true });
15075
15714
  listener?.timeout(request, 0);
15076
15715
  return new Response(stream, { headers: {
15077
15716
  ...headers,
@@ -15145,6 +15784,16 @@ async function startApp(settings) {
15145
15784
  return json(result, result.cancelled ? 200 : 201);
15146
15785
  }
15147
15786
  }
15787
+ const task = /^\/api\/sessions\/([a-z0-9-]+)\/native-runtime\/task\/([a-f0-9]{64})\/output$/u.exec(pathname);
15788
+ if (task?.[2]) {
15789
+ if (request.method !== "GET")
15790
+ throw new WebError(405, "method_not_allowed", "\u6B64\u5165\u53E3\u53EA\u652F\u6301 GET\u3002");
15791
+ const cursor = searchParams.size === 0 ? undefined : taskOutputCursor.safeParse(searchParams.get("cursor"));
15792
+ if (searchParams.size > 1 || cursor?.success === false)
15793
+ throw new WebError(400, "invalid_request", "\u8BF7\u6C42\u53C2\u6570\u4E0D\u6B63\u786E\u3002");
15794
+ const result = await sessions.nativeTaskOutput(sessionKey.parse(task[1]), task[2], cursor?.data);
15795
+ return jsonWithin(result, TASK_OUTPUT_PAGE_BYTES) ?? json({ status: "malformed" });
15796
+ }
15148
15797
  const dag = /^\/api\/sessions\/([a-z0-9-]+)\/native-runtime\/dag\/([a-f0-9]{64})$/u.exec(pathname);
15149
15798
  if (request.method === "GET" && dag?.[2]) {
15150
15799
  const [scope = "current", ...extra] = searchParams.getAll("scope");
@@ -15280,7 +15929,8 @@ async function startApp(settings) {
15280
15929
  throw error;
15281
15930
  }
15282
15931
  const url = access.origin === undefined ? server.url : new URL(access.origin);
15283
- const heartbeat = setInterval(() => publish(encoder.encode(`: keepalive
15932
+ const heartbeat = setInterval(() => publish(encoder.encode(`event: heartbeat
15933
+ data: {}
15284
15934
 
15285
15935
  `)), 15000);
15286
15936
  let closing;
@@ -15295,7 +15945,7 @@ async function startApp(settings) {
15295
15945
  clearInterval(heartbeat);
15296
15946
  terminals.stop();
15297
15947
  sessions.stop();
15298
- for (const client of clients)
15948
+ for (const client of clients.keys())
15299
15949
  disconnect(client);
15300
15950
  await Promise.all([server.stop(true), engine.stop(), sendFile?.stop()]);
15301
15951
  })();
@@ -15336,10 +15986,15 @@ var app = await startApp({
15336
15986
  "in-process"
15337
15987
  ]
15338
15988
  }).catch((error) => {
15339
- if (!(error instanceof WebAccessConfigError))
15340
- throw error;
15341
- console.error(`OmO Web config: ${error.message}`);
15342
- process.exit(1);
15989
+ if (error instanceof WebAccessConfigError) {
15990
+ console.error(`OmO Web config: ${error.message}`);
15991
+ process.exit(1);
15992
+ }
15993
+ if (error instanceof WebError) {
15994
+ console.error(cliTr(`OmO Web \u65E0\u6CD5\u542F\u52A8\uFF1A${error.message}`, `OmO Web cannot start: ${error.message}`));
15995
+ process.exit(1);
15996
+ }
15997
+ throw error;
15343
15998
  });
15344
15999
  if (app.unprotected)
15345
16000
  console.warn(cliTr("\u8B66\u544A\uFF1A\u975E\u672C\u673A\u5165\u53E3\u672A\u8BBE\u5BC6\u7801\u3002\u80FD\u8BBF\u95EE\u6B64\u5730\u5740\u7684\u4EBA\u90FD\u80FD\u8BFB\u53D6\u4F1A\u8BDD\u5E76\u901A\u8FC7 OmO \u64CD\u4F5C\u672C\u673A\u3002\u4EC5\u5728\u53D7\u9650\u79C1\u7F51\u6216 VPN \u5185\u4F7F\u7528\u3002", "Warning: remote access without a password. Anyone who can reach this address can read sessions and run tools through OmO. Use only on a restricted private network or VPN."));