@giovannijecha/jecode 0.8.4 → 0.8.6

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 (99) hide show
  1. package/README.md +28 -9
  2. package/dist/accounts.js +47 -10
  3. package/dist/atomic.js +24 -14
  4. package/dist/batch-view.js +27 -2
  5. package/dist/batch.js +39 -4
  6. package/dist/bounded-file.js +212 -0
  7. package/dist/cli-info.js +0 -1
  8. package/dist/commands.js +2 -0
  9. package/dist/config.js +16 -7
  10. package/dist/context/automatic.js +35 -0
  11. package/dist/context/compactor.js +32 -2
  12. package/dist/context/manual.js +20 -3
  13. package/dist/context/request-projection.js +130 -0
  14. package/dist/controller-request.js +33 -11
  15. package/dist/credential-commands.js +25 -9
  16. package/dist/credentials.js +56 -18
  17. package/dist/directory-anchor.js +91 -0
  18. package/dist/file-identity.js +12 -0
  19. package/dist/model-command.js +5 -4
  20. package/dist/openai-account-command.js +23 -10
  21. package/dist/openai-account.js +7 -5
  22. package/dist/openai-oauth-callback.js +13 -4
  23. package/dist/openai-oauth-tokens.js +9 -7
  24. package/dist/openai-oauth.js +8 -6
  25. package/dist/permission-command.js +1 -1
  26. package/dist/process-lease.js +329 -0
  27. package/dist/provider-commands.js +11 -37
  28. package/dist/provider-errors.js +31 -7
  29. package/dist/provider-label.js +9 -3
  30. package/dist/providers/anthropic-stream.js +4 -1
  31. package/dist/providers/anthropic-wire.js +8 -3
  32. package/dist/providers/anthropic.js +39 -20
  33. package/dist/providers/catalog.js +4 -4
  34. package/dist/providers/failure.js +181 -0
  35. package/dist/providers/http.js +82 -23
  36. package/dist/providers/index.js +1 -5
  37. package/dist/providers/ollama-context.js +42 -0
  38. package/dist/providers/ollama-endpoint.js +7 -34
  39. package/dist/providers/ollama-stream.js +5 -1
  40. package/dist/providers/ollama.js +36 -158
  41. package/dist/providers/openai-codex.js +71 -45
  42. package/dist/providers/openai-stream.js +26 -2
  43. package/dist/providers/openai.js +51 -25
  44. package/dist/providers/sse.js +52 -8
  45. package/dist/request-identity.js +32 -0
  46. package/dist/sessions/bucket.js +55 -0
  47. package/dist/sessions/catalog-io.js +162 -0
  48. package/dist/sessions/catalog.js +3 -1
  49. package/dist/sessions/codec-messages.js +122 -0
  50. package/dist/sessions/codec-transcript.js +93 -0
  51. package/dist/sessions/codec-values.js +52 -0
  52. package/dist/sessions/codec.js +4 -257
  53. package/dist/sessions/files.js +158 -0
  54. package/dist/sessions/lease.js +132 -49
  55. package/dist/sessions/load.js +90 -0
  56. package/dist/sessions/runtime.js +15 -8
  57. package/dist/sessions/snapshot.js +33 -0
  58. package/dist/sessions/store.js +183 -378
  59. package/dist/settings-command.js +10 -5
  60. package/dist/settings.js +75 -22
  61. package/dist/stable-directory.js +148 -0
  62. package/dist/start.js +1 -2
  63. package/dist/store-lock.js +68 -84
  64. package/dist/tools/args.js +2 -2
  65. package/dist/tools/file-read.js +192 -0
  66. package/dist/tools/file-summary.js +9 -0
  67. package/dist/tools/{fs.js → file-write.js} +5 -171
  68. package/dist/tools/glob.js +107 -0
  69. package/dist/tools/index.js +2 -1
  70. package/dist/tools/search.js +66 -205
  71. package/dist/tools/text-boundary.js +7 -33
  72. package/dist/tui/app-workflows.js +9 -334
  73. package/dist/tui/approve.js +5 -3
  74. package/dist/tui/blocks.js +8 -7
  75. package/dist/tui/command-workflow.js +106 -0
  76. package/dist/tui/components/command-menu.js +7 -10
  77. package/dist/tui/components/footer.js +1 -1
  78. package/dist/tui/components/menu.js +74 -43
  79. package/dist/tui/components/messages.js +16 -9
  80. package/dist/tui/components/tool-evidence.js +107 -0
  81. package/dist/tui/components/tool-motion.js +32 -0
  82. package/dist/tui/components/tool.js +48 -202
  83. package/dist/tui/feedback.js +4 -0
  84. package/dist/tui/help.js +1 -1
  85. package/dist/tui/picker-layout.js +40 -0
  86. package/dist/tui/picker.js +7 -71
  87. package/dist/tui/session-view.js +7 -2
  88. package/dist/tui/tool-details.js +135 -0
  89. package/dist/tui/transcript-grammar.js +8 -1
  90. package/dist/tui/transcript-view.js +26 -112
  91. package/dist/tui/turn-workflow.js +264 -0
  92. package/dist/tui/turn.js +7 -140
  93. package/dist/tui/workflow-types.js +2 -0
  94. package/dist/tui/workspace.js +21 -7
  95. package/dist/user-store.js +23 -31
  96. package/package.json +14 -15
  97. package/dist/ollama-settings-command.js +0 -74
  98. package/dist/tools/ripgrep.js +0 -230
  99. package/dist/tui/motion.js +0 -32
@@ -0,0 +1,135 @@
1
+ // Semantic tool evidence built from arguments, previews, and results.
2
+ import { graphemes } from "../text-boundary.js";
3
+ import { condense, diff } from "../ui/diff.js";
4
+ /** Unchanged rows kept either side of a change. */
5
+ const CONTEXT = 2;
6
+ /** The argument worth showing: the thing the call acts on. */
7
+ export function toolTarget(input) {
8
+ const { path, command } = input;
9
+ if (typeof command === "string")
10
+ return command;
11
+ if (typeof path === "string")
12
+ return path;
13
+ const rest = JSON.stringify(input);
14
+ return rest === "{}" ? "" : rest;
15
+ }
16
+ /**
17
+ * What the call is about to do, drawn before it is allowed to do it.
18
+ *
19
+ * The tool is asked first, because only it knows what is already on disk: a
20
+ * write against an existing file is a replacement, and showing it as a page of
21
+ * additions hides exactly the part worth approving. The fallback diffs what is
22
+ * in the arguments, which is all there is when a tool has nothing to say.
23
+ */
24
+ export function previewDetails(call, look) {
25
+ if (look !== undefined)
26
+ return changes(look.before, look.after);
27
+ const input = call.input;
28
+ if (call.name === "write_file" && typeof input.content === "string") {
29
+ return changes("", input.content);
30
+ }
31
+ if (call.name === "edit_file" && typeof input.old_text === "string") {
32
+ return changes(input.old_text, typeof input.new_text === "string" ? input.new_text : "");
33
+ }
34
+ return undefined;
35
+ }
36
+ /** Two texts as the rows of their difference, unchanged runs summed up. */
37
+ function changes(before, after) {
38
+ let oldLine = 1;
39
+ let newLine = 1;
40
+ const rows = [];
41
+ for (const changed of condense(diff(before, after), CONTEXT)) {
42
+ if (changed.kind === "gap") {
43
+ rows.push({ kind: "gap", text: `… ${changed.skipped} unchanged` });
44
+ oldLine += changed.skipped;
45
+ newLine += changed.skipped;
46
+ continue;
47
+ }
48
+ if (changed.kind === "keep") {
49
+ rows.push({ kind: "keep", text: tabs(changed.text), oldLine, newLine });
50
+ oldLine++;
51
+ newLine++;
52
+ continue;
53
+ }
54
+ if (changed.kind === "del") {
55
+ rows.push({ kind: "del", text: tabs(changed.text), oldLine });
56
+ oldLine++;
57
+ continue;
58
+ }
59
+ rows.push({ kind: "add", text: tabs(changed.text), newLine });
60
+ newLine++;
61
+ }
62
+ emphasizePairs(rows);
63
+ return rows.length === 0 ? undefined : rows;
64
+ }
65
+ function emphasizePairs(rows) {
66
+ for (let index = 0; index < rows.length - 1; index++) {
67
+ const removed = rows[index];
68
+ const added = rows[index + 1];
69
+ if (removed?.kind !== "del" || added?.kind !== "add")
70
+ continue;
71
+ if (rows[index - 1]?.kind === "del" || rows[index + 2]?.kind === "add")
72
+ continue;
73
+ const removedClusters = graphemes(removed.text);
74
+ const addedClusters = graphemes(added.text);
75
+ let prefix = 0;
76
+ let start = 0;
77
+ while (prefix < removedClusters.length &&
78
+ prefix < addedClusters.length &&
79
+ removedClusters[prefix] === addedClusters[prefix]) {
80
+ start += removedClusters[prefix].length;
81
+ prefix++;
82
+ }
83
+ let suffix = 0;
84
+ let removedSuffix = 0;
85
+ let addedSuffix = 0;
86
+ while (suffix < removedClusters.length - prefix &&
87
+ suffix < addedClusters.length - prefix &&
88
+ removedClusters[removedClusters.length - 1 - suffix] ===
89
+ addedClusters[addedClusters.length - 1 - suffix]) {
90
+ removedSuffix += removedClusters[removedClusters.length - 1 - suffix].length;
91
+ addedSuffix += addedClusters[addedClusters.length - 1 - suffix].length;
92
+ suffix++;
93
+ }
94
+ while (suffix > 0 &&
95
+ (!wordBoundary(removed.text, removedSuffix) || !wordBoundary(added.text, addedSuffix))) {
96
+ removedSuffix -= removedClusters[removedClusters.length - suffix].length;
97
+ addedSuffix -= addedClusters[addedClusters.length - suffix].length;
98
+ suffix--;
99
+ }
100
+ const removedLength = removed.text.length - start - removedSuffix;
101
+ const addedLength = added.text.length - start - addedSuffix;
102
+ if (removedLength > 0)
103
+ removed.emphasis = { start, length: removedLength };
104
+ if (addedLength > 0)
105
+ added.emphasis = { start, length: addedLength };
106
+ }
107
+ }
108
+ function wordBoundary(text, suffix) {
109
+ const at = text.length - suffix;
110
+ if (at <= 0 || at >= text.length)
111
+ return true;
112
+ return /\w/.test(text[at - 1]) !== /\w/.test(text[at]);
113
+ }
114
+ /** What the call left behind, for the calls whose output is worth a look. */
115
+ export function producedDetails(call, output) {
116
+ if (call.name === "run_command")
117
+ return outputDetails(output, "out");
118
+ // A read or a listing is already summed up on the right of its own row, and
119
+ // the model is about to say what was in it. Printing it twice helps nobody.
120
+ return undefined;
121
+ }
122
+ export function outputDetails(text, kind) {
123
+ const rows = split(text).map((line) => ({ kind, text: tabs(line) }));
124
+ return rows.length === 0 ? undefined : rows;
125
+ }
126
+ function split(text) {
127
+ const lines = text.replace(/\r\n?/g, "\n").split("\n");
128
+ while (lines.length > 0 && lines[lines.length - 1] === "")
129
+ lines.pop();
130
+ return lines.map(tabs);
131
+ }
132
+ // A tab is a width the terminal decides and the row measurement cannot see.
133
+ function tabs(line) {
134
+ return line.replace(/\t/g, " ");
135
+ }
@@ -1,5 +1,12 @@
1
- // One semantic margin shared by the user cue and executable tool evidence.
1
+ // Shared transcript inset and a bounded measure for model prose and tool records.
2
2
  const GUTTER = 2;
3
+ const MODEL_MEASURE = 86;
4
+ export function modelTranscriptWidth(width) {
5
+ return Math.max(8, Math.min(width - GUTTER * 2, MODEL_MEASURE));
6
+ }
7
+ export function insetTranscript(rows) {
8
+ return rows.map((line) => line === "" ? "" : `${" ".repeat(GUTTER)}${line}`);
9
+ }
3
10
  export function transcriptGutter(_width) {
4
11
  return GUTTER;
5
12
  }
@@ -1,6 +1,7 @@
1
1
  // Incremental transcript layout for long-running sessions.
2
+ import { hasColor } from "../ui/render.js";
3
+ import { runningTool } from "./components/tool-motion.js";
2
4
  import { render } from "./blocks.js";
3
- import { TOOL_BIRTH_MS, TOOL_LEADER_MAX_MS, TOOL_ROW_ARRIVAL_MS, TOOL_SETTLE_MS, } from "./motion.js";
4
5
  const MAX_LAYOUTS = 2;
5
6
  const REFLOW_BLOCKS_PER_FRAME = 128;
6
7
  /**
@@ -13,18 +14,13 @@ const REFLOW_BLOCKS_PER_FRAME = 128;
13
14
  */
14
15
  export function transcriptRenderer(draw = render, clock = Date.now) {
15
16
  let layouts = [];
16
- const motions = new WeakMap();
17
- const activeMotion = new Set();
17
+ const activeTools = new Set();
18
18
  return {
19
19
  viewport(blocks, width, height, scroll, palette, state = {}) {
20
20
  const layout = layoutFor(blocks, width, palette);
21
- const now = state.now ?? clock();
22
- if (state.reducedMotion === true) {
23
- discardSuppressedMotion(layout);
24
- }
25
- else if (scroll === 0) {
26
- invalidateMovingEntries(layout, now);
27
- }
21
+ state = { ...state, now: state.now ?? clock() };
22
+ if (scroll === 0)
23
+ invalidateRunningEntries(layout);
28
24
  // Reflowing rows below a scroll-locked viewport would move the content
29
25
  // being read as estimates become exact. Visible rows still resolve on
30
26
  // demand; background work resumes when the user follows the tail again.
@@ -35,15 +31,19 @@ export function transcriptRenderer(draw = render, clock = Date.now) {
35
31
  rows: visibleRows(layout, window, Math.max(0, height)),
36
32
  maxScroll: window.maxScroll,
37
33
  pending: scroll === 0 && layout.pending > 0,
38
- animating: scroll === 0 && state.reducedMotion !== true && hasMovingEntry(layout, now),
34
+ animating: scroll === 0 && state.reducedMotion !== true && hasColor() && hasRunningEntry(layout, window),
39
35
  };
40
36
  },
41
37
  invalidate(block) {
42
38
  if (block === undefined) {
43
39
  layouts = [];
40
+ activeTools.clear();
44
41
  return;
45
42
  }
46
- observeMotion(block, clock());
43
+ if (runningTool(block))
44
+ activeTools.add(block);
45
+ else
46
+ activeTools.delete(block);
47
47
  for (const layout of layouts) {
48
48
  const index = layout.positions.get(block);
49
49
  if (index === undefined)
@@ -95,6 +95,8 @@ export function transcriptRenderer(draw = render, clock = Date.now) {
95
95
  const rowCount = seeded?.block === block ? seeded.rowCount : estimatedRows(block);
96
96
  layout.entries.push({ block, rowCount });
97
97
  layout.positions.set(block, index);
98
+ if (runningTool(block))
99
+ activeTools.add(block);
98
100
  layout.pending++;
99
101
  total += rowCount;
100
102
  layout.ends.push(total);
@@ -138,7 +140,6 @@ export function transcriptRenderer(draw = render, clock = Date.now) {
138
140
  entry.rows = draw(entry.block, layout.width, layout.palette, {
139
141
  ...state,
140
142
  previous: layout.entries[index - 1]?.block,
141
- motion: motions.get(entry.block),
142
143
  });
143
144
  entry.rowCount = entry.rows.length;
144
145
  layout.pending--;
@@ -188,115 +189,28 @@ export function transcriptRenderer(draw = render, clock = Date.now) {
188
189
  }
189
190
  layout.next = Math.max(layout.next, index);
190
191
  }
191
- function observeMotion(block, now) {
192
- if (block.kind !== "tool")
193
- return;
194
- let motion = motions.get(block);
195
- // A settled historical block may be invalidated by Ctrl+O. It should not
196
- // replay its original arrival animation after resume.
197
- if (motion === undefined) {
198
- if (block.tone !== "pending")
199
- return;
200
- motion = {
201
- bornAt: now,
202
- rowsAt: (block.body ?? []).map(() => now),
203
- rowKeys: (block.body ?? []).map(detailKey),
204
- tone: block.tone,
205
- };
206
- motions.set(block, motion);
207
- activeMotion.add(block);
208
- return;
209
- }
210
- if (motion.tone === "pending" && block.tone !== "pending")
211
- motion.settledAt = now;
212
- motion.tone = block.tone;
213
- reconcileRows(motion, block.body ?? [], now);
214
- activeMotion.add(block);
215
- }
216
- function invalidateMovingEntries(layout, now) {
217
- for (const block of activeMotion) {
192
+ function invalidateRunningEntries(layout) {
193
+ for (const block of activeTools) {
218
194
  const index = layout.positions.get(block);
219
- if (index === undefined) {
220
- activeMotion.delete(block);
221
- continue;
222
- }
223
- const motion = motions.get(block);
224
- if (motion === undefined || !moving(block, motion, now)) {
225
- // Paint the resting state once before leaving the motion registry;
226
- // otherwise the cache could retain the final in-between frame.
227
- dirty(layout, index);
228
- activeMotion.delete(block);
195
+ if (index === undefined || !runningTool(block)) {
196
+ activeTools.delete(block);
197
+ if (index !== undefined)
198
+ dirty(layout, index);
229
199
  continue;
230
200
  }
201
+ // Clock-driven repaints keep elapsed time current even without motion.
231
202
  dirty(layout, index);
232
203
  }
233
204
  }
234
- function hasMovingEntry(layout, now) {
235
- for (const block of activeMotion) {
236
- if (layout.positions.get(block) === undefined)
237
- continue;
238
- const motion = motions.get(block);
239
- if (motion !== undefined && moving(block, motion, now))
205
+ function hasRunningEntry(layout, window) {
206
+ for (const block of activeTools) {
207
+ const index = layout.positions.get(block);
208
+ if (index !== undefined && index >= window.first && index <= window.last &&
209
+ runningTool(block) && block.expanded !== true)
240
210
  return true;
241
211
  }
242
212
  return false;
243
213
  }
244
- function discardSuppressedMotion(layout) {
245
- for (const block of activeMotion) {
246
- if (layout.positions.get(block) !== undefined && block.kind === "tool" && block.tone === "pending") {
247
- continue;
248
- }
249
- activeMotion.delete(block);
250
- motions.delete(block);
251
- }
252
- }
253
- }
254
- function reconcileRows(motion, details, now) {
255
- const available = new Map();
256
- for (let index = 0; index < motion.rowKeys.length; index++) {
257
- const key = motion.rowKeys[index];
258
- if (key === undefined)
259
- continue;
260
- const bucket = available.get(key) ?? { values: [], next: 0 };
261
- bucket.values.push(motion.rowsAt[index] ?? motion.bornAt);
262
- available.set(key, bucket);
263
- }
264
- const rowKeys = details.map(detailKey);
265
- const rowsAt = rowKeys.map((key) => {
266
- const bucket = available.get(key);
267
- if (bucket === undefined || bucket.next >= bucket.values.length)
268
- return now;
269
- const value = bucket.values[bucket.next] ?? now;
270
- bucket.next++;
271
- return value;
272
- });
273
- motion.rowKeys = rowKeys;
274
- motion.rowsAt = rowsAt;
275
- }
276
- function detailKey(detail) {
277
- if (detail.kind === "out" || detail.kind === "gap") {
278
- return JSON.stringify([detail.kind, detail.text]);
279
- }
280
- return JSON.stringify([
281
- detail.kind,
282
- detail.oldLine ?? "",
283
- detail.newLine ?? "",
284
- detail.emphasis?.start ?? "",
285
- detail.emphasis?.length ?? "",
286
- detail.text,
287
- ]);
288
- }
289
- function moving(block, motion, now) {
290
- if (block.kind === "tool" && block.tone === "pending" &&
291
- block.startedAt !== undefined && block.right === "running")
292
- return true;
293
- let until = motion.bornAt + Math.max(TOOL_BIRTH_MS, TOOL_LEADER_MAX_MS);
294
- if (motion.settledAt !== undefined)
295
- until = Math.max(until, motion.settledAt + TOOL_SETTLE_MS);
296
- for (const arrivedAt of motion.rowsAt) {
297
- until = Math.max(until, arrivedAt + TOOL_ROW_ARRIVAL_MS);
298
- }
299
- return now < until;
300
214
  }
301
215
  function compatible(layout, blocks) {
302
216
  return layout.source === blocks &&
@@ -0,0 +1,264 @@
1
+ // One model turn, including steering, compaction, durable settlement, and recovery.
2
+ import { runTurn } from "../controller.js";
3
+ import { resolveContextPolicy } from "../context/capacity.js";
4
+ import { automaticCompactionKey } from "../context/automatic.js";
5
+ import { compactContext } from "../context/compactor.js";
6
+ import { isContextOverflow } from "../context/policy.js";
7
+ import { steeringInbox } from "../steering.js";
8
+ import { recordAuxiliaryUsage, recordRequestInput, recordUsage } from "../usage.js";
9
+ import { toolSpecs } from "../tools/index.js";
10
+ import { requestIdentityForSession } from "../request-identity.js";
11
+ import { transition } from "./activity.js";
12
+ import { answerAt } from "./approve.js";
13
+ import * as edit from "./editor.js";
14
+ import { controllerOptions, turnFailure } from "./session-view.js";
15
+ import { transcribe } from "./turn.js";
16
+ const WAITING = "Waiting";
17
+ export function turnWorkflow(options, automaticCompaction) {
18
+ const { session, state, permissions, feedback } = options;
19
+ let activeSteering;
20
+ async function turn(text) {
21
+ const activity = options.startActivity("turn", WAITING);
22
+ if (activity === undefined)
23
+ return;
24
+ const inbox = steeringInbox((pending, accepting) => {
25
+ if (activeSteering !== inbox)
26
+ return;
27
+ state.steering = accepting ? pending : undefined;
28
+ options.render();
29
+ });
30
+ activeSteering = inbox;
31
+ state.steering = 0;
32
+ const status = (label) => transition(activity, label);
33
+ const parentId = session.conversation.activeNodeId;
34
+ const history = session.conversation.history;
35
+ const modelHistory = session.conversation.contextHistory;
36
+ const historyStart = history.length;
37
+ const blockStart = state.blocks.length;
38
+ const createdAt = new Date().toISOString();
39
+ const prospectiveNodeId = session.conversation.nodes.length + 1;
40
+ let nodeId;
41
+ let context;
42
+ const unpersistedSteering = [];
43
+ const turnTools = permissions.availableTools();
44
+ const specs = toolSpecs(turnTools);
45
+ let firstPolicy = true;
46
+ const policy = () => {
47
+ let visible = firstPolicy;
48
+ firstPolicy = false;
49
+ if (visible) {
50
+ status("Checking context");
51
+ options.render();
52
+ }
53
+ return resolveContextPolicy({
54
+ provider: session.provider,
55
+ model: session.model,
56
+ compactionPercent: session.config.compactionPercent,
57
+ signal: activity.control.signal,
58
+ onStatus: (said) => {
59
+ visible = true;
60
+ status(said);
61
+ options.render();
62
+ },
63
+ }).finally(() => {
64
+ if (visible) {
65
+ status(WAITING);
66
+ options.render();
67
+ }
68
+ });
69
+ };
70
+ options.emit({ kind: "user", text });
71
+ const user = { role: "user", content: [{ kind: "text", text }] };
72
+ history.push(user);
73
+ modelHistory.push(structuredClone(user));
74
+ const events = transcribe({
75
+ emit: options.emit,
76
+ render: options.render,
77
+ palette: session.palette,
78
+ approved: (call) => permissions.approved(call),
79
+ remember: (call) => permissions.remember(call),
80
+ ask: (prompt, settle) => {
81
+ state.open = { picker: prompt, settle: (index) => settle(answerAt(index)) };
82
+ options.render();
83
+ },
84
+ status: (text) => {
85
+ status(text);
86
+ },
87
+ usage: (usage) => recordUsage(session.usage, usage),
88
+ requestInput: (inputTokens) => recordRequestInput(session.usage, inputTokens),
89
+ });
90
+ const persist = async (checkpoint, settlement, failure) => {
91
+ const next = session.conversation.commit({
92
+ ...(nodeId === undefined ? {} : { nodeId }),
93
+ parentId,
94
+ createdAt,
95
+ identity: {
96
+ providerId: session.provider.id,
97
+ model: session.model,
98
+ effort: session.config.effort,
99
+ },
100
+ messages: checkpoint.slice(historyStart),
101
+ blocks: state.blocks.slice(blockStart),
102
+ ...(context === undefined ? {} : { context }),
103
+ ...(failure === undefined ? {} : { failure }),
104
+ }, settlement);
105
+ await session.persistence?.checkpoint(next);
106
+ session.conversation = next;
107
+ nodeId = next.activeNodeId;
108
+ state.committedNodeId = next.activeNodeId;
109
+ unpersistedSteering.length = 0;
110
+ };
111
+ const compact = async (checkpoint, projected, request) => {
112
+ if (request.reason === "overflow" &&
113
+ (request.error === undefined || !isContextOverflow(request.error))) {
114
+ return undefined;
115
+ }
116
+ const force = request.reason === "overflow" || request.projectionSaturated;
117
+ const key = automaticCompactionKey(session.provider.id, session.model, nodeId ?? prospectiveNodeId, checkpoint.length);
118
+ const attempt = { key, reason: request.reason };
119
+ if (!automaticCompaction.allows(attempt))
120
+ return undefined;
121
+ let attempted = false;
122
+ const result = await compactContext({
123
+ provider: session.provider,
124
+ model: session.model,
125
+ effort: session.config.effort,
126
+ context: projected,
127
+ turn: checkpoint.slice(historyStart),
128
+ nodeId: nodeId ?? prospectiveNodeId,
129
+ coveredMessages: context?.messageCount ?? 0,
130
+ lastInputTokens: Math.max(session.usage.lastInputTokens, request.inputTokens),
131
+ estimatedInputTokens: request.inputTokens,
132
+ signal: activity.control.signal,
133
+ force,
134
+ policy: request.policy,
135
+ requestEnvelope: {
136
+ system: session.system,
137
+ tools: specs,
138
+ maxOutputTokens: session.config.maxTokens,
139
+ },
140
+ requestIdentity: requestIdentityForSession(session),
141
+ onBegin: () => {
142
+ attempted = true;
143
+ status("Compacting");
144
+ options.render();
145
+ },
146
+ onEnd: () => {
147
+ status(WAITING);
148
+ options.render();
149
+ },
150
+ });
151
+ if (result === undefined) {
152
+ if (attempted && !activity.control.signal.aborted)
153
+ automaticCompaction.failed(attempt);
154
+ return undefined;
155
+ }
156
+ automaticCompaction.succeeded(attempt);
157
+ context = result.anchor;
158
+ if (result.usage !== undefined)
159
+ recordAuxiliaryUsage(session.usage, result.usage);
160
+ return result.messages;
161
+ };
162
+ events.onContext = compact;
163
+ events.onSteering = (guidance) => {
164
+ unpersistedSteering.push(guidance);
165
+ options.emit({ kind: "user", text: guidance });
166
+ options.render();
167
+ };
168
+ events.onCheckpoint = async (checkpoint, settlement, projected) => {
169
+ await persist(checkpoint, settlement);
170
+ const compacted = await compact(checkpoint, projected, {
171
+ reason: "budget",
172
+ policy: await policy(),
173
+ inputTokens: session.usage.lastInputTokens,
174
+ projectionSaturated: false,
175
+ });
176
+ if (compacted !== undefined)
177
+ await persist(checkpoint, settlement);
178
+ return compacted;
179
+ };
180
+ let finishReason;
181
+ let failed;
182
+ try {
183
+ await runTurn(history, controllerOptions(session, policy, turnTools, inbox), events, activity.control.signal, modelHistory);
184
+ }
185
+ catch (error) {
186
+ const interrupted = activity.control.signal.aborted;
187
+ const completed = nodeId !== undefined && session.conversation.activeNodeId === nodeId &&
188
+ session.conversation.activeNode?.settlement === "completed";
189
+ if (completed) {
190
+ const notice = turnFailure(session, error, interrupted);
191
+ feedback.show({ text: notice.text, tone: notice.tone, timeoutMs: 6_000 });
192
+ }
193
+ else {
194
+ finishReason = interrupted ? "interrupted" : "failed";
195
+ failed = { error: error, interrupted };
196
+ }
197
+ }
198
+ finally {
199
+ let pendingSteering = inbox.close();
200
+ if (activeSteering === inbox)
201
+ activeSteering = undefined;
202
+ state.steering = undefined;
203
+ try {
204
+ events.finish(finishReason);
205
+ if (failed !== undefined) {
206
+ const notice = turnFailure(session, failed.error, failed.interrupted);
207
+ const settlement = failed.interrupted ? "interrupted" : "failed";
208
+ const failure = {
209
+ text: notice.text,
210
+ tone: failed.interrupted ? "warn" : "error",
211
+ };
212
+ options.emit(notice);
213
+ try {
214
+ await persist(closeFailedTurn(history, settlement), settlement, failure);
215
+ }
216
+ catch (error) {
217
+ // A failed persistence boundary cannot remain visible as if it had
218
+ // been saved. Revert to the last durable path and return the input
219
+ // to the composer so the user can retry without losing it.
220
+ options.replaceTranscript();
221
+ state.editor = edit.of([
222
+ ...(nodeId === undefined ? [text] : []),
223
+ ...unpersistedSteering,
224
+ ...pendingSteering,
225
+ state.editor.text,
226
+ ].filter((part) => part !== "").join("\n\n"));
227
+ state.completing = undefined;
228
+ pendingSteering = [];
229
+ feedback.show({
230
+ text: error.message,
231
+ tone: "error",
232
+ timeoutMs: 6_000,
233
+ });
234
+ }
235
+ }
236
+ }
237
+ finally {
238
+ restorePendingSteering(state, pendingSteering);
239
+ options.finishActivity(activity);
240
+ }
241
+ }
242
+ }
243
+ function steer(text) {
244
+ return activeSteering?.offer(text) ?? "unavailable";
245
+ }
246
+ return { turn, steer };
247
+ }
248
+ function restorePendingSteering(state, messages) {
249
+ if (messages.length === 0)
250
+ return;
251
+ const pending = messages.join("\n\n");
252
+ state.editor = edit.of(state.editor.text === "" ? pending : `${pending}\n\n${state.editor.text}`);
253
+ state.completing = undefined;
254
+ }
255
+ function closeFailedTurn(history, settlement) {
256
+ const closed = [...history];
257
+ if (closed.at(-1)?.role === "assistant")
258
+ return closed;
259
+ const text = settlement === "interrupted"
260
+ ? "The previous attempt was interrupted by the user before completion."
261
+ : "The previous attempt failed before completion.";
262
+ closed.push({ role: "assistant", content: [{ kind: "text", text }] });
263
+ return closed;
264
+ }