openwork-server 0.18.63 → 0.18.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +2 -2
  2. package/dist/opencode-plugin-deps-1.18.33.tgz +0 -0
  3. package/dist/opencode-plugins/approval-loopback-fetch.js +18 -0
  4. package/dist/opencode-plugins/computer-listing-files.js +101 -0
  5. package/dist/opencode-plugins/drive-file-tools.js +2 -2
  6. package/dist/opencode-plugins/managed-policy-next.js +11 -5
  7. package/dist/opencode-plugins/openwork-agent-permissions-v2.js +162 -11
  8. package/dist/opencode-plugins/openwork-agent-questions.js +24 -0
  9. package/dist/opencode-plugins/openwork-auto-route-v2.js +19657 -0
  10. package/dist/opencode-plugins/openwork-capabilities-knowledge.js +5 -3
  11. package/dist/opencode-plugins/openwork-chrome-devtools.js +17498 -5
  12. package/dist/opencode-plugins/openwork-cloud-skills-v2.js +54 -31
  13. package/dist/opencode-plugins/openwork-codemode-discovery-v2.js +19 -6
  14. package/dist/opencode-plugins/openwork-computer-use.js +17650 -37
  15. package/dist/opencode-plugins/openwork-context-v2.js +17840 -78
  16. package/dist/opencode-plugins/openwork-extensions-preview.js +929 -175
  17. package/dist/opencode-plugins/openwork-gateway-quota-v2.js +15 -0
  18. package/dist/opencode-plugins/openwork-gateway-quota.js +15 -0
  19. package/dist/opencode-plugins/openwork-mcp-results-v2.js +20 -4
  20. package/dist/opencode-plugins/openwork-office-attachments.js +1 -1
  21. package/dist/opencode-plugins/openwork-provider-adapters.js +65 -6
  22. package/dist/opencode-plugins/openwork-provider-sync-v2.js +459 -139
  23. package/dist/opencode-plugins/openwork-session-groups.js +5 -4
  24. package/dist/opencode-plugins/openwork-spreadsheets.js +1 -1
  25. package/dist/opencode-plugins/openwork-ui-bridge.js +6 -3
  26. package/dist/opencode-plugins/session-read-detail.js +475 -0
  27. package/dist/openwork-server.mjs +98993 -87384
  28. package/package.json +1 -1
  29. package/web/assets/{abnfDiagram-VCTEODGH-BSIb81ug.js → abnfDiagram-VCTEODGH-_euFTfuE.js} +1 -1
  30. package/web/assets/app-BL4DzbHg.css +32 -0
  31. package/web/assets/{app-DZr96oX3.js → app-B_eR6sGg.js} +461 -460
  32. package/web/assets/{arc-BTCnV0Ha.js → arc-DIIHEUK5.js} +1 -1
  33. package/web/assets/{architectureDiagram-5GKGNRK7-3IgeX1_6.js → architectureDiagram-5GKGNRK7-DD7V4Nl6.js} +1 -1
  34. package/web/assets/{artifact-code-view-ZP8nVuQx.js → artifact-code-view-2fHBrzKl.js} +1 -1
  35. package/web/assets/{artifact-spreadsheet-editor-BW94PK45.js → artifact-spreadsheet-editor-D2kPT8kU.js} +1 -1
  36. package/web/assets/{artifact-text-editor-BhIcTcNi.js → artifact-text-editor-uJetA3RS.js} +1 -1
  37. package/web/assets/{blockDiagram-OSKFZWR5-d1pNUfi4.js → blockDiagram-OSKFZWR5-B5VTERzj.js} +1 -1
  38. package/web/assets/{c4Diagram-7LVT6UL2-BTVoP_gs.js → c4Diagram-7LVT6UL2-1Lh6d98a.js} +1 -1
  39. package/web/assets/channel-CLju5G1-.js +1 -0
  40. package/web/assets/{chunk-2Q5K7J3B-BIy8BDgC.js → chunk-2Q5K7J3B-BYSg2PtF.js} +1 -1
  41. package/web/assets/{chunk-5VM5RSS4-BDvSSuPz.js → chunk-5VM5RSS4-CUeEqVp6.js} +1 -1
  42. package/web/assets/{chunk-F27PBJKO-CqT02j1I.js → chunk-F27PBJKO-BYl1gIUK.js} +1 -1
  43. package/web/assets/{chunk-HLEWEB6X-DOSYJ6qO.js → chunk-HLEWEB6X-CSHTqizU.js} +1 -1
  44. package/web/assets/{chunk-JWPE2WC7-BLJ5TLJ6.js → chunk-JWPE2WC7-C3M9OIeQ.js} +1 -1
  45. package/web/assets/{chunk-POPQ4Y6H-TRvB63--.js → chunk-POPQ4Y6H-CBer2BDK.js} +1 -1
  46. package/web/assets/{chunk-SVP7TREG-Bz6HrnA2.js → chunk-SVP7TREG-gh6XHnDe.js} +1 -1
  47. package/web/assets/{chunk-XXDRQBXY-wBuvw6SP.js → chunk-XXDRQBXY-BWW96PGH.js} +1 -1
  48. package/web/assets/{chunk-ZLD2IHE6-CsK6m1Sk.js → chunk-ZLD2IHE6-BwjCpFv6.js} +1 -1
  49. package/web/assets/classDiagram-CYGNFDIV-DZO1M7Ic.js +1 -0
  50. package/web/assets/classDiagram-v2-TLXNO2FR-DZO1M7Ic.js +1 -0
  51. package/web/assets/{cose-bilkent-JH36ORCC-CISbKtKO.js → cose-bilkent-JH36ORCC-lJjj59Sx.js} +1 -1
  52. package/web/assets/{cynefin-OW5HDTMX-Dk7vIkhw.js → cynefin-OW5HDTMX-CAIFZQxV.js} +1 -1
  53. package/web/assets/{cynefinDiagram-5FMLGOSQ-C3bIjcy0.js → cynefinDiagram-5FMLGOSQ-BNCAcb93.js} +1 -1
  54. package/web/assets/{dagre-OS7QT2EB-BsP75gf5.js → dagre-OS7QT2EB-DMlHDwrG.js} +1 -1
  55. package/web/assets/{diagram-S7CK7UJ4-B4K-iSz7.js → diagram-S7CK7UJ4-Dbpa25GK.js} +1 -1
  56. package/web/assets/{diagram-UQ7AKVKN-bly7AwhV.js → diagram-UQ7AKVKN-BCT_Qc9p.js} +1 -1
  57. package/web/assets/{diagram-VSXAHHWV-DObKajM9.js → diagram-VSXAHHWV-CapON9I2.js} +1 -1
  58. package/web/assets/{diagram-VX7I27RA-SQp5kc6I.js → diagram-VX7I27RA-CCMsrHOR.js} +1 -1
  59. package/web/assets/{diagram-Z3DM3KII-BmaqS6Rw.js → diagram-Z3DM3KII-BOpKxuDL.js} +1 -1
  60. package/web/assets/{ebnfDiagram-PWID7BFC-BOhK-9Al.js → ebnfDiagram-PWID7BFC-C1sb3HsT.js} +1 -1
  61. package/web/assets/{erDiagram-2YWLMYGG-DP0d4SRU.js → erDiagram-2YWLMYGG-3TIcbkY2.js} +1 -1
  62. package/web/assets/{flowDiagram-T62WH6J4-CJLvattq.js → flowDiagram-T62WH6J4-C3YP5_VV.js} +1 -1
  63. package/web/assets/{ganttDiagram-EL5Y4UJY-Dzi8suyh.js → ganttDiagram-EL5Y4UJY-BWO0IFRX.js} +1 -1
  64. package/web/assets/{gitGraphDiagram-WWUBYQGX-D-xOZUu9.js → gitGraphDiagram-WWUBYQGX-Dpi4d5u9.js} +1 -1
  65. package/web/assets/{infoDiagram-FKFFQAWI-CTR7Ei2k.js → infoDiagram-FKFFQAWI-C3t_XWD1.js} +1 -1
  66. package/web/assets/{ishikawaDiagram-5VMMS53U-CBf51Qea.js → ishikawaDiagram-5VMMS53U-Duhj9xvC.js} +1 -1
  67. package/web/assets/{journeyDiagram-EYS64GPL-ZumMGF2u.js → journeyDiagram-EYS64GPL-Bq_tWeLz.js} +1 -1
  68. package/web/assets/{kanban-definition-UXKFOSKX-81Fni8Sl.js → kanban-definition-UXKFOSKX-C7zCaEcE.js} +1 -1
  69. package/web/assets/{layout-D-HFg0Gy.js → layout-BGV5k35C.js} +1 -1
  70. package/web/assets/{linear-lAHomfjd.js → linear-jBjiubEm.js} +1 -1
  71. package/web/assets/{mermaid.core-sRbhnZ3C.js → mermaid.core-DcEA9CwK.js} +6 -6
  72. package/web/assets/{mindmap-definition-THT77NOG-t_uxFNYx.js → mindmap-definition-THT77NOG-DWi2qNO-.js} +1 -1
  73. package/web/assets/{pegDiagram-XKGWAZYB-B4FryuiE.js → pegDiagram-XKGWAZYB-mpdETODF.js} +1 -1
  74. package/web/assets/{pieDiagram-E7YTZNPT-DrIgLewj.js → pieDiagram-E7YTZNPT-B_E8xv7R.js} +1 -1
  75. package/web/assets/{quadrantDiagram-AXDQQJYC-DifmQS8L.js → quadrantDiagram-AXDQQJYC-C3DLSKZx.js} +1 -1
  76. package/web/assets/{railroadDiagram-O6MQD6OU-C76a1ZKv.js → railroadDiagram-O6MQD6OU-CV8e2EYD.js} +1 -1
  77. package/web/assets/{requirementDiagram-IS5BZ75X-CT_K8F_V.js → requirementDiagram-IS5BZ75X-D8_GWwzL.js} +1 -1
  78. package/web/assets/{sankeyDiagram-P5KCCOFB-DWQLcVQR.js → sankeyDiagram-P5KCCOFB-BedccLEd.js} +1 -1
  79. package/web/assets/{sequenceDiagram-WJ2MYXX4-aTZD72z2.js → sequenceDiagram-WJ2MYXX4-Cf9QsPD1.js} +1 -1
  80. package/web/assets/{sizeCapture-INFHLROL-BzVHqyuK.js → sizeCapture-INFHLROL-BZXVwOZ-.js} +1 -1
  81. package/web/assets/{stateDiagram-XQSTLZYL-D9BpFjx0.js → stateDiagram-XQSTLZYL-JaEqdUWJ.js} +1 -1
  82. package/web/assets/stateDiagram-v2-IH3M54BS-BVaVsTdq.js +1 -0
  83. package/web/assets/{swimlanes-V6O3JKXN-DiN46HW4.js → swimlanes-V6O3JKXN-CIkru_FY.js} +1 -1
  84. package/web/assets/swimlanesDiagram-JKAHXJPX-AGVU67SD.js +8 -0
  85. package/web/assets/{timeline-definition-24CTP7MA-CJZAuVpz.js → timeline-definition-24CTP7MA-BDahVZ3U.js} +1 -1
  86. package/web/assets/{vennDiagram-4TSXK5OY-d5RgWEF0.js → vennDiagram-4TSXK5OY-yi0sphxQ.js} +1 -1
  87. package/web/assets/{wardleyDiagram-VM6X3IG4-DP1nzuP1.js → wardleyDiagram-VM6X3IG4-PXKHpuHP.js} +1 -1
  88. package/web/assets/{workspace-file-tree-iodkCqW9.js → workspace-file-tree-BoW3xSOx.js} +1 -1
  89. package/web/assets/{xychartDiagram-S5SC5T6Z-Bh1aCFiI.js → xychartDiagram-S5SC5T6Z-2ZN6-3RY.js} +1 -1
  90. package/web/index.html +2 -2
  91. package/web/assets/app-Bx1ym5U0.css +0 -32
  92. package/web/assets/channel-DqkU7DUB.js +0 -1
  93. package/web/assets/classDiagram-CYGNFDIV-C-Tb50QW.js +0 -1
  94. package/web/assets/classDiagram-v2-TLXNO2FR-C-Tb50QW.js +0 -1
  95. package/web/assets/stateDiagram-v2-IH3M54BS-B7xLeFMx.js +0 -1
  96. package/web/assets/swimlanesDiagram-JKAHXJPX-C1vbqhAp.js +0 -8
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { strictArgsSchema } from "./openwork-provider-adapters.js";
2
3
  // Sidebar groups live in the OpenWork server's workspace store, so the agent
3
4
  // changes them there directly. Nothing here needs the desktop window: the app
4
5
  // follows these writes through its session-group event feed.
@@ -6,17 +7,17 @@ export const SESSION_GROUP_COMMAND_IDS = ["session.group.create", "session.group
6
7
  export const SESSION_GROUP_AFFORDANCE_IDS = ["session.group.list", ...SESSION_GROUP_COMMAND_IDS];
7
8
  const workspaceIdArg = z.string().trim().optional()
8
9
  .describe("Optional OpenWork workspace id/name. Defaults to the workspace of the session involved.");
9
- export const sessionGroupListArgsSchema = z.object({ workspaceId: workspaceIdArg });
10
- export const sessionGroupCreateArgsSchema = z.object({
10
+ export const sessionGroupListArgsSchema = strictArgsSchema({ workspaceId: workspaceIdArg });
11
+ export const sessionGroupCreateArgsSchema = strictArgsSchema({
11
12
  label: z.string().trim().min(1).max(120).describe("Group name shown in the sidebar, for example \"Done\" or \"In progress\"."),
12
13
  workspaceId: workspaceIdArg,
13
14
  });
14
- export const sessionGroupMoveArgsSchema = z.object({
15
+ export const sessionGroupMoveArgsSchema = strictArgsSchema({
15
16
  sessionId: z.string().trim().min(1).describe("Session ID from session.search, session.read or session.group.list."),
16
17
  groupId: z.string().trim().nullable().optional().describe("Group id or exact label from session.group.list. Omit or null to ungroup."),
17
18
  workspaceId: workspaceIdArg,
18
19
  });
19
- export const sessionGroupRemoveArgsSchema = z.object({
20
+ export const sessionGroupRemoveArgsSchema = strictArgsSchema({
20
21
  groupId: z.string().trim().min(1).describe("Group id or exact label to remove. Its sessions are kept."),
21
22
  destinationGroupId: z.string().trim().optional().describe("Optional group id or label that receives the removed group's sessions. Omit to leave them ungrouped."),
22
23
  confirmed: z.literal(true).describe("Must be true: the person asked for this group to be removed."),
@@ -19556,7 +19556,7 @@ async function openWorkspaceFileForReading(realRoot, path, label) {
19556
19556
  await refuseLinkedFolder(path, label, "missing");
19557
19557
  let handle;
19558
19558
  try {
19559
- handle = await open2(path, constants.O_RDONLY | NO_FOLLOW);
19559
+ handle = await open2(path, constants.O_RDONLY | NO_FOLLOW | (constants.O_NONBLOCK ?? 0));
19560
19560
  } catch (error62) {
19561
19561
  const code = errorCode(error62);
19562
19562
  if (code === "ENOENT" || code === "ENOTDIR")
@@ -1,3 +1,4 @@
1
+ import { approvalLoopbackFetch } from "./approval-loopback-fetch.js";
1
2
  import { readFile } from "node:fs/promises";
2
3
  import { join } from "node:path";
3
4
  import { homedir, platform } from "node:os";
@@ -56,9 +57,8 @@ options = {}) {
56
57
  if (!bridge)
57
58
  return { ok: false, code: "browser_unavailable", dispatched: false, error: "The built-in browser is unavailable. Open the desktop app on the same machine as this task's server." };
58
59
  try {
59
- const response = await fetch(`${bridge.baseUrl}${path}`, {
60
+ const request = {
60
61
  method: options.method || "GET",
61
- redirect: "error",
62
62
  signal: options.timeoutMs === null && options.signal ? options.signal
63
63
  : options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs ?? BRIDGE_TIMEOUT_MS)]) : AbortSignal.timeout(options.timeoutMs ?? BRIDGE_TIMEOUT_MS),
64
64
  headers: {
@@ -66,7 +66,10 @@ options = {}) {
66
66
  ...(options.body ? { "Content-Type": "application/json" } : {}),
67
67
  },
68
68
  ...(options.body ? { body: JSON.stringify(options.body) } : {}),
69
- });
69
+ };
70
+ const response = options.timeoutMs === null && options.signal
71
+ ? await approvalLoopbackFetch(`${bridge.baseUrl}${path}`, request)
72
+ : await fetch(`${bridge.baseUrl}${path}`, { ...request, redirect: "error" });
70
73
  const text = await response.text();
71
74
  try {
72
75
  return JSON.parse(text);
@@ -0,0 +1,475 @@
1
+ /**
2
+ * `session.read` with `detail: "full"`: every message and content item the
3
+ * engine stores, mapped from OpenCode v2's native message schema
4
+ * (`Session.Message.Info`, `GET /api/session/:id/message`, engine 2.2.0) and,
5
+ * for sessions still on v1, from the equivalent v1 message parts into the
6
+ * same shape.
7
+ *
8
+ * Kept: every message type (user, assistant, synthetic, system, skill, shell,
9
+ * compaction, idle, agent/model/location switches) and every assistant
10
+ * content item (text, reasoning, tool calls with input, output, files, error,
11
+ * metadata and timing), plus model, agent, finish reason, tokens, cost,
12
+ * retries and changed files.
13
+ *
14
+ * Left out on purpose: provider `native` blobs (opaque, provider-specific,
15
+ * may hold signed reasoning), inline base64 file data (the file's name, type
16
+ * and URI are kept) and raw provider response bodies in errors.
17
+ *
18
+ * Long fields are clipped with a visible marker and the message is flagged
19
+ * `truncated`; reading one message by `messageId` raises the limits.
20
+ *
21
+ * Dependency-free on purpose: the bundled engine plugin imports it.
22
+ */
23
+ function isRecord(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function str(value) {
27
+ return typeof value === "string" ? value : undefined;
28
+ }
29
+ function num(value) {
30
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
31
+ }
32
+ function rec(value) {
33
+ return isRecord(value) ? value : undefined;
34
+ }
35
+ function list(value) {
36
+ return Array.isArray(value) ? value : [];
37
+ }
38
+ /** Drops undefined fields so the result stays compact. */
39
+ function compact(value) {
40
+ for (const key of Object.keys(value))
41
+ if (value[key] === undefined)
42
+ delete value[key];
43
+ return value;
44
+ }
45
+ export const SESSION_READ_LIST_LIMITS = {
46
+ text: 8_000,
47
+ reasoning: 4_000,
48
+ context: 2_000,
49
+ toolInput: 2_000,
50
+ toolOutput: 4_000,
51
+ toolMetadata: 1_000,
52
+ shellOutput: 4_000,
53
+ compactionSummary: 4_000,
54
+ errorMessage: 1_000,
55
+ toolBudget: 64_000,
56
+ };
57
+ export const SESSION_READ_MESSAGE_LIMITS = {
58
+ text: 100_000,
59
+ reasoning: 50_000,
60
+ context: 50_000,
61
+ toolInput: 50_000,
62
+ toolOutput: 100_000,
63
+ toolMetadata: 20_000,
64
+ shellOutput: 100_000,
65
+ compactionSummary: 50_000,
66
+ errorMessage: 4_000,
67
+ toolBudget: 400_000,
68
+ };
69
+ /** Whole-result character budget for a list read. One message is always returned. */
70
+ export const SESSION_READ_RESULT_BUDGET = 200_000;
71
+ class Clipper {
72
+ limits;
73
+ truncated = false;
74
+ constructor(limits) {
75
+ this.limits = limits;
76
+ }
77
+ text(value, limit) {
78
+ if (value === undefined)
79
+ return undefined;
80
+ if (value.length <= limit)
81
+ return value;
82
+ this.truncated = true;
83
+ return `${value.slice(0, limit)}…[+${value.length - limit} chars; read this message by messageId for more]`;
84
+ }
85
+ /** Small JSON values stay structured; large ones become a clipped JSON string. */
86
+ json(value, limit) {
87
+ if (value === undefined)
88
+ return undefined;
89
+ if (typeof value === "string")
90
+ return this.text(value, limit);
91
+ let encoded;
92
+ try {
93
+ encoded = JSON.stringify(value) ?? "";
94
+ }
95
+ catch {
96
+ return "[unserializable]";
97
+ }
98
+ if (encoded.length <= limit)
99
+ return value;
100
+ return this.text(encoded, limit);
101
+ }
102
+ }
103
+ function richModel(value) {
104
+ const model = rec(value);
105
+ if (!model)
106
+ return undefined;
107
+ const modelId = str(model.id) ?? str(model.modelID);
108
+ const providerId = str(model.providerID);
109
+ if (!modelId || !providerId)
110
+ return undefined;
111
+ return compact({ providerId, modelId, variant: str(model.variant) });
112
+ }
113
+ function richTokens(value) {
114
+ const tokens = rec(value);
115
+ if (!tokens)
116
+ return undefined;
117
+ const cache = rec(tokens.cache);
118
+ return compact({
119
+ input: num(tokens.input),
120
+ output: num(tokens.output),
121
+ reasoning: num(tokens.reasoning),
122
+ cache: cache ? compact({ read: num(cache.read), write: num(cache.write) }) : undefined,
123
+ });
124
+ }
125
+ /** v2 `Session.StructuredError`; the provider response body is omitted. */
126
+ function richV2Error(value, clip) {
127
+ const error = rec(value);
128
+ if (!error)
129
+ return undefined;
130
+ return compact({
131
+ type: str(error.type) ?? "UnknownError",
132
+ message: clip.text(str(error.message), clip.limits.errorMessage),
133
+ status: num(error.status),
134
+ retryAfterMs: num(error.retryAfterMs),
135
+ });
136
+ }
137
+ function richTime(value) {
138
+ const time = rec(value);
139
+ return compact({ created: num(time?.created), streamed: num(time?.streamed), completed: num(time?.completed) });
140
+ }
141
+ function childSessionId(tool, metadata) {
142
+ if (!metadata || (tool !== "subagent" && tool !== "task"))
143
+ return undefined;
144
+ return str(metadata.sessionId)?.trim() || str(metadata.sessionID)?.trim() || undefined;
145
+ }
146
+ /** A file reference without its bytes: `data:` URLs carry the whole file, so they become `inline`. */
147
+ function fileRef(name, mime, uri) {
148
+ const inline = uri?.startsWith("data:") === true;
149
+ return compact({ name, mime, uri: inline ? undefined : uri, inline: inline ? true : undefined });
150
+ }
151
+ function nonEmpty(value) {
152
+ return value && Object.keys(value).length > 0 ? value : undefined;
153
+ }
154
+ /** Keeps tool input, output and metadata within the message's tool budget. */
155
+ function budgetTools(content, clip) {
156
+ let budget = clip.limits.toolBudget;
157
+ return content.map((item) => {
158
+ if (item.type !== "tool")
159
+ return item;
160
+ const size = JSON.stringify(item).length;
161
+ if (size <= budget) {
162
+ budget -= size;
163
+ return item;
164
+ }
165
+ budget = 0;
166
+ if (item.input === undefined && item.output === undefined && item.metadata === undefined)
167
+ return item;
168
+ clip.truncated = true;
169
+ const { input: _input, output: _output, metadata: _metadata, ...listed } = item;
170
+ return { ...listed, detailOmitted: true };
171
+ });
172
+ }
173
+ function v2ToolOutput(content) {
174
+ const texts = [];
175
+ const files = [];
176
+ for (const item of list(content)) {
177
+ if (!isRecord(item))
178
+ continue;
179
+ if (item.type === "text" && typeof item.text === "string")
180
+ texts.push(item.text);
181
+ if (item.type === "file")
182
+ files.push(fileRef(str(item.name), str(item.mime), str(item.uri)));
183
+ }
184
+ return { ...(texts.length ? { output: texts.join("\n") } : {}), ...(files.length ? { files } : {}) };
185
+ }
186
+ function v2Tool(item, clip) {
187
+ const id = str(item.id);
188
+ const name = str(item.name);
189
+ const state = rec(item.state);
190
+ if (!id || !name || !state)
191
+ return null;
192
+ const status = str(state.status) ?? "unknown";
193
+ const metadata = rec(state.metadata);
194
+ const { output, files } = v2ToolOutput(state.content);
195
+ const time = rec(item.time);
196
+ const call = {
197
+ type: "tool",
198
+ id,
199
+ name,
200
+ status,
201
+ executed: typeof item.executed === "boolean" ? item.executed : undefined,
202
+ // Streaming input is the raw partial JSON text the model is still writing.
203
+ input: clip.json(state.input, clip.limits.toolInput),
204
+ output: clip.text(output, clip.limits.toolOutput),
205
+ files,
206
+ error: status === "error" ? richV2Error(state.error, clip) : undefined,
207
+ metadata: clip.json(nonEmpty(metadata), clip.limits.toolMetadata),
208
+ childSessionId: childSessionId(name, metadata),
209
+ time: time ? compact({ created: num(time.created), ran: num(time.ran), completed: num(time.completed) }) : undefined,
210
+ };
211
+ return compact(call);
212
+ }
213
+ function v2Content(value, clip) {
214
+ const content = [];
215
+ for (const item of list(value)) {
216
+ if (!isRecord(item))
217
+ continue;
218
+ if (item.type === "text") {
219
+ content.push({ type: "text", text: clip.text(str(item.text) ?? "", clip.limits.text) ?? "" });
220
+ }
221
+ else if (item.type === "reasoning") {
222
+ const time = rec(item.time);
223
+ content.push(compact({
224
+ type: "reasoning",
225
+ text: clip.text(str(item.text) ?? "", clip.limits.reasoning) ?? "",
226
+ time: time ? compact({ created: num(time.created), completed: num(time.completed) }) : undefined,
227
+ }));
228
+ }
229
+ else if (item.type === "tool") {
230
+ const tool = v2Tool(item, clip);
231
+ if (tool)
232
+ content.push(tool);
233
+ }
234
+ }
235
+ return budgetTools(content, clip);
236
+ }
237
+ function v2File(value) {
238
+ const file = rec(value);
239
+ if (!file)
240
+ return null;
241
+ const source = rec(file.source);
242
+ if (source?.type === "uri")
243
+ return fileRef(str(file.name), str(file.mime), str(source.uri));
244
+ return compact({ name: str(file.name), mime: str(file.mime), inline: true });
245
+ }
246
+ /** Maps one native v2 `Session.Message.Info`. Unknown future types keep id, type and time. */
247
+ export function richV2Message(row, limits, options = {}) {
248
+ if (!isRecord(row))
249
+ return null;
250
+ const id = str(row.id);
251
+ const type = str(row.type);
252
+ if (!id || !type)
253
+ return null;
254
+ const clip = new Clipper(limits);
255
+ const base = { id, type, time: richTime(row.time) };
256
+ let fields = {};
257
+ switch (type) {
258
+ case "user": {
259
+ const files = list(row.files).map(v2File).filter((file) => file !== null);
260
+ const agents = list(row.agents).flatMap((agent) => (isRecord(agent) && typeof agent.name === "string" ? [agent.name] : []));
261
+ const skills = list(row.skills).flatMap((skill) => isRecord(skill) && typeof skill.name === "string" ? [compact({ id: str(skill.id), name: skill.name })] : []);
262
+ fields = {
263
+ text: clip.text(str(row.text) ?? "", limits.text),
264
+ files: files.length ? files : undefined,
265
+ agents: agents.length ? agents : undefined,
266
+ skills: skills.length ? skills : undefined,
267
+ };
268
+ break;
269
+ }
270
+ case "synthetic":
271
+ case "system":
272
+ fields = { text: clip.text(str(row.text) ?? "", limits.context) };
273
+ break;
274
+ case "skill":
275
+ fields = { skill: str(row.skill), name: str(row.name), text: clip.text(str(row.text) ?? "", limits.context) };
276
+ break;
277
+ case "shell": {
278
+ const output = rec(row.output);
279
+ fields = {
280
+ shellId: str(row.shellID),
281
+ command: str(row.command),
282
+ status: str(row.status),
283
+ exit: num(row.exit) ?? str(row.exit),
284
+ output: clip.text(str(output?.output), limits.shellOutput),
285
+ outputTruncatedByEngine: output?.truncated === true ? true : undefined,
286
+ };
287
+ break;
288
+ }
289
+ case "assistant": {
290
+ const snapshot = rec(row.snapshot);
291
+ const retry = rec(row.retry);
292
+ const changed = list(snapshot?.files).filter((file) => typeof file === "string");
293
+ fields = {
294
+ agent: str(row.agent),
295
+ model: richModel(row.model),
296
+ finish: str(row.finish),
297
+ cost: num(row.cost),
298
+ tokens: richTokens(row.tokens),
299
+ error: richV2Error(row.error, clip),
300
+ retry: retry ? compact({ attempt: num(retry.attempt), at: num(retry.at), error: richV2Error(retry.error, clip) }) : undefined,
301
+ changedFiles: changed.length ? changed : undefined,
302
+ content: v2Content(row.content, clip),
303
+ };
304
+ break;
305
+ }
306
+ case "compaction":
307
+ fields = {
308
+ status: str(row.status),
309
+ reason: str(row.reason),
310
+ summary: clip.text(str(row.summary), limits.compactionSummary),
311
+ model: richModel(row.model),
312
+ error: richV2Error(row.error, clip),
313
+ cost: num(row.cost),
314
+ tokens: richTokens(row.tokens),
315
+ };
316
+ break;
317
+ case "idle":
318
+ fields = { outcome: str(row.outcome), error: richV2Error(row.error, clip) };
319
+ break;
320
+ case "agent-switched":
321
+ fields = { agent: str(row.agent), previous: str(row.previous) };
322
+ break;
323
+ case "model-switched":
324
+ fields = { model: richModel(row.model), previous: richModel(row.previous) };
325
+ break;
326
+ case "location-switched": {
327
+ const previous = rec(row.previous);
328
+ fields = {
329
+ directory: str(rec(row.location)?.directory),
330
+ subpath: str(row.subpath),
331
+ previousDirectory: str(rec(previous?.location)?.directory),
332
+ };
333
+ break;
334
+ }
335
+ default:
336
+ break;
337
+ }
338
+ const metadata = options.includeMetadata ? clip.json(nonEmpty(rec(row.metadata)), limits.toolMetadata) : undefined;
339
+ return compact({ ...base, ...fields, metadata, truncated: clip.truncated ? true : undefined });
340
+ }
341
+ /** v1 errors are `{ name, data: { message } }`. */
342
+ function richV1Error(value, clip) {
343
+ const error = rec(value);
344
+ if (!error)
345
+ return undefined;
346
+ const data = rec(error.data);
347
+ return compact({
348
+ type: str(error.name) ?? "UnknownError",
349
+ message: clip.text(str(data?.message) ?? str(error.message), clip.limits.errorMessage),
350
+ status: num(data?.statusCode),
351
+ });
352
+ }
353
+ function v1Tool(part, clip) {
354
+ const id = str(part.callID) ?? str(part.id);
355
+ const name = str(part.tool);
356
+ const state = rec(part.state);
357
+ if (!id || !name || !state)
358
+ return null;
359
+ const rawStatus = str(state.status) ?? "unknown";
360
+ const status = rawStatus === "pending" ? "streaming" : rawStatus;
361
+ const metadata = rec(state.metadata);
362
+ const time = rec(state.time);
363
+ const files = list(state.attachments).flatMap((file) => isRecord(file) ? [fileRef(str(file.filename), str(file.mime), str(file.url))] : []);
364
+ const errorText = str(state.error);
365
+ const call = {
366
+ type: "tool",
367
+ id,
368
+ name,
369
+ status,
370
+ input: clip.json(rawStatus === "pending" && str(state.raw) ? state.raw : state.input, clip.limits.toolInput),
371
+ output: clip.text(str(state.output), clip.limits.toolOutput),
372
+ files: files.length ? files : undefined,
373
+ error: errorText !== undefined ? { type: "ToolError", message: clip.text(errorText, clip.limits.errorMessage) } : undefined,
374
+ metadata: clip.json(nonEmpty(metadata), clip.limits.toolMetadata),
375
+ childSessionId: childSessionId(name, metadata),
376
+ time: time ? compact({ ran: num(time.start), completed: num(time.end) }) : undefined,
377
+ };
378
+ return compact(call);
379
+ }
380
+ /** Maps one v1 `{ info, parts }` message into the same shape as v2. */
381
+ export function richV1Message(message, limits, options = {}) {
382
+ if (!isRecord(message))
383
+ return null;
384
+ const info = rec(message.info);
385
+ const id = str(info?.id);
386
+ const role = str(info?.role);
387
+ if (!info || !id || !role)
388
+ return null;
389
+ const clip = new Clipper(limits);
390
+ const parts = list(message.parts).filter(isRecord);
391
+ const base = { id, type: role, time: richTime(info.time) };
392
+ if (role === "user") {
393
+ const text = parts
394
+ .filter((part) => part.type === "text" && part.ignored !== true && typeof part.text === "string")
395
+ .map((part) => str(part.text) ?? "")
396
+ .join("\n\n");
397
+ const files = parts.flatMap((part) => part.type === "file" ? [fileRef(str(part.filename), str(part.mime), str(part.url))] : []);
398
+ const agents = parts.flatMap((part) => (part.type === "agent" && typeof part.name === "string" ? [part.name] : []));
399
+ return compact({
400
+ ...base,
401
+ text: clip.text(text, limits.text),
402
+ files: files.length ? files : undefined,
403
+ agents: agents.length ? agents : undefined,
404
+ truncated: clip.truncated ? true : undefined,
405
+ });
406
+ }
407
+ const content = [];
408
+ const changed = new Set();
409
+ for (const part of parts) {
410
+ if (part.type === "text" && part.ignored !== true) {
411
+ content.push(compact({
412
+ type: "text",
413
+ text: clip.text(str(part.text) ?? "", limits.text) ?? "",
414
+ synthetic: part.synthetic === true ? true : undefined,
415
+ }));
416
+ }
417
+ else if (part.type === "reasoning") {
418
+ const time = rec(part.time);
419
+ content.push(compact({
420
+ type: "reasoning",
421
+ text: clip.text(str(part.text) ?? "", limits.reasoning) ?? "",
422
+ time: time ? compact({ created: num(time.start), completed: num(time.end) }) : undefined,
423
+ }));
424
+ }
425
+ else if (part.type === "tool") {
426
+ const tool = v1Tool(part, clip);
427
+ if (tool)
428
+ content.push(tool);
429
+ }
430
+ else if (part.type === "file") {
431
+ content.push({ type: "file", file: fileRef(str(part.filename), str(part.mime), str(part.url)) });
432
+ }
433
+ else if (part.type === "patch") {
434
+ for (const file of list(part.files))
435
+ if (typeof file === "string")
436
+ changed.add(file);
437
+ }
438
+ }
439
+ const model = str(info.modelID) && str(info.providerID)
440
+ ? compact({ providerId: str(info.providerID) ?? "", modelId: str(info.modelID) ?? "", variant: str(info.variant) })
441
+ : undefined;
442
+ return compact({
443
+ ...base,
444
+ agent: str(info.agent) ?? str(info.mode),
445
+ model,
446
+ finish: str(info.finish),
447
+ cost: num(info.cost),
448
+ tokens: richTokens(info.tokens),
449
+ error: richV1Error(info.error, clip),
450
+ changedFiles: changed.size ? [...changed] : undefined,
451
+ content: budgetTools(content, clip),
452
+ metadata: options.includeMetadata ? clip.json(nonEmpty(rec(info.metadata)), limits.toolMetadata) : undefined,
453
+ truncated: clip.truncated ? true : undefined,
454
+ });
455
+ }
456
+ /**
457
+ * The newest (from end) or oldest (from start) messages that fit the result
458
+ * budget, in chronological order. Always keeps at least one message.
459
+ */
460
+ export function fitSessionReadBudget(messages, from, budget = SESSION_READ_RESULT_BUDGET) {
461
+ const ordered = from === "end" ? [...messages].reverse() : messages;
462
+ const kept = [];
463
+ let used = 0;
464
+ for (const message of ordered) {
465
+ const size = JSON.stringify(message).length;
466
+ if (kept.length > 0 && used + size > budget)
467
+ break;
468
+ kept.push(message);
469
+ used += size;
470
+ }
471
+ return {
472
+ messages: from === "end" ? kept.reverse() : kept,
473
+ omittedForSize: messages.length - kept.length,
474
+ };
475
+ }