@0perator/operator 0.2.2-next.1 → 0.2.4
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/autonomy/index.js +14 -5
- package/dist/autonomy/session-factory.js +7 -1
- package/dist/cli.js +90 -19
- package/dist/config/features.js +7 -0
- package/dist/config/settings.js +17 -0
- package/dist/engine/agent.js +3 -0
- package/dist/engine/aurora.js +51 -12
- package/dist/engine/compaction.js +8 -1
- package/dist/engine/messages.js +5 -0
- package/dist/engine/native-vision-node.js +88 -10
- package/dist/engine/native-vision.js +25 -7
- package/dist/engine/rolling-summary.js +3 -2
- package/dist/engine/router-adapter.js +1 -0
- package/dist/engine/speed-compaction.js +7 -0
- package/dist/engine/token-meter.js +1 -1
- package/dist/products/voice.js +44 -9
- package/dist/router/activation.js +132 -0
- package/dist/router/discovery.js +4 -3
- package/dist/router/model-list.js +79 -0
- package/dist/router/models.js +12 -1
- package/dist/router/router.js +0 -11
- package/dist/session.js +215 -28
- package/dist/tools/executor.js +17 -3
- package/dist/tools/micro-assist.js +105 -0
- package/dist/tools/read-ledger.js +4 -0
- package/dist/tools/registry.js +65 -58
- package/dist/tools/sandbox.js +1 -1
- package/dist/tools/semantic-compress.js +1 -9
- package/dist/tools/tool-output-spill.js +1 -1
- package/dist/ui/activationFlow.js +126 -0
- package/dist/ui/modelPicker.js +12 -7
- package/package.json +1 -1
package/dist/session.js
CHANGED
|
@@ -6,16 +6,19 @@ import { recordTruncation } from "./observability/blackbox.js";
|
|
|
6
6
|
import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
|
|
7
7
|
import { scratchDirFor } from "./config/scratch.js";
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
|
-
import { detectVision, markVisionRejected } from "./engine/native-vision.js";
|
|
10
|
-
import {
|
|
9
|
+
import { detectVision, markVisionRejected, visionRejected } from "./engine/native-vision.js";
|
|
10
|
+
import { voiceConfig, withTranscripts } from "./products/voice.js";
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
import { extractAudioPaths, extractImagePaths, extractVideoPaths } from "./engine/native-vision-node.js";
|
|
11
13
|
import { planFanOut } from "./engine/fanout.js";
|
|
12
14
|
import { withCodeActDelegateSchema } from "./moa/codeact-lane.js";
|
|
13
15
|
import { codeActEnabled } from "./moa/codeact.js";
|
|
16
|
+
import { effortFor } from "./router/models.js";
|
|
14
17
|
import { chat, health, reachable, gateKey, isRemoteBase, shipsLlamaCacheKnobs, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
|
|
15
18
|
import { claimSlot, releaseSlot } from "./engine/kv-slot.js";
|
|
16
19
|
import { randomUUID } from "node:crypto";
|
|
17
|
-
import { recordDecodeSample, speedCompactionDue } from "./engine/speed-compaction.js";
|
|
18
|
-
import { compact, compactionSplit, fitToWindow, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail } from "./engine/compaction.js";
|
|
20
|
+
import { recordDecodeSample, speedCompactionDue, SPEED_REARM_TOKENS } from "./engine/speed-compaction.js";
|
|
21
|
+
import { compact, compactionSplit, fitToWindow, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, archiveEvicted, defaultThreshold, fixedRequestTokens } from "./engine/compaction.js";
|
|
19
22
|
import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
|
|
20
23
|
import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
|
|
21
24
|
import { engineRouter } from "./engine/router-adapter.js";
|
|
@@ -35,7 +38,7 @@ import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0
|
|
|
35
38
|
import { AuroraRouter } from "./router/router.js";
|
|
36
39
|
import { operatorAgentPersona } from "./config/operator-harness.js";
|
|
37
40
|
import { progressDeadline, summaryCeilingMs, DeadlineError } from "./engine/progress-deadline.js";
|
|
38
|
-
import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, CHAIN_MODEL_ID, LEAN_HARNESS_CTX, resolveModel } from "./router/models.js";
|
|
41
|
+
import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, CHAIN_MODEL_ID, LEAN_HARNESS_CTX, resolveModel, isRetired } from "./router/models.js";
|
|
39
42
|
import { probeServed, usableCtx } from "./router/discovery.js";
|
|
40
43
|
import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
|
|
41
44
|
import { askFrontDoor, recentTurns } from "./engine/front-door.js";
|
|
@@ -44,6 +47,7 @@ import { Executor } from "./tools/executor.js";
|
|
|
44
47
|
import { autoDeliverReport, autoDeliverFailure, wakeRoot } from "./bus/inbox.js";
|
|
45
48
|
import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, mdocToolsFor, craftToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
|
|
46
49
|
import { isFeatureEnabled } from "./config/features.js";
|
|
50
|
+
import { createMicroAssist } from "./tools/micro-assist.js";
|
|
47
51
|
import { MemoryStore } from "./memory/index.js";
|
|
48
52
|
import { McpHub, withMcp } from "./mcp/index.js";
|
|
49
53
|
import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
|
|
@@ -461,6 +465,12 @@ export class Session {
|
|
|
461
465
|
compactionThreshold;
|
|
462
466
|
compactionCeilingTokens;
|
|
463
467
|
compactionMinDecodeTps;
|
|
468
|
+
compactionSpeedTargetTokens;
|
|
469
|
+
speedRearmAt; // the speed target was missed: no speed compaction below this request size
|
|
470
|
+
speedMissTold = false;
|
|
471
|
+
compactionSummaryModel;
|
|
472
|
+
summaryModelTold = false;
|
|
473
|
+
summarySlots = new Map(); // background slots claimed for the summary model, apart from kvSlots
|
|
464
474
|
decodeSamples = []; // the last measured turns' decode, for the speed trigger
|
|
465
475
|
fallbackModelId; // settings.fallbackModel (turnModel)
|
|
466
476
|
background;
|
|
@@ -485,11 +495,16 @@ export class Session {
|
|
|
485
495
|
planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
|
|
486
496
|
planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
|
|
487
497
|
thinkMode = "off"; // /think, /ultrathink — extended reasoning
|
|
498
|
+
efforts;
|
|
499
|
+
voice;
|
|
488
500
|
recalled = false;
|
|
489
501
|
activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
|
|
490
502
|
activeSkillName = ""; // name of the active skill (for status display)
|
|
491
503
|
skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
|
|
492
504
|
referenceNote = ""; // one-shot quoted third-party text for the owner's next message (referenceOnce)
|
|
505
|
+
microRecall; // `microAssist`: unset once the session's one search has run
|
|
506
|
+
memoryNote = ""; // its hits, appended after the owner's words in that one message
|
|
507
|
+
unpromptedTools; // the assist's own calls: gatedTools with nobody to ask
|
|
493
508
|
// Rolling summarizer (engine/rolling-summary.ts): bounded background passes keep a summary of the conversation so
|
|
494
509
|
// far, so a compaction reads only the tail the summary does not cover yet.
|
|
495
510
|
rollingSummarizer;
|
|
@@ -574,6 +589,13 @@ export class Session {
|
|
|
574
589
|
if (dt && cfg.moa && codeActEnabled(cfg.moa.codeact))
|
|
575
590
|
reg.set("delegate_task", withCodeActDelegateSchema(dt));
|
|
576
591
|
this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
|
|
592
|
+
if (isFeatureEnabled("microAssist", { features: cfg.features })) {
|
|
593
|
+
const hub = () => this.hub && { has: (n) => this.hub.has(n), call: (n, a) => this.unpromptedTools.execute(n, a) };
|
|
594
|
+
const micro = createMicroAssist({ hub, task: () => this.lastRequest });
|
|
595
|
+
this.executor.assist = micro.result;
|
|
596
|
+
if (!cfg.background)
|
|
597
|
+
this.microRecall = micro.recall;
|
|
598
|
+
}
|
|
577
599
|
this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
|
|
578
600
|
this.localSchemas = toSchemas(reg);
|
|
579
601
|
// Main sessions only: a sub-agent's prompt (subagentSystemPrompt) lists its tools as attached, and a role's
|
|
@@ -584,6 +606,8 @@ export class Session {
|
|
|
584
606
|
this.inner = cfg.router ?? new AuroraRouter();
|
|
585
607
|
this.router = this.wrap(this.inner);
|
|
586
608
|
this.chain = cfg.router;
|
|
609
|
+
this.efforts = { ...cfg.reasoningEffort };
|
|
610
|
+
this.voice = cfg.voice;
|
|
587
611
|
this.models = cfg.models;
|
|
588
612
|
this.dynamicModels = cfg.dynamicModels;
|
|
589
613
|
this.registry = modelRegistry(cfg.models);
|
|
@@ -619,6 +643,8 @@ export class Session {
|
|
|
619
643
|
this.compactionThreshold = cfg.compactionThreshold;
|
|
620
644
|
this.compactionCeilingTokens = cfg.compactionCeilingTokens;
|
|
621
645
|
this.compactionMinDecodeTps = cfg.compactionMinDecodeTps;
|
|
646
|
+
this.compactionSpeedTargetTokens = cfg.compactionSpeedTargetTokens;
|
|
647
|
+
this.compactionSummaryModel = cfg.compactionSummaryModel;
|
|
622
648
|
this.fallbackModelId = cfg.fallbackModel;
|
|
623
649
|
this.contextFloor = cfg.contextFloor ?? AGENT_CTX_FLOOR;
|
|
624
650
|
this.background = cfg.background ?? false;
|
|
@@ -730,10 +756,19 @@ export class Session {
|
|
|
730
756
|
* In plan mode a read-only gated policy (no approver → mutating tools fail-safe deny) overrides the
|
|
731
757
|
* normal policy, so nothing can be modified regardless of the owner's mode/tier. */
|
|
732
758
|
buildTools() {
|
|
759
|
+
if (this.executor.assist)
|
|
760
|
+
this.unpromptedTools = this.gatedTools(); // `microAssist`'s own calls
|
|
761
|
+
const hooked = this.gatedTools(this.planMode ? undefined : this.approve, this.planMode ? undefined : this.askUser); // no approver in plan mode = hard read-only
|
|
762
|
+
if (this.nativeDeferred)
|
|
763
|
+
return withNativeDeferred(hooked, this.nativeDeferred);
|
|
764
|
+
return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
|
|
765
|
+
}
|
|
766
|
+
/** Every gate a tool call passes: hooks, delegate fence, PR preflight, permissions. With no approver and no asker, a
|
|
767
|
+
* call that needs the owner is refused instead of prompted. */
|
|
768
|
+
gatedTools(approve, ask) {
|
|
733
769
|
const policy = this.planMode
|
|
734
770
|
? new PermissionPolicy({ mode: "gated", tier: this.policy.currentTier() }) // read-only: safe tools allow, mutating ask→deny (no approve fn)
|
|
735
771
|
: this.policy;
|
|
736
|
-
const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
|
|
737
772
|
const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
|
|
738
773
|
// The PR preflight holds code from a PR Operator did not write until the owner picks host or isolation (sub-agents
|
|
739
774
|
// and headless runs: isolation or refuse). It sits under the delegate fence, so a fenced call never asks.
|
|
@@ -741,7 +776,7 @@ export class Session {
|
|
|
741
776
|
const preflighted = withPrPreflight(base, {
|
|
742
777
|
cwd, scratch: scratchDirFor(cwd), shell: this.prShell,
|
|
743
778
|
trees: () => PR_TREES.getStore() ?? this.prTrees, within: (t, fn) => PR_TREES.run(t, fn),
|
|
744
|
-
git: prGit, probe: () => probeIsolation(), ask
|
|
779
|
+
git: prGit, probe: () => probeIsolation(), ask,
|
|
745
780
|
audit: (line) => this.prAudit(line),
|
|
746
781
|
});
|
|
747
782
|
// Delegate mode's fence sits above the gate: a call it refuses never asks the owner to approve it. Off = pass-through.
|
|
@@ -751,10 +786,7 @@ export class Session {
|
|
|
751
786
|
catch {
|
|
752
787
|
return p;
|
|
753
788
|
} } });
|
|
754
|
-
|
|
755
|
-
if (this.nativeDeferred)
|
|
756
|
-
return withNativeDeferred(hooked, this.nativeDeferred);
|
|
757
|
-
return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
|
|
789
|
+
return withHooks(guarded, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
|
|
758
790
|
}
|
|
759
791
|
/** One PR preflight audit line: the event trail (when recorded) and `<operator home>/audit/pr-preflight.jsonl`. */
|
|
760
792
|
prAudit(line) {
|
|
@@ -956,7 +988,7 @@ export class Session {
|
|
|
956
988
|
// The notes are folded once over their cap, and they can never hold more than was written into them: one fold
|
|
957
989
|
// (SUMMARY_MAX_TOKENS) plus a note per pass, and a background pass reads at least dueTokens. So a short session's
|
|
958
990
|
// bound stays below the session itself instead of jumping to the cap a long one needs.
|
|
959
|
-
const b =
|
|
991
|
+
const b = this.rollBudget();
|
|
960
992
|
const passes = Math.ceil(globalTokenMeter.estimateRequestFor(this.meterKey(), this.convo.all) / b.dueTokens) + 1;
|
|
961
993
|
const summaryMax = Math.min(b.capTokens, SUMMARY_MAX_TOKENS + b.noteTokens * passes);
|
|
962
994
|
return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + summaryMax, summaryMax };
|
|
@@ -1083,7 +1115,7 @@ export class Session {
|
|
|
1083
1115
|
this.turnHandlers = undefined;
|
|
1084
1116
|
}
|
|
1085
1117
|
}
|
|
1086
|
-
async compactNowInner() {
|
|
1118
|
+
async compactNowInner(speed) {
|
|
1087
1119
|
const opts = {
|
|
1088
1120
|
ctxWindow: this.effectiveContext(),
|
|
1089
1121
|
systemPrompt: this.sys(),
|
|
@@ -1097,13 +1129,25 @@ export class Session {
|
|
|
1097
1129
|
spill: spillToolOutput, // GW-10-COMPLETE: /compact's fitToWindow OFFLOADS (re-readable), never erases
|
|
1098
1130
|
};
|
|
1099
1131
|
const before = this.requestEstimate();
|
|
1100
|
-
|
|
1132
|
+
if (speed)
|
|
1133
|
+
opts.onSkip = () => { speed.failed = true; };
|
|
1134
|
+
const evicted = compactionSplit(this.convo.all, 2)?.evicted;
|
|
1135
|
+
const compacted = await compact(this.convo.all, opts);
|
|
1136
|
+
if (speed && !speed.failed) {
|
|
1137
|
+
if (evicted?.length)
|
|
1138
|
+
archiveEvicted(compacted[0], evicted, spillToolOutput);
|
|
1139
|
+
const ratio = Math.min(opts.threshold ?? defaultThreshold(opts.ctxWindow), speed.target / opts.ctxWindow);
|
|
1140
|
+
this.convo.replaceAll(fitToWindow(compacted, { ...opts, minShedChars: 600 }, ratio));
|
|
1141
|
+
}
|
|
1142
|
+
else
|
|
1143
|
+
this.convo.replaceAll(fitToWindow(compacted, opts));
|
|
1101
1144
|
return Math.max(0, before - this.requestEstimate()); // CALIBRATED tokens freed — one basis with the bar
|
|
1102
1145
|
}
|
|
1103
1146
|
/** Reset the conversation to empty (for /new). */
|
|
1104
1147
|
reset() {
|
|
1105
1148
|
this.convo.replaceAll([]);
|
|
1106
1149
|
this.decodeSamples = [];
|
|
1150
|
+
this.clearSpeedMiss();
|
|
1107
1151
|
this.rollingSummarizer.clear(); // clear the rolling summary on new session
|
|
1108
1152
|
this.planApproval.clear(); // a fresh conversation has no reviewed plan
|
|
1109
1153
|
this.planReviewTold = false; // …and has not been told the mode
|
|
@@ -1140,6 +1184,10 @@ export class Session {
|
|
|
1140
1184
|
const dyn = this.dynamicModels?.() ?? [];
|
|
1141
1185
|
return dyn.length ? modelRegistry([...(this.models ?? []), ...dyn]) : this.registry;
|
|
1142
1186
|
}
|
|
1187
|
+
/** The row a pick of `id` would run on (aliases and retired ids followed), without selecting it. */
|
|
1188
|
+
resolveSelection(id) {
|
|
1189
|
+
return selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner).profile;
|
|
1190
|
+
}
|
|
1143
1191
|
/** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
|
|
1144
1192
|
* overrides passed in at construction, plus the dynamic rows. BYO connectors appear ONLY when their vendor
|
|
1145
1193
|
* key is connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
|
|
@@ -1178,9 +1226,28 @@ export class Session {
|
|
|
1178
1226
|
chatPath: profile.chatPath,
|
|
1179
1227
|
maxOutput: profile.maxOutput,
|
|
1180
1228
|
provider: profile.box,
|
|
1229
|
+
reasoning: this.reasoningFor(profile),
|
|
1181
1230
|
}));
|
|
1182
1231
|
return new AuroraRouter(eps);
|
|
1183
1232
|
}
|
|
1233
|
+
/** A profile's thinking knobs. The effort is read per request, so `/think <level>` applies from the next one. */
|
|
1234
|
+
reasoningFor(profile) {
|
|
1235
|
+
const efforts = () => this.efforts;
|
|
1236
|
+
return {
|
|
1237
|
+
get reasoningEffort() { return effortFor(efforts(), profile); },
|
|
1238
|
+
preserveThinking: profile.preserveThinking === true,
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
/** The active model's reasoning effort, or undefined for the server's default. */
|
|
1242
|
+
currentReasoningEffort() {
|
|
1243
|
+
return effortFor(this.efforts, findModel(this.liveRegistry(), this.modelId) ?? { id: this.modelId });
|
|
1244
|
+
}
|
|
1245
|
+
/** `/think <level>`: override the active model's effort ("default" returns to the profile's). Returns the overrides
|
|
1246
|
+
* to save. */
|
|
1247
|
+
setReasoningEffort(level) {
|
|
1248
|
+
this.efforts[this.modelId] = level; // "default" is stored too: the saved map is merged, so a removed key would return
|
|
1249
|
+
return { ...this.efforts };
|
|
1250
|
+
}
|
|
1184
1251
|
/** A turn's model as the owner reads it, and its fallback (runTurn's TurnModel): when every leg of another model
|
|
1185
1252
|
* fails, or it keeps finishing with nothing, settings.fallbackModel answers that turn (default: the router's `main`,
|
|
1186
1253
|
* never the launchd-owned Aurora row) — the owner's choice stays, so the next turn tries the chosen model first again.
|
|
@@ -1230,6 +1297,7 @@ export class Session {
|
|
|
1230
1297
|
if (error || !profile)
|
|
1231
1298
|
return { ok: false, error };
|
|
1232
1299
|
this.decodeSamples = []; // another model's rate says nothing about this one
|
|
1300
|
+
this.clearSpeedMiss();
|
|
1233
1301
|
if (profile.kind === "orchestrated" && profile.id !== WATERFALL_MODEL_ID) { // Waterfall builds its teams from gateway seats
|
|
1234
1302
|
const team = moaTeam(this.moaConfig);
|
|
1235
1303
|
if (!team)
|
|
@@ -1355,6 +1423,7 @@ export class Session {
|
|
|
1355
1423
|
loopbackAuth: leg?.loopbackAuth,
|
|
1356
1424
|
transport: leg?.transport,
|
|
1357
1425
|
chatPath: leg?.chatPath,
|
|
1426
|
+
...leg?.reasoning,
|
|
1358
1427
|
tools, // identical tools → the span prefix-matches the live turn's cached KV
|
|
1359
1428
|
maxTokens,
|
|
1360
1429
|
temperature: 0,
|
|
@@ -1417,6 +1486,51 @@ export class Session {
|
|
|
1417
1486
|
}
|
|
1418
1487
|
catch { /* handoff is a durability convenience, never a hard dependency */ }
|
|
1419
1488
|
}
|
|
1489
|
+
rollBudget() {
|
|
1490
|
+
return rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS, this.compactionSpeedTargetTokens);
|
|
1491
|
+
}
|
|
1492
|
+
/** Where compaction.summaryModel may take a background pass: its first leg on a private address that is proven to
|
|
1493
|
+
* stay there — a llama-server answering `/props` itself, or a router route marked `fleet_only` — with room for a
|
|
1494
|
+
* pass. A provider-key row, the Anthropic wire, a retired row and a gateway host never qualify: the pass carries
|
|
1495
|
+
* conversation text. Asked before every pass (a router's table reloads live). Undefined = the live endpoint. */
|
|
1496
|
+
async summaryLeg(b) {
|
|
1497
|
+
const id = this.compactionSummaryModel;
|
|
1498
|
+
if (!id)
|
|
1499
|
+
return undefined;
|
|
1500
|
+
const p = findModel(this.liveRegistry(), id);
|
|
1501
|
+
if (p?.kind !== "single" || isRetired(p) || !profileEndpoint(p))
|
|
1502
|
+
return this.summaryRefused("not a model id with an endpoint of its own");
|
|
1503
|
+
if (p.byo || p.transport === "anthropic")
|
|
1504
|
+
return this.summaryRefused("a cloud provider row");
|
|
1505
|
+
const need = Math.max(b.chunkTokens, b.capTokens + b.summaryTokens) + b.summaryTokens + 1024;
|
|
1506
|
+
for (const leg of this.routerForProfile(p).list()) {
|
|
1507
|
+
if (requiresOperatorToken(leg.base) || !operatorTrustedUrl(leg.base))
|
|
1508
|
+
continue;
|
|
1509
|
+
const s = await probeServed(leg.base, { timeoutMs: 1500, model: leg.model });
|
|
1510
|
+
if ((!s.direct && !s.fleetOnly) || (s.ctx ?? p.ctx ?? 0) < need)
|
|
1511
|
+
continue;
|
|
1512
|
+
return { leg, ...(s.direct && s.slots && s.slots > 1 ? { slots: s.slots } : {}) };
|
|
1513
|
+
}
|
|
1514
|
+
return this.summaryRefused("no leg proven to stay on your own machines with room for a pass");
|
|
1515
|
+
}
|
|
1516
|
+
summaryRefused(reason) {
|
|
1517
|
+
if (!this.summaryModelTold)
|
|
1518
|
+
this.telemetry.record({ type: "summary_model_unavailable", model: this.compactionSummaryModel, reason });
|
|
1519
|
+
this.summaryModelTold = true;
|
|
1520
|
+
return undefined;
|
|
1521
|
+
}
|
|
1522
|
+
/** The summary model's request identity: always a background conversation of its own, so it never holds or demotes
|
|
1523
|
+
* the interactive lease; on a llama-server reached directly, a slot claimed from the background end. */
|
|
1524
|
+
summaryAffinity(side) {
|
|
1525
|
+
const own = { session: `${this.kvSession}-summary`, sessionRole: "background" };
|
|
1526
|
+
if (!side.slots || process.env.KODE_SLOT_AFFINITY === "0")
|
|
1527
|
+
return own;
|
|
1528
|
+
const key = gateKey(side.leg.base, side.leg.model);
|
|
1529
|
+
let slot = this.summarySlots.get(key);
|
|
1530
|
+
if (slot === undefined)
|
|
1531
|
+
this.summarySlots.set(key, slot = claimSlot(key, side.slots, false, this.kvSlotDir));
|
|
1532
|
+
return { ...own, slot };
|
|
1533
|
+
}
|
|
1420
1534
|
/** One rolling pass, a lean request (no system prompt, no tools) so what it reads is its own prompt whatever the
|
|
1421
1535
|
* server has cached. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
|
|
1422
1536
|
* compaction, the owner waiting) takes the whole uncovered tail at once. Once the notes are over their cap the pass
|
|
@@ -1425,7 +1539,7 @@ export class Session {
|
|
|
1425
1539
|
async rollingPass(upTo, signal, live) {
|
|
1426
1540
|
const all = this.convo.all;
|
|
1427
1541
|
const rs = this.rollingSummarizer;
|
|
1428
|
-
const b =
|
|
1542
|
+
const b = this.rollBudget();
|
|
1429
1543
|
// An earlier compaction's note IS the notes so far: adopted as written, never digested again by a note pass.
|
|
1430
1544
|
const adopted = rs.coveredCount(all) ? undefined : adoptedNotes(all[0]?.content);
|
|
1431
1545
|
if (adopted !== undefined)
|
|
@@ -1447,10 +1561,10 @@ export class Session {
|
|
|
1447
1561
|
let wrote = 0;
|
|
1448
1562
|
const written = h?.onCompactionWrite ? () => h.onCompactionWrite?.(++wrote) : undefined;
|
|
1449
1563
|
const t0 = performance.now();
|
|
1450
|
-
const
|
|
1451
|
-
|
|
1452
|
-
...
|
|
1453
|
-
maxTokens:
|
|
1564
|
+
const ask = (to, at, affinity) => chat([{ role: "user", content: fold ? foldPrompt(old, b) : notePrompt(chunk.text, b, noteTokens) }], {
|
|
1565
|
+
...at, token: to?.token, loopbackAuth: to?.loopbackAuth, transport: to?.transport, chatPath: to?.chatPath, ...to?.reasoning,
|
|
1566
|
+
...affinity,
|
|
1567
|
+
maxTokens: to?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : fold ? SUMMARY_MAX_TOKENS : noteTokens,
|
|
1454
1568
|
temperature: 0,
|
|
1455
1569
|
background: !live || this.background, // the endpoint gate: a background pass never takes a slot an interactive request waits for
|
|
1456
1570
|
owner: "compaction",
|
|
@@ -1459,6 +1573,25 @@ export class Session {
|
|
|
1459
1573
|
onReasoning: written,
|
|
1460
1574
|
signal,
|
|
1461
1575
|
});
|
|
1576
|
+
let r;
|
|
1577
|
+
const side = live ? undefined : await this.summaryLeg(b);
|
|
1578
|
+
if (signal?.aborted)
|
|
1579
|
+
return false;
|
|
1580
|
+
if (side) {
|
|
1581
|
+
try {
|
|
1582
|
+
r = await ask(side.leg, { base: side.leg.base, model: side.leg.model }, this.summaryAffinity(side));
|
|
1583
|
+
if (!pickSummaryContent(r.content, r.reasoningContent))
|
|
1584
|
+
r = undefined;
|
|
1585
|
+
}
|
|
1586
|
+
catch (e) {
|
|
1587
|
+
if (signal?.aborted)
|
|
1588
|
+
throw e;
|
|
1589
|
+
}
|
|
1590
|
+
if (!r)
|
|
1591
|
+
this.summaryRefused("its request failed or came back empty");
|
|
1592
|
+
}
|
|
1593
|
+
const via = r ? this.compactionSummaryModel : undefined;
|
|
1594
|
+
r ??= await ask(leg, { base, model }, this.affinity({ base, model, transport: leg?.transport })); // the live turn's slot or session: the span is cached there
|
|
1462
1595
|
const text = pickSummaryContent(r.content, r.reasoningContent);
|
|
1463
1596
|
if (!text || signal?.aborted || this.convo.all !== all)
|
|
1464
1597
|
return false;
|
|
@@ -1466,7 +1599,7 @@ export class Session {
|
|
|
1466
1599
|
rs.advance(foldedNotes(old, text, recent, b), all, covered);
|
|
1467
1600
|
else
|
|
1468
1601
|
rs.advance(appendNote(notes, text), all, chunk.end);
|
|
1469
|
-
this.telemetry.record({ type: "rolling_summary", live, fold, read, covered: fold ? covered : chunk.end, ms: Math.round(performance.now() - t0) });
|
|
1602
|
+
this.telemetry.record({ type: "rolling_summary", ...(via ? { model: via } : {}), live, fold, read, covered: fold ? covered : chunk.end, ms: Math.round(performance.now() - t0) });
|
|
1470
1603
|
return true;
|
|
1471
1604
|
}
|
|
1472
1605
|
/** After a settled turn: while half a chunk or more is uncovered (or the notes are over their cap), summarize it in
|
|
@@ -1477,7 +1610,7 @@ export class Session {
|
|
|
1477
1610
|
fireRollingSummary() {
|
|
1478
1611
|
if (this.rollingRun || this.background || process.env.KODE_ROLLING_SUMMARY === "0")
|
|
1479
1612
|
return;
|
|
1480
|
-
const b =
|
|
1613
|
+
const b = this.rollBudget();
|
|
1481
1614
|
const due = () => {
|
|
1482
1615
|
const all = this.convo.all;
|
|
1483
1616
|
return uncoveredTokens(all, this.rollingSummarizer.coveredCount(all), all.length, b) >= b.dueTokens || notesOverCap(this.rollingSummarizer.getSummary(), b);
|
|
@@ -1508,7 +1641,7 @@ export class Session {
|
|
|
1508
1641
|
this.rollingAbort?.abort();
|
|
1509
1642
|
await this.rollingRun;
|
|
1510
1643
|
const rs = this.rollingSummarizer;
|
|
1511
|
-
const b =
|
|
1644
|
+
const b = this.rollBudget();
|
|
1512
1645
|
const pending = () => rs.coveredCount(all) < n || notesOverCap(rs.getSummary(), b);
|
|
1513
1646
|
if (!pending()) {
|
|
1514
1647
|
this.turnHandlers?.onCompactionCoverage?.({ covered: globalTokenMeter.estimateRequestFor(this.meterKey(), span), reading: 0 });
|
|
@@ -1617,6 +1750,8 @@ export class Session {
|
|
|
1617
1750
|
this.disposeShell();
|
|
1618
1751
|
for (const [key, slot] of this.kvSlots)
|
|
1619
1752
|
releaseSlot(key, slot, this.kvSlotDir);
|
|
1753
|
+
for (const [key, slot] of this.summarySlots)
|
|
1754
|
+
releaseSlot(key, slot, this.kvSlotDir);
|
|
1620
1755
|
this.kvSlots.clear();
|
|
1621
1756
|
this.sleepScheduler?.dispose(); // tear down the sleep consolidation scheduler
|
|
1622
1757
|
}
|
|
@@ -1665,12 +1800,22 @@ export class Session {
|
|
|
1665
1800
|
this.rollingAbort?.abort(); // the owner's turn takes the model: a background summary pass gives it up at once
|
|
1666
1801
|
try {
|
|
1667
1802
|
this.turnImages = await this.nativeImagesFor(text);
|
|
1803
|
+
text = await this.withHeardAudio(text);
|
|
1804
|
+
if (this.ctrl.signal.aborted)
|
|
1805
|
+
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1668
1806
|
const front = await this.viaFrontDoor(text, h);
|
|
1669
1807
|
if (front)
|
|
1670
1808
|
return front;
|
|
1671
1809
|
await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
|
|
1672
1810
|
if (this.ctrl.signal.aborted)
|
|
1673
1811
|
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1812
|
+
if (this.microRecall && !this.wakeTurn) {
|
|
1813
|
+
const recall = this.microRecall;
|
|
1814
|
+
this.microRecall = undefined;
|
|
1815
|
+
this.memoryNote = await recall(text);
|
|
1816
|
+
if (this.ctrl.signal.aborted)
|
|
1817
|
+
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1818
|
+
}
|
|
1674
1819
|
await this.maybeSpeedCompact(h);
|
|
1675
1820
|
if (this.ctrl.signal.aborted)
|
|
1676
1821
|
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
@@ -1692,19 +1837,20 @@ export class Session {
|
|
|
1692
1837
|
this.turnThinkOff = false;
|
|
1693
1838
|
}
|
|
1694
1839
|
}
|
|
1695
|
-
/** The image files in the owner's message that go to the model
|
|
1840
|
+
/** The image and video files in the owner's message that go to the model directly, not through image_analyze: only when the
|
|
1696
1841
|
* model answering can see (the profile says so, else its server does; an unknown is tried, and a server that turns
|
|
1697
1842
|
* the image down puts it back on the tool). Never for a sub-agent, a wake turn or a remote url. */
|
|
1698
1843
|
async nativeImagesFor(text) {
|
|
1699
1844
|
if (this.background || this.wakeTurn)
|
|
1700
1845
|
return [];
|
|
1701
|
-
const
|
|
1846
|
+
const p = findModel(this.liveRegistry(), this.modelId);
|
|
1847
|
+
// video only where the profile declares native vision; a probed or vendor model keeps video_analyze
|
|
1848
|
+
const paths = [...extractImagePaths(text), ...(p?.vision === true ? extractVideoPaths(text) : [])];
|
|
1702
1849
|
if (!paths.length)
|
|
1703
1850
|
return [];
|
|
1704
|
-
const p = findModel(this.liveRegistry(), this.modelId);
|
|
1705
1851
|
if (p?.kind !== "single" || p.transport === "anthropic" || p.vision === false)
|
|
1706
1852
|
return [];
|
|
1707
|
-
if (p.
|
|
1853
|
+
if (p.byo)
|
|
1708
1854
|
return paths;
|
|
1709
1855
|
let base, model;
|
|
1710
1856
|
if (p.id === CHAIN_MODEL_ID) {
|
|
@@ -1719,14 +1865,33 @@ export class Session {
|
|
|
1719
1865
|
base = endpointBase(ep);
|
|
1720
1866
|
model = p.endpointModels?.[0] ?? p.model ?? p.id;
|
|
1721
1867
|
}
|
|
1868
|
+
if (p.vision === true)
|
|
1869
|
+
return visionRejected(base, model) ? [] : paths;
|
|
1722
1870
|
return (await detectVision(base, model)) === "no" ? [] : paths;
|
|
1723
1871
|
}
|
|
1872
|
+
/** The owner's message with the audio files it names transcribed under it (the gateway's speech-to-text route): a
|
|
1873
|
+
* natively multimodal model sees pictures but is given no audio. Only for a profile that declares native vision, and
|
|
1874
|
+
* never for a sub-agent or a wake turn. */
|
|
1875
|
+
async withHeardAudio(text) {
|
|
1876
|
+
if (this.background || this.wakeTurn || findModel(this.liveRegistry(), this.modelId)?.vision !== true)
|
|
1877
|
+
return text;
|
|
1878
|
+
const files = extractAudioPaths(text).flatMap((path) => {
|
|
1879
|
+
try {
|
|
1880
|
+
return [{ path, audio: readFileSync(path) }];
|
|
1881
|
+
}
|
|
1882
|
+
catch {
|
|
1883
|
+
return [];
|
|
1884
|
+
}
|
|
1885
|
+
});
|
|
1886
|
+
return files.length ? withTranscripts(text, files, voiceConfig(this.voice), { signal: this.ctrl?.signal }) : text;
|
|
1887
|
+
}
|
|
1724
1888
|
/** Speed-aware compaction: the last measured turns decoded under compaction.minDecodeTps at a request big enough
|
|
1725
1889
|
* for compaction to help, so compact now, before this turn's first request. The samples are cleared either way, so
|
|
1726
1890
|
* the next trigger needs two fresh slow turns. A failed summarizer leaves the conversation as it was. */
|
|
1727
1891
|
async maybeSpeedCompact(h) {
|
|
1728
1892
|
const due = speedCompactionDue(this.decodeSamples, this.compactionMinDecodeTps, this.requestEstimate());
|
|
1729
|
-
|
|
1893
|
+
const target = this.compactionSpeedTargetTokens;
|
|
1894
|
+
if (!due || (target && (due.ctxTokens <= target || due.ctxTokens < (this.speedRearmAt ?? 0))))
|
|
1730
1895
|
return;
|
|
1731
1896
|
this.decodeSamples = [];
|
|
1732
1897
|
h.onSpeedCompaction?.(due);
|
|
@@ -1734,8 +1899,9 @@ export class Session {
|
|
|
1734
1899
|
h.onCompactionStart?.({ before });
|
|
1735
1900
|
this.turnHandlers = h;
|
|
1736
1901
|
let skipped;
|
|
1902
|
+
const speed = target ? { target } : undefined;
|
|
1737
1903
|
try {
|
|
1738
|
-
await this.compactNowInner();
|
|
1904
|
+
await this.compactNowInner(speed);
|
|
1739
1905
|
}
|
|
1740
1906
|
catch {
|
|
1741
1907
|
skipped = "summarizer_error"; // the turn still runs; the window-fill gate stays the backstop
|
|
@@ -1745,8 +1911,26 @@ export class Session {
|
|
|
1745
1911
|
const after = this.requestEstimate();
|
|
1746
1912
|
this.telemetry.record({ type: "compaction", before, after, trigger: "decode", tps: Math.round(due.tps * 10) / 10, floorTps: due.floorTps, ...(skipped ? { skipped } : {}) });
|
|
1747
1913
|
h.onCompactionEnd?.({ before, after });
|
|
1914
|
+
if (speed && !speed.failed && !skipped)
|
|
1915
|
+
this.noteSpeedTarget(speed.target, after, h);
|
|
1748
1916
|
}
|
|
1749
1917
|
}
|
|
1918
|
+
noteSpeedTarget(target, after, h) {
|
|
1919
|
+
if (after <= target) {
|
|
1920
|
+
this.speedRearmAt = undefined;
|
|
1921
|
+
return;
|
|
1922
|
+
}
|
|
1923
|
+
this.speedRearmAt = after + SPEED_REARM_TOKENS;
|
|
1924
|
+
if (this.speedMissTold)
|
|
1925
|
+
return;
|
|
1926
|
+
this.speedMissTold = true;
|
|
1927
|
+
const floor = fixedRequestTokens({ ctxWindow: this.effectiveContext(), systemPrompt: this.sys(), tools: this.allSchemas(), meter: globalTokenMeter, meterKey: this.meterKey(), summarize: this.summarizeEvicted });
|
|
1928
|
+
h.onSpeedTargetMissed?.({ target, after, floor });
|
|
1929
|
+
}
|
|
1930
|
+
clearSpeedMiss() {
|
|
1931
|
+
this.speedRearmAt = undefined;
|
|
1932
|
+
this.speedMissTold = false;
|
|
1933
|
+
}
|
|
1750
1934
|
/** The front door (engine/front-door.ts). On the default model and MOA, the gateway answers a message its classifier
|
|
1751
1935
|
* is confident needs no tools with its fast model in this session's voice; the reply joins the conversation like any
|
|
1752
1936
|
* other. Returns null to run the turn as usual: the gateway says work (the owner sees its status line at once), it
|
|
@@ -1914,6 +2098,9 @@ export class Session {
|
|
|
1914
2098
|
this.referenceNote = "";
|
|
1915
2099
|
if (carry)
|
|
1916
2100
|
text = `${carry}\n\n${text}`;
|
|
2101
|
+
if (this.memoryNote)
|
|
2102
|
+
text = `${text}\n\n${this.memoryNote}`; // after the owner's words: a leading note would mark the message as the engine's
|
|
2103
|
+
this.memoryNote = "";
|
|
1917
2104
|
const turn = { text, task, convoStart, t0: _t0 };
|
|
1918
2105
|
this.inflight = turn;
|
|
1919
2106
|
const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
|
package/dist/tools/executor.js
CHANGED
|
@@ -56,6 +56,19 @@ const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this
|
|
|
56
56
|
// its session's whole lifetime (the Session is constructed once and reused across turns), so this id
|
|
57
57
|
// is stable across a session's turns — the persistent shell survives, keyed per session, not shared.
|
|
58
58
|
let _execSeq = 0;
|
|
59
|
+
/** Semantic compression, then the character cap. The raw output is spilled before any cut; if it cannot be, nothing is
|
|
60
|
+
* cut by lines. A shell result gets the pointer on top: its exit trailer has to stay last (engine/loop-guard.ts). */
|
|
61
|
+
function shrinkResult(name, args, raw) {
|
|
62
|
+
const compressed = semanticCompress(raw, { toolName: name, toolArgs: args });
|
|
63
|
+
if (compressed === raw)
|
|
64
|
+
return capToolResult(raw, spillToolOutput);
|
|
65
|
+
const path = spillToolOutput(raw);
|
|
66
|
+
if (!path)
|
|
67
|
+
return capToolResult(raw);
|
|
68
|
+
const note = `…[cut from ${raw.split("\n").length} lines — FULL output saved to ${path} · read any part with file_read(path, offset, limit)]`;
|
|
69
|
+
const cut = capToolResult(compressed);
|
|
70
|
+
return SHELL_FOREGROUND.has(name) ? `${note}\n${cut}` : `${cut}\n${note}`;
|
|
71
|
+
}
|
|
59
72
|
export class Executor {
|
|
60
73
|
reg;
|
|
61
74
|
root;
|
|
@@ -86,6 +99,8 @@ export class Executor {
|
|
|
86
99
|
get effectiveRoot() {
|
|
87
100
|
return this.turnRoot ?? this.root;
|
|
88
101
|
}
|
|
102
|
+
/** Set by a host to answer a large result with an extract of its own; null (or a throw) keeps the stock result. */
|
|
103
|
+
assist;
|
|
89
104
|
resetTurn() {
|
|
90
105
|
this.seen.clear();
|
|
91
106
|
}
|
|
@@ -111,9 +126,8 @@ export class Executor {
|
|
|
111
126
|
// Carry the batch's abort signal (FIX 5) through a side-channel so an in-flight bash command is killed
|
|
112
127
|
// on esc — a store, not a Tool.run param, so tools that use their 2nd param for test DI keep it.
|
|
113
128
|
const raw = await shellKeyStore.run(this.shellKey, () => shellSignalStore.run(report?.signal, () => tool.run(args)));
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
const out = capToolResult(compressed, spillToolOutput);
|
|
129
|
+
const assisted = this.assist ? await this.assist(name, args, raw, this.shellKey).catch(() => null) : null;
|
|
130
|
+
const out = assisted ?? shrinkResult(name, args, raw);
|
|
117
131
|
// A file edit that LANDED changed the workspace, so prior identical-call counts are stale — re-running the
|
|
118
132
|
// same test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
|
|
119
133
|
// A FAILING edit ("error: old_string not found") changed nothing, so it must not reset the count.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// The `microAssist` feature (config/features.ts, default OFF): the `micro` MCP server answers a large un-ranged
|
|
2
|
+
// file_read or a long command output with ranked verbatim chunks, and Scribe is searched once for the first task.
|
|
3
|
+
// Only NEW tail content is touched; the tool array and system prompt never change. Anything unexpected (no server,
|
|
4
|
+
// refusal, timeout, a reply that is not the expected shape) returns null/"" and the stock behaviour stands.
|
|
5
|
+
// NODE-ONLY (node:fs, node:crypto).
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { readFile, stat } from "node:fs/promises";
|
|
8
|
+
import { resolve } from "node:path";
|
|
9
|
+
import { SHELL_FOREGROUND } from "./classes.js";
|
|
10
|
+
import { forgetRead } from "./read-ledger.js";
|
|
11
|
+
import { resolveReadPath } from "./read-path.js";
|
|
12
|
+
import { spillToolOutput } from "./tool-output-spill.js";
|
|
13
|
+
export const MICRO_READ = "micro:micro_read";
|
|
14
|
+
export const SCRIBE_SEARCH = "micro:scribe_search";
|
|
15
|
+
export const ASSIST_MIN_CHARS = 20_000;
|
|
16
|
+
const SOURCE_MAX_BYTES = 2 * 1024 * 1024;
|
|
17
|
+
const QUERY_MAX_CHARS = 500;
|
|
18
|
+
const SCRIBE_PARTITION = "default"; // where scribe_add writes when no owner is named
|
|
19
|
+
const SCRIBE_HITS = 3;
|
|
20
|
+
const SCRIBE_FACT_CHARS = 600;
|
|
21
|
+
const TIMEOUT_MS = 4_000;
|
|
22
|
+
export function createMicroAssist(deps) {
|
|
23
|
+
let hung = false; // a server that missed the deadline once is not asked again: every later result would wait too
|
|
24
|
+
async function ask(tool, args) {
|
|
25
|
+
const hub = deps.hub();
|
|
26
|
+
if (hung || !hub?.has(tool))
|
|
27
|
+
return null;
|
|
28
|
+
let timer;
|
|
29
|
+
const late = new Promise((done) => { timer = setTimeout(() => { hung = true; done(null); }, deps.timeoutMs ?? TIMEOUT_MS); });
|
|
30
|
+
try {
|
|
31
|
+
const reply = await Promise.race([hub.call(tool, args), late]);
|
|
32
|
+
return reply === null || reply.startsWith("error") ? null : reply;
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** The reader's reply, only if it names the sha256 of exactly what we hold and is smaller than the stock result. */
|
|
39
|
+
async function extract(target, source, query, stock) {
|
|
40
|
+
const reply = await ask(MICRO_READ, { target, query: query.slice(0, QUERY_MAX_CHARS) });
|
|
41
|
+
if (!reply || reply.length >= stock.length || reply.includes("\nno line matches the query"))
|
|
42
|
+
return null;
|
|
43
|
+
return reply.includes(`sha256: ${createHash("sha256").update(source).digest("hex")}`) ? reply : null;
|
|
44
|
+
}
|
|
45
|
+
async function file(args, raw, sessionKey) {
|
|
46
|
+
if (["offset", "limit", "start_char", "max_chars", "force"].some((k) => args[k] !== undefined))
|
|
47
|
+
return null;
|
|
48
|
+
if (raw.startsWith("[extracted text"))
|
|
49
|
+
return null;
|
|
50
|
+
const asked = await resolveReadPath(String(args.path ?? ""));
|
|
51
|
+
const path = resolve(asked);
|
|
52
|
+
if ((await stat(path)).size > SOURCE_MAX_BYTES)
|
|
53
|
+
return null;
|
|
54
|
+
const bytes = await readFile(path);
|
|
55
|
+
const reply = await extract(path, bytes, deps.task() || path, raw);
|
|
56
|
+
if (!reply)
|
|
57
|
+
return null;
|
|
58
|
+
const saved = spillToolOutput(bytes.toString("utf8"));
|
|
59
|
+
if (!saved)
|
|
60
|
+
return null;
|
|
61
|
+
forgetRead(sessionKey, asked); // the model has not seen this file: a re-read returns it, an overwrite still needs one
|
|
62
|
+
return `[extract of ${path}, not the whole file — FULL output saved to ${saved} · exact lines L<a>-L<b>: file_read(path, offset=a-1, limit=b-a+1)]\n${reply}`;
|
|
63
|
+
}
|
|
64
|
+
async function shell(args, raw) {
|
|
65
|
+
if (raw.length > SOURCE_MAX_BYTES || !raw.includes("\n"))
|
|
66
|
+
return null;
|
|
67
|
+
const reply = await extract(raw, raw, `${String(args.command ?? "")}\n${deps.task()}`, raw);
|
|
68
|
+
if (!reply)
|
|
69
|
+
return null;
|
|
70
|
+
const saved = spillToolOutput(raw);
|
|
71
|
+
if (!saved)
|
|
72
|
+
return null;
|
|
73
|
+
const trailer = /(?:\n(?:\[|\(no output)[^\n]*)+$/.exec(raw)?.[0] ?? ""; // exit code and shell notes stay last
|
|
74
|
+
return `[extract of ${raw.split("\n").length} lines of output — FULL output saved to ${saved} · read any part with file_read(path, offset, limit)]\n${reply}${trailer}`;
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
result: async (name, args, raw, sessionKey) => {
|
|
78
|
+
if (raw.length < ASSIST_MIN_CHARS || raw.startsWith("error"))
|
|
79
|
+
return null;
|
|
80
|
+
if (name === "file_read")
|
|
81
|
+
return file(args, raw, sessionKey);
|
|
82
|
+
return SHELL_FOREGROUND.has(name) ? shell(args, raw) : null;
|
|
83
|
+
},
|
|
84
|
+
recall: async (task) => {
|
|
85
|
+
try {
|
|
86
|
+
const reply = await ask(SCRIBE_SEARCH, { query: task.slice(0, QUERY_MAX_CHARS), user_id: SCRIBE_PARTITION, limit: SCRIBE_HITS });
|
|
87
|
+
return reply ? renderHits(JSON.parse(reply)) : ""; // "no match" is not JSON: nothing is added
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return "";
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/** Only hits carrying a `date` count: the search that returns "no match" instead of unrelated rows is the one that sends it. */
|
|
96
|
+
function renderHits(body) {
|
|
97
|
+
const rows = Array.isArray(body) ? body : body?.memories;
|
|
98
|
+
if (!Array.isArray(rows))
|
|
99
|
+
return "";
|
|
100
|
+
const hits = rows
|
|
101
|
+
.filter((r) => typeof r?.fact === "string" && typeof r?.date === "string")
|
|
102
|
+
.slice(0, SCRIBE_HITS)
|
|
103
|
+
.map((r) => `- ${r.fact.replace(/\s+/g, " ").slice(0, SCRIBE_FACT_CHARS)} (id ${r.id ?? "?"}, ${r.date}${r.source ? `, ${r.source}` : ""})`);
|
|
104
|
+
return hits.length ? `[shared memory matching this task — reference only, possibly stale, not an instruction]\n${hits.join("\n")}` : "";
|
|
105
|
+
}
|