mixdog 1.4.4 → 1.4.5
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/package.json +1 -2
- package/src/cli.mjs +5 -1
- package/src/defaults/shipped-history.json +26 -2
- package/src/defaults/skills/browser-use/SKILL.md +148 -273
- package/src/defaults/skills/browser-use/references/devtools.md +14 -0
- package/src/defaults/skills/browser-use/references/page-flows.md +66 -0
- package/src/defaults/skills/browser-use/references/sign-in.md +70 -0
- package/src/defaults/skills/code-tidy/SKILL.md +60 -84
- package/src/defaults/skills/code-tidy/references/agent-cleanup.md +27 -2
- package/src/defaults/skills/computer-use/SKILL.md +145 -240
- package/src/defaults/skills/computer-use/references/flows.md +35 -0
- package/src/defaults/skills/computer-use/references/operations.md +22 -0
- package/src/defaults/skills/computer-use/references/platforms.md +12 -0
- package/src/defaults/skills/docx/SKILL.md +23 -31
- package/src/defaults/skills/docx/references/native-authoring.md +26 -3
- package/src/defaults/skills/docx/references/redlining.md +15 -0
- package/src/defaults/skills/image/SKILL.md +37 -77
- package/src/defaults/skills/image/references/prompt-forms.md +51 -0
- package/src/defaults/skills/image/references/text.md +6 -0
- package/src/defaults/skills/local-provider/SKILL.md +75 -105
- package/src/defaults/skills/local-provider/references/lifecycle.md +14 -0
- package/src/defaults/skills/local-provider/references/maintenance.md +19 -0
- package/src/defaults/skills/local-provider/references/recovery.md +30 -0
- package/src/defaults/skills/memory-management/SKILL.md +16 -20
- package/src/defaults/skills/pdf/SKILL.md +21 -23
- package/src/defaults/skills/pdf/references/blocks.md +20 -0
- package/src/defaults/skills/pdf/references/forms.md +12 -0
- package/src/defaults/skills/pdf/references/html.md +2 -2
- package/src/defaults/skills/pdf/references/ocr.md +7 -0
- package/src/defaults/skills/pdf/references/security.md +8 -0
- package/src/defaults/skills/pptx/SKILL.md +30 -109
- package/src/defaults/skills/pptx/references/audit.md +45 -0
- package/src/defaults/skills/pptx/references/brief-critique.md +47 -0
- package/src/defaults/skills/pptx/references/editing.md +24 -0
- package/src/defaults/skills/pptx/references/html.md +1 -1
- package/src/defaults/skills/pptx/references/script.md +33 -0
- package/src/defaults/skills/setup/SKILL.md +34 -102
- package/src/defaults/skills/setup/references/actions.md +72 -13
- package/src/defaults/skills/setup/references/surfaces.md +23 -8
- package/src/defaults/skills/setup-guide/SKILL.md +28 -115
- package/src/defaults/skills/setup-guide/references/features.md +36 -0
- package/src/defaults/skills/setup-guide/references/glossary.md +38 -0
- package/src/defaults/skills/setup-guide/references/workflow-models.md +62 -0
- package/src/defaults/skills/test-suite/SKILL.md +15 -127
- package/src/defaults/skills/test-suite/references/case-management.md +17 -9
- package/src/defaults/skills/test-suite/references/diagnose.md +23 -0
- package/src/defaults/skills/test-suite/references/prune.md +27 -0
- package/src/defaults/skills/test-suite/references/write.md +44 -0
- package/src/defaults/skills/video/SKILL.md +28 -42
- package/src/defaults/skills/video/references/prompting.md +31 -0
- package/src/defaults/skills/visualize/SKILL.md +73 -107
- package/src/defaults/skills/visualize/references/craft.md +1 -2
- package/src/defaults/skills/visualize/references/feedback.md +36 -0
- package/src/defaults/skills/visualize/references/showing.md +13 -0
- package/src/defaults/skills/xlsx/SKILL.md +23 -50
- package/src/defaults/skills/xlsx/references/editing.md +15 -0
- package/src/defaults/skills/xlsx/references/model-conventions.md +1 -1
- package/src/defaults/skills/xlsx/references/recalculation.md +37 -0
- package/src/defaults/skills/xlsx/references/report-design.md +18 -2
- package/src/lib/keychain-cjs.cjs +22 -1
- package/src/lib/rules-builder.cjs +1 -1
- package/src/rules/agent/AGENT.md +3 -0
- package/src/rules/lead/LEAD.md +3 -1
- package/src/runtime/agent/orchestrator/agent-runtime/cache-strategy.mjs +8 -30
- package/src/runtime/agent/orchestrator/agent-runtime/title-completion.mjs +5 -0
- package/src/runtime/agent/orchestrator/mcp/oauth-request.mjs +21 -2
- package/src/runtime/agent/orchestrator/providers/account-pool.mjs +3 -0
- package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +2 -2
- package/src/runtime/agent/orchestrator/providers/anthropic-api-transport.mjs +2 -0
- package/src/runtime/agent/orchestrator/providers/anthropic-message-threads.mjs +583 -0
- package/src/runtime/agent/orchestrator/providers/anthropic-oauth-client-version.mjs +1 -1
- package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +81 -19
- package/src/runtime/agent/orchestrator/providers/anthropic-sse.mjs +180 -13
- package/src/runtime/agent/orchestrator/providers/anthropic.mjs +56 -6
- package/src/runtime/agent/orchestrator/providers/cursor-wire.mjs +4 -2
- package/src/runtime/agent/orchestrator/providers/gemini-error-contract.mjs +6 -6
- package/src/runtime/agent/orchestrator/providers/gemini-model-redirect.mjs +44 -0
- package/src/runtime/agent/orchestrator/providers/gemini-reasoning-relay.mjs +5 -0
- package/src/runtime/agent/orchestrator/providers/gemini-request-body.mjs +34 -5
- package/src/runtime/agent/orchestrator/providers/gemini-response.mjs +10 -0
- package/src/runtime/agent/orchestrator/providers/gemini-schema.mjs +11 -6
- package/src/runtime/agent/orchestrator/providers/gemini-sdk-request.mjs +4 -100
- package/src/runtime/agent/orchestrator/providers/gemini-stream.mjs +3 -227
- package/src/runtime/agent/orchestrator/providers/gemini.mjs +226 -118
- package/src/runtime/agent/orchestrator/providers/lib/anthropic-request-utils.mjs +11 -1
- package/src/runtime/agent/orchestrator/providers/lib/claude-bridge-schema.mjs +15 -3
- package/src/runtime/agent/orchestrator/providers/lib/gemini-model-catalog.mjs +2 -1
- package/src/runtime/agent/orchestrator/providers/openai-direct-request.mjs +5 -28
- package/src/runtime/agent/orchestrator/providers/openai-ws-pool.mjs +50 -28
- package/src/runtime/agent/orchestrator/providers/openai-ws-stream/socket-handlers.mjs +14 -10
- package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +1 -3
- package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs +8 -3
- package/src/runtime/agent/orchestrator/providers/vertex-ai-maas.mjs +2 -2
- package/src/runtime/agent/orchestrator/runtime-core/config-helpers.mjs +4 -5
- package/src/runtime/agent/orchestrator/runtime-core/goal-tool-defs.mjs +2 -2
- package/src/runtime/agent/orchestrator/runtime-core/provider-request-tools.mjs +15 -8
- package/src/runtime/agent/orchestrator/runtime-core/session-title.mjs +1 -0
- package/src/runtime/agent/orchestrator/runtime-core/todo-list.mjs +9 -32
- package/src/runtime/agent/orchestrator/runtime-core/todo-tool-defs.mjs +4 -5
- package/src/runtime/agent/orchestrator/session/compact/summary-route.mjs +1 -3
- package/src/runtime/agent/orchestrator/session/loop/compact-policy.mjs +5 -2
- package/src/runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs +2 -17
- package/src/runtime/agent/orchestrator/session/loop/usage.mjs +7 -3
- package/src/runtime/agent/orchestrator/session/manager/ask-turn-settle.mjs +9 -2
- package/src/runtime/agent/orchestrator/session/manager/session-close.mjs +26 -13
- package/src/runtime/agent/orchestrator/session/manager/session-lifecycle.mjs +4 -5
- package/src/runtime/agent/orchestrator/session/manager/usage-metrics.mjs +16 -5
- package/src/runtime/agent/orchestrator/session/store/lifecycle-barriers.mjs +22 -1
- package/src/runtime/agent/orchestrator/session/store/live-state.mjs +4 -0
- package/src/runtime/agent/orchestrator/tools/builtin/cache-layers.mjs +11 -9
- package/src/runtime/agent/orchestrator/tools/builtin/grep-formatting.mjs +2 -8
- package/src/runtime/agent/orchestrator/tools/builtin/lib/search-input-helpers.mjs +1 -9
- package/src/runtime/agent/orchestrator/tools/builtin/local-search-telemetry.mjs +2 -2
- package/src/runtime/agent/orchestrator/tools/builtin/native-search-client.mjs +1 -1
- package/src/runtime/agent/orchestrator/tools/builtin/runtime-capabilities.mjs +12 -3
- package/src/runtime/agent/orchestrator/tools/code-graph/ast-calls.mjs +9 -2
- package/src/runtime/agent/orchestrator/tools/code-graph/build.mjs +137 -7
- package/src/runtime/agent/orchestrator/tools/code-graph/calls-cache.mjs +43 -14
- package/src/runtime/agent/orchestrator/tools/code-graph/calls-sidecar-worker.mjs +33 -0
- package/src/runtime/agent/orchestrator/tools/code-graph/disk-cache.mjs +146 -11
- package/src/runtime/agent/orchestrator/tools/code-graph/dispatch.mjs +31 -24
- package/src/runtime/agent/orchestrator/tools/code-graph/graph-binary/spawn-jsonl.mjs +172 -25
- package/src/runtime/agent/orchestrator/tools/code-graph/graph-model.mjs +100 -2
- package/src/runtime/agent/orchestrator/tools/code-graph/main-thread-slice.mjs +18 -0
- package/src/runtime/agent/orchestrator/tools/code-graph/mask-pool.mjs +219 -0
- package/src/runtime/agent/orchestrator/tools/code-graph/mask-worker.mjs +12 -0
- package/src/runtime/agent/orchestrator/tools/code-graph/memory-cache.mjs +6 -1
- package/src/runtime/agent/orchestrator/tools/code-graph/modes/calls.mjs +9 -2
- package/src/runtime/agent/orchestrator/tools/code-graph/modes/dependents.mjs +5 -1
- package/src/runtime/agent/orchestrator/tools/code-graph/modes/structure.mjs +8 -2
- package/src/runtime/agent/orchestrator/tools/code-graph/modes/symbols.mjs +14 -11
- package/src/runtime/agent/orchestrator/tools/code-graph/search-references.mjs +41 -18
- package/src/runtime/agent/orchestrator/tools/code-graph/search.mjs +391 -83
- package/src/runtime/agent/orchestrator/tools/code-graph/symbol-index.mjs +109 -9
- package/src/runtime/agent/orchestrator/tools/code-graph/text-mask.mjs +73 -29
- package/src/runtime/agent/orchestrator/tools/code-graph-prewarm-worker.mjs +6 -5
- package/src/runtime/agent/orchestrator/tools/lib/native-spawn-client.mjs +7 -3
- package/src/runtime/channels/lib/crash-log.mjs +21 -1
- package/src/runtime/channels/lib/worker-main.mjs +8 -25
- package/src/runtime/media/jobs.mjs +5 -0
- package/src/runtime/media/store.mjs +146 -3
- package/src/runtime/office/core/office-write-ledger.mjs +2 -2
- package/src/runtime/shared/agent-reap-state.mjs +19 -0
- package/src/runtime/shared/desktop-notice-host.d.mts +13 -0
- package/src/runtime/shared/desktop-notice-host.mjs +87 -0
- package/src/runtime/shared/file-lock.mjs +2 -2
- package/src/runtime/shared/heap-cap.mjs +9 -11
- package/src/runtime/shared/llm/http-agent.mjs +11 -1
- package/src/runtime/shared/llm/system-proxy.mjs +100 -25
- package/src/runtime/shared/llm/usage-accounting.mjs +18 -7
- package/src/runtime/shared/llm/usage-context.mjs +2 -2
- package/src/runtime/shared/llm/usage-ledger-requests.mjs +10 -3
- package/src/runtime/shared/llm/usage-ledger.mjs +13 -1
- package/src/runtime/shared/provider-accounts.mjs +22 -0
- package/src/runtime/shared/provider-auth-binding.mjs +2 -2
- package/src/runtime/shared/resource-admission.mjs +2 -2
- package/src/runtime/shared/root-async-context.mjs +51 -0
- package/src/runtime/shared/run-child.mjs +18 -1
- package/src/runtime/shared/slow-span.mjs +2 -2
- package/src/runtime/shared/tool-execution-owner.mjs +2 -2
- package/src/runtime/shared/tool-work-units.mjs +2 -0
- package/src/runtime/shared/turn-snapshot-store.mjs +75 -18
- package/src/runtime/shared/turn-worktree-snapshot.mjs +38 -8
- package/src/runtime/shared/user-cwd.mjs +2 -2
- package/src/runtime/shared/worker-requests.mjs +3 -1
- package/src/runtime/shared/worktrees/lock.mjs +2 -2
- package/src/runtime/visualize-bridge/client.mjs +26 -4
- package/src/runtime/visualize-bridge/tool-defs.mjs +46 -5
- package/src/session-runtime/boot/apis.mjs +1 -0
- package/src/session-runtime/boot/begin.mjs +2 -0
- package/src/session-runtime/media-api.mjs +15 -0
- package/src/session-runtime/provider-readiness.mjs +10 -2
- package/src/session-runtime/runtime-core.mjs +35 -8
- package/src/session-runtime/runtime-review-api.mjs +3 -1
- package/src/session-runtime/services/agent-tool/close-flow.mjs +6 -1
- package/src/session-runtime/services/agent-tool/execute-resume.mjs +94 -0
- package/src/session-runtime/services/agent-tool/execute-send.mjs +77 -27
- package/src/session-runtime/services/agent-tool/execute-spawn.mjs +28 -7
- package/src/session-runtime/services/agent-tool/execute.mjs +6 -1
- package/src/session-runtime/services/agent-tool/helpers.mjs +11 -0
- package/src/session-runtime/services/agent-tool/job-views/job-render.mjs +13 -10
- package/src/session-runtime/services/agent-tool/render.mjs +2 -0
- package/src/session-runtime/services/agent-tool/send-flow.mjs +1 -0
- package/src/session-runtime/services/agent-tool/spawn-flow/spawn-prep.mjs +6 -0
- package/src/session-runtime/services/agent-tool/spawn-flow/spawn-run.mjs +2 -1
- package/src/session-runtime/services/agent-tool/tag-registry/reaped-sessions.mjs +82 -0
- package/src/session-runtime/services/agent-tool/tag-registry/record-facts-worker.mjs +36 -0
- package/src/session-runtime/services/agent-tool/tag-registry.mjs +4 -0
- package/src/session-runtime/services/agent-tool/terminal-reaper/row-helpers.mjs +29 -0
- package/src/session-runtime/services/agent-tool/terminal-reaper/scan-admission.mjs +11 -3
- package/src/session-runtime/services/agent-tool/terminal-reaper/stale-rows.mjs +19 -8
- package/src/session-runtime/services/agent-tool/terminal-reaper.mjs +5 -2
- package/src/session-runtime/services/agent-tool/worker-index.mjs +1 -0
- package/src/session-runtime/services/daemon-crash-capture/daemon-exit-record.mjs +2 -2
- package/src/session-runtime/session-create.mjs +5 -0
- package/src/session-runtime/setup-tool/settings-contract.mjs +2 -0
- package/src/session-runtime/usage-stats-api.mjs +3 -0
- package/src/session-runtime/workspace/admission-gate.mjs +25 -7
- package/src/session-runtime/workspace/transitions.mjs +4 -0
- package/src/standalone/daemon-log.mjs +28 -4
- package/src/standalone/daemon-owner.mjs +41 -7
- package/src/standalone/daemon-work-gate.mjs +139 -0
- package/src/standalone/daemon.mjs +80 -11
- package/src/standalone/desktop-service-registry.mjs +11 -4
- package/src/standalone/session-client.mjs +57 -5
- package/src/standalone/session-protocol.mjs +5 -0
- package/src/standalone/session-service/agent-tree/agent-cancel.mjs +17 -1
- package/src/standalone/session-service/agent-tree.mjs +7 -0
- package/src/standalone/session-service/session-calls/session-turns.mjs +12 -5
- package/src/standalone/session-transport/call-route.mjs +10 -4
- package/src/standalone/session-transport/routes.mjs +21 -0
- package/src/standalone/session-transport/stack.mjs +3 -1
- package/src/standalone/session-transport.mjs +5 -0
- package/src/tui/dist/index.mjs +495 -477
- package/src/tui/session/session-api/media.mjs +5 -0
- package/src/tui/session/turn.mjs +13 -0
- package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/cancellation.mjs +0 -71
- package/src/runtime/agent/orchestrator/providers/gemini-sdk-stream/reader.mjs +0 -108
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
_cfCookieHeader,
|
|
30
30
|
} from './openai-ws-headers.mjs';
|
|
31
31
|
import { clearAllCodexTurnStates, clearCodexTurnStateScope, retireCodexTurnStateOwner } from './openai-turn-state.mjs';
|
|
32
|
+
import { runInRootAsyncContext } from '../../../shared/root-async-context.mjs';
|
|
32
33
|
|
|
33
34
|
// Human-readable transport label for handshake/acquire error messages. Shared
|
|
34
35
|
// with openai-oauth-ws.mjs (stream-side errors use the same labels).
|
|
@@ -273,16 +274,20 @@ function _removeFromPool(poolKey, entry) {
|
|
|
273
274
|
if (arr.length === 0) _wsPool.delete(poolKey);
|
|
274
275
|
}
|
|
275
276
|
|
|
277
|
+
// Pooled sockets and their idle/liveness timers outlive the request that made
|
|
278
|
+
// them; created in the root context they never retain that request's session.
|
|
276
279
|
function _scheduleIdleClose(poolKey, entry) {
|
|
277
280
|
if (!entry) return;
|
|
278
281
|
if (entry.idleTimer) clearTimeout(entry.idleTimer);
|
|
279
|
-
entry.idleTimer =
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
282
|
+
entry.idleTimer = runInRootAsyncContext(() =>
|
|
283
|
+
setTimeout(() => {
|
|
284
|
+
if (entry.busy) return;
|
|
285
|
+
try {
|
|
286
|
+
entry.socket.close(1000, 'idle_timeout');
|
|
287
|
+
} catch {}
|
|
288
|
+
_removeFromPool(poolKey, entry);
|
|
289
|
+
}, WS_IDLE_MS)
|
|
290
|
+
);
|
|
286
291
|
try {
|
|
287
292
|
entry.idleTimer.unref?.();
|
|
288
293
|
} catch {}
|
|
@@ -369,22 +374,24 @@ function _pingProbe(entry, timeoutMs) {
|
|
|
369
374
|
// its own inter-chunk/semantic-idle watchdogs.
|
|
370
375
|
function _armLiveness(poolKey, entry) {
|
|
371
376
|
_clearLiveness(entry);
|
|
372
|
-
entry.pingTimer =
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
377
|
+
entry.pingTimer = runInRootAsyncContext(() =>
|
|
378
|
+
setInterval(async () => {
|
|
379
|
+
if (entry.busy || entry.closing || entry.probing) return;
|
|
380
|
+
if (!_isOpen(entry)) {
|
|
381
|
+
_evictDead(poolKey, entry);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
// Recent activity ⇒ assume live, skip the probe this tick.
|
|
385
|
+
if (Date.now() - (entry.lastAliveAt || 0) < WS_LIVENESS_STALE_MS) return;
|
|
386
|
+
entry.probing = true;
|
|
387
|
+
try {
|
|
388
|
+
const alive = await _pingProbe(entry, WS_PONG_TIMEOUT_MS);
|
|
389
|
+
if (!alive && !entry.busy) _evictDead(poolKey, entry);
|
|
390
|
+
} finally {
|
|
391
|
+
entry.probing = false;
|
|
392
|
+
}
|
|
393
|
+
}, WS_PING_INTERVAL_MS)
|
|
394
|
+
);
|
|
388
395
|
try {
|
|
389
396
|
entry.pingTimer.unref?.();
|
|
390
397
|
} catch {}
|
|
@@ -734,7 +741,11 @@ async function _openPoolEntry({ auth, cacheKey, codexHeaders, externalSignal, co
|
|
|
734
741
|
const tokenHash = createHash('sha256').update(String(sessionToken)).digest('hex').slice(0, 8);
|
|
735
742
|
_acquireTrace(`acquire-new tokenHash=${tokenHash} elapsed=${Date.now() - acqStart}ms`);
|
|
736
743
|
}
|
|
737
|
-
|
|
744
|
+
// The socket (its TCP/TLS handle and handshake timers) is reused by later
|
|
745
|
+
// requests: open it in the root context, never this one's.
|
|
746
|
+
const { socket } = await runInRootAsyncContext(() =>
|
|
747
|
+
_openSocketImpl({ auth, sessionToken, externalSignal, cacheKey, codexHeaders })
|
|
748
|
+
);
|
|
738
749
|
if (_drainComplete) {
|
|
739
750
|
try {
|
|
740
751
|
socket.close(1000, 'drain-complete');
|
|
@@ -922,8 +933,18 @@ export function releaseWebSocket({ entry, poolKey: callerPoolKey, keep }) {
|
|
|
922
933
|
_releasePoolOwner(poolKey, entry);
|
|
923
934
|
}
|
|
924
935
|
|
|
925
|
-
function closeOpenaiWsPoolForSession(poolKey, reason = 'session_closed') {
|
|
936
|
+
function closeOpenaiWsPoolForSession(poolKey, reason = 'session_closed', { inFlightOnly = false } = {}) {
|
|
926
937
|
if (!poolKey) return;
|
|
938
|
+
if (inFlightOnly) {
|
|
939
|
+
// A turn abort: only a socket mid-response is unusable. An idle one keeps
|
|
940
|
+
// its response chain for the next turn; the closed one's own 'close'
|
|
941
|
+
// handler releases its owner claim and pool slot.
|
|
942
|
+
const owned = [...(_wsPool.get(poolKey) || []), ...[..._unpooledSockets].filter((e) => e.poolKey === poolKey)];
|
|
943
|
+
for (const entry of owned) {
|
|
944
|
+
if (entry.busy) _shutdownEntry(entry, String(reason || 'turn_aborted'));
|
|
945
|
+
}
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
927
948
|
_clearPoolOwnerScope(poolKey);
|
|
928
949
|
clearCodexTurnStateScope(poolKey);
|
|
929
950
|
const closeReason = String(reason || 'session_closed');
|
|
@@ -1052,11 +1073,12 @@ export function drainOpenaiWsPool(reason = 'shutdown', { immediate = false } = {
|
|
|
1052
1073
|
// registers the same globals), so chain whatever is already installed instead of
|
|
1053
1074
|
// replacing it — import order must not decide which transport gets torn down.
|
|
1054
1075
|
const _priorPoolSessionCloseHook = globalThis.__mixdogCloseProviderConnectionsForSession;
|
|
1055
|
-
|
|
1076
|
+
// `options.inFlightOnly`: a turn abort, which leaves idle connections alone.
|
|
1077
|
+
globalThis.__mixdogCloseProviderConnectionsForSession = (poolKey, reason, options) => {
|
|
1056
1078
|
try {
|
|
1057
|
-
_priorPoolSessionCloseHook?.(poolKey, reason);
|
|
1079
|
+
_priorPoolSessionCloseHook?.(poolKey, reason, options);
|
|
1058
1080
|
} finally {
|
|
1059
|
-
closeOpenaiWsPoolForSession(poolKey, reason);
|
|
1081
|
+
closeOpenaiWsPoolForSession(poolKey, reason, options);
|
|
1060
1082
|
}
|
|
1061
1083
|
};
|
|
1062
1084
|
const _priorPoolDrainHook = globalThis.__mixdogDrainProviderConnections;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AsyncResource } from 'node:async_hooks';
|
|
1
2
|
import { performance } from 'node:perf_hooks';
|
|
2
3
|
import { _parseEvent } from '../openai-ws-events.mjs';
|
|
3
4
|
import {
|
|
@@ -158,13 +159,20 @@ export function createSocketHandlers({
|
|
|
158
159
|
};
|
|
159
160
|
const onOpen = () => _writeWsLifecycleTrace('open');
|
|
160
161
|
|
|
162
|
+
// Pooled sockets are opened in the root context (openai-ws-pool.mjs), and a
|
|
163
|
+
// socket's events run in the context it was opened in: bind this stream's
|
|
164
|
+
// handlers to the context of the request that sends on it.
|
|
165
|
+
const socketListeners = [
|
|
166
|
+
['message', AsyncResource.bind(onMessage)],
|
|
167
|
+
['close', AsyncResource.bind(onClose)],
|
|
168
|
+
['error', AsyncResource.bind(onError)],
|
|
169
|
+
['ping', AsyncResource.bind(onPing)],
|
|
170
|
+
['pong', AsyncResource.bind(onPong)],
|
|
171
|
+
];
|
|
172
|
+
|
|
161
173
|
function detach() {
|
|
162
|
-
socket.off(
|
|
163
|
-
socket.off('close', onClose);
|
|
164
|
-
socket.off('error', onError);
|
|
174
|
+
for (const [event, listener] of socketListeners) socket.off(event, listener);
|
|
165
175
|
socket.off('open', onOpen);
|
|
166
|
-
socket.off('ping', onPing);
|
|
167
|
-
socket.off('pong', onPong);
|
|
168
176
|
externalSignal?.removeEventListener('abort', onAbort);
|
|
169
177
|
}
|
|
170
178
|
|
|
@@ -176,11 +184,7 @@ export function createSocketHandlers({
|
|
|
176
184
|
}
|
|
177
185
|
externalSignal.addEventListener('abort', onAbort, { once: true });
|
|
178
186
|
}
|
|
179
|
-
socket.on(
|
|
180
|
-
socket.on('close', onClose);
|
|
181
|
-
socket.on('error', onError);
|
|
182
|
-
socket.on('ping', onPing);
|
|
183
|
-
socket.on('pong', onPong);
|
|
187
|
+
for (const [event, listener] of socketListeners) socket.on(event, listener);
|
|
184
188
|
if (WS_TRACE_ENABLED) {
|
|
185
189
|
socket.on('open', onOpen);
|
|
186
190
|
if (socket.readyState === WebSocket.OPEN) _writeWsLifecycleTrace('open');
|
|
@@ -142,9 +142,7 @@ export class OpenAIDirectProvider {
|
|
|
142
142
|
// Keep public response storage and model-specific cache options out of
|
|
143
143
|
// the shared OAuth payload. Storage opt-out still forces full frames in
|
|
144
144
|
// _computeDelta; retained output items make those frames self-contained.
|
|
145
|
-
applyOpenAIDirectCachePolicy(body, useModel, _envFlag('MIXDOG_OAI_STORE', true)
|
|
146
|
-
prefixTtl: opts.promptCachePrefixTtl || null,
|
|
147
|
-
});
|
|
145
|
+
applyOpenAIDirectCachePolicy(body, useModel, _envFlag('MIXDOG_OAI_STORE', true));
|
|
148
146
|
// poolKey MUST be sessionId-only. Falling back to promptCacheKey would
|
|
149
147
|
// let unrelated raw sessions sharing the same provider-scoped cache
|
|
150
148
|
// bucket reuse each other's pooled socket and inherit lastResponseId
|
package/src/runtime/agent/orchestrator/providers/stream-json-pool/worker-slots/slot-spawn.mjs
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* idle worker from holding the process open.
|
|
5
5
|
*/
|
|
6
6
|
import { Worker } from 'node:worker_threads';
|
|
7
|
+
import { runInRootAsyncContext } from '../../../../../shared/root-async-context.mjs';
|
|
7
8
|
|
|
8
9
|
// After this many consecutive worker-construction failures the pool stops
|
|
9
10
|
// trying to spawn and stays inline. This is a failure latch, not a throttle:
|
|
@@ -65,9 +66,13 @@ export function createSlotSpawner({ state, WorkerImpl = Worker, isClosed, affini
|
|
|
65
66
|
function createSlot() {
|
|
66
67
|
let worker;
|
|
67
68
|
try {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
69
|
+
// A slot serves later streams too: spawn it outside this stream's context.
|
|
70
|
+
worker = runInRootAsyncContext(
|
|
71
|
+
() =>
|
|
72
|
+
new WorkerImpl(new URL('../../stream-json-worker.mjs', import.meta.url), {
|
|
73
|
+
execArgv: [],
|
|
74
|
+
})
|
|
75
|
+
);
|
|
71
76
|
} catch {
|
|
72
77
|
noteSpawnFailure();
|
|
73
78
|
return null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runtimeAsyncLocalStorage } from '../../../shared/root-async-context.mjs';
|
|
2
2
|
import { currentUsageContext } from '../../../shared/llm/usage-context.mjs';
|
|
3
3
|
import { noteErrorUsage } from './lib/note-error-usage.mjs';
|
|
4
4
|
import { OpenAICompatProvider } from './openai-compat.mjs';
|
|
@@ -73,7 +73,7 @@ export function vertexErrorBody(text) {
|
|
|
73
73
|
|
|
74
74
|
// The account one send targets ({ identity, token }), read by its engine's
|
|
75
75
|
// fetch on every HTTP attempt, the engine's own retries included.
|
|
76
|
-
const sendAccount =
|
|
76
|
+
const sendAccount = runtimeAsyncLocalStorage();
|
|
77
77
|
|
|
78
78
|
// Each HTTP attempt carries the send's account's current token, and a
|
|
79
79
|
// credential switch since the send began aborts it before anything is sent.
|
|
@@ -202,11 +202,10 @@ const AUTO_CLEAR_DEFAULT_IDLE_MS = 60 * 60 * 1000;
|
|
|
202
202
|
// reusable. Gemini, xAI and Mistral
|
|
203
203
|
// caches run ~1h, Groq's implicit cache persists ~2h, and DeepSeek's
|
|
204
204
|
// implicit cache is evicted after "a few hours to a few days" (kept at 24h).
|
|
205
|
-
// OpenAI public API (GPT-5.6+ Responses, cache-strategy.mjs):
|
|
206
|
-
// is written with ttl "30m"
|
|
207
|
-
//
|
|
208
|
-
// (
|
|
209
|
-
// prefix. Earlier OpenAI models (prompt_cache_retention, typically ~30 min)
|
|
205
|
+
// OpenAI public API (GPT-5.6+ Responses, cache-strategy.mjs): every request
|
|
206
|
+
// is written with ttl "30m", so the sweep matches it — a clear after that
|
|
207
|
+
// costs nothing extra (the cache is cold anyway). Earlier OpenAI models
|
|
208
|
+
// (prompt_cache_retention, typically ~30 min)
|
|
210
209
|
// are not distinguished: these call sites only know the provider.
|
|
211
210
|
// OpenAI OAuth (Codex/ChatGPT login) keeps the cache of logged-in users
|
|
212
211
|
// indefinitely (2026-10-20), so its built-in window is unlimited: no idle
|
|
@@ -6,7 +6,7 @@ export const GOAL_TOOL_DEFS = Object.freeze([
|
|
|
6
6
|
name: 'goal',
|
|
7
7
|
title: 'Goal',
|
|
8
8
|
description:
|
|
9
|
-
'A durable objective the runtime keeps working on across turns until you complete or block it, with an optional time cap (an upper bound, never a minimum). Create one only for an explicit Goal request or approved multi-turn work (staged refactors, migrations, open-ended objectives); never for single-turn tasks, plans, estimates or unaccepted proposals. One Goal at a time; its steps live in todo, not here. complete only after auditing every user condition against current evidence
|
|
9
|
+
'A durable objective the runtime keeps working on across turns until you complete or block it, with an optional time cap (an upper bound, never a minimum). Create one only for an explicit Goal request or approved multi-turn work (staged refactors, migrations, open-ended objectives); never for single-turn tasks, plans, estimates or unaccepted proposals. One Goal at a time; its steps live in todo, not here. complete only after auditing every user condition against current evidence — never because time is low, the cap was reached or the turn is ending, and never for a smaller objective than the one stated. block only when the same blocking condition has recurred for at least three consecutive Goal turns (first turn and continuations count) and no progress is possible without the user or a change in external state; never because the work is hard, slow, uncertain, unfinished or would benefit from clarification. A resumed Goal counts afresh; once the threshold is met, block rather than report the impasse. Pause, resume, stop and edits are the user’s controls.',
|
|
10
10
|
annotations: {
|
|
11
11
|
title: 'Goal',
|
|
12
12
|
readOnlyHint: false,
|
|
@@ -34,7 +34,7 @@ export const GOAL_TOOL_DEFS = Object.freeze([
|
|
|
34
34
|
type: 'string',
|
|
35
35
|
minLength: 1,
|
|
36
36
|
maxLength: 1_000,
|
|
37
|
-
description: 'block: the impasse; stops the Goal.',
|
|
37
|
+
description: 'block: the impasse that recurred for three consecutive Goal turns; stops the Goal.',
|
|
38
38
|
},
|
|
39
39
|
},
|
|
40
40
|
required: ['action'],
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { runtimeAsyncLocalStorage } from '../../../shared/root-async-context.mjs';
|
|
2
2
|
|
|
3
|
-
const requestToolScope =
|
|
3
|
+
const requestToolScope = runtimeAsyncLocalStorage();
|
|
4
4
|
const NATIVE_PREFIX_COUNT = Symbol('mixdog.providerNativeToolPrefixCount');
|
|
5
5
|
const finalizedProviderRequestTools = new WeakSet();
|
|
6
6
|
let requestToolScopeGeneration = 0;
|
|
@@ -49,21 +49,28 @@ export function runWithProviderRequestToolsScope(scope, callback) {
|
|
|
49
49
|
try {
|
|
50
50
|
result = callback();
|
|
51
51
|
} catch (error) {
|
|
52
|
-
store
|
|
52
|
+
deactivate(store);
|
|
53
53
|
throw error;
|
|
54
54
|
}
|
|
55
55
|
if (result && typeof result.then === 'function') {
|
|
56
|
-
return Promise.resolve(result).finally(() =>
|
|
57
|
-
store.active = false;
|
|
58
|
-
});
|
|
56
|
+
return Promise.resolve(result).finally(() => deactivate(store));
|
|
59
57
|
}
|
|
60
|
-
store
|
|
58
|
+
deactivate(store);
|
|
61
59
|
return result;
|
|
62
60
|
});
|
|
63
61
|
}
|
|
64
62
|
|
|
63
|
+
// An inactive scope is never read again, but any handle, timer or listener
|
|
64
|
+
// created under it keeps the store: drop what pins the session.
|
|
65
|
+
function deactivate(store) {
|
|
66
|
+
store.active = false;
|
|
67
|
+
store.session = null;
|
|
68
|
+
store.messages = null;
|
|
69
|
+
store.requestTools = null;
|
|
70
|
+
}
|
|
71
|
+
|
|
65
72
|
export function invalidateProviderRequestToolsScope(scope = requestToolScope.getStore()) {
|
|
66
|
-
if (scope && typeof scope === 'object') scope
|
|
73
|
+
if (scope && typeof scope === 'object') deactivate(scope);
|
|
67
74
|
}
|
|
68
75
|
|
|
69
76
|
export function scopedProviderRequestTools(session, provider, messages) {
|
|
@@ -189,6 +189,7 @@ export function createSessionTitleController(deps = {}) {
|
|
|
189
189
|
deps.generateSessionTitle || (await import('../agent-runtime/title-completion.mjs')).generateSessionTitle;
|
|
190
190
|
if (disposed) return '';
|
|
191
191
|
return complete(source, {
|
|
192
|
+
sessionId,
|
|
192
193
|
signal: abort.signal,
|
|
193
194
|
locale: String(deps.systemLocale?.() || resolvedSystemLocale()),
|
|
194
195
|
});
|
|
@@ -31,9 +31,9 @@ function normalizeTask(raw) {
|
|
|
31
31
|
if (!raw || typeof raw !== 'object') return null;
|
|
32
32
|
const content = oneLine(raw.content);
|
|
33
33
|
if (!content) return null;
|
|
34
|
+
// Stored lists from when `blocked` existed load as pending.
|
|
34
35
|
const status = TODO_STATUSES.includes(raw.status) ? raw.status : 'pending';
|
|
35
36
|
const task = { content, status };
|
|
36
|
-
if (status === 'blocked' && oneLine(raw.blocker)) task.blocker = oneLine(raw.blocker);
|
|
37
37
|
if (oneLine(raw.note)) task.note = oneLine(raw.note);
|
|
38
38
|
return task;
|
|
39
39
|
}
|
|
@@ -52,7 +52,7 @@ export function todoPhases(session) {
|
|
|
52
52
|
const allTasks = (phases) => phases.flatMap((phase) => phase.tasks);
|
|
53
53
|
|
|
54
54
|
/** Exactly one in_progress while actionable work exists: several keep the
|
|
55
|
-
* earliest, none starts the earliest pending.
|
|
55
|
+
* earliest, none starts the earliest pending. */
|
|
56
56
|
function normalizeTodoPhases(phases) {
|
|
57
57
|
const tasks = allTasks(phases);
|
|
58
58
|
const active = tasks.filter((task) => task.status === 'in_progress');
|
|
@@ -78,8 +78,8 @@ export function openTodoItems(session) {
|
|
|
78
78
|
return allTasks(todoPhases(session)).filter((task) => OPEN_STATUSES.has(task.status));
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
/** Every item not completed or dropped
|
|
82
|
-
*
|
|
81
|
+
/** Every item not completed or dropped: what an agent leaves undone when it
|
|
82
|
+
* ends. */
|
|
83
83
|
export function unfinishedTodoItems(session) {
|
|
84
84
|
return allTasks(todoPhases(session)).filter((task) => task.status !== 'completed' && task.status !== 'abandoned');
|
|
85
85
|
}
|
|
@@ -145,7 +145,7 @@ function publish(session) {
|
|
|
145
145
|
}
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
-
const MARKS = { completed: 'x', in_progress: '>', pending: ' ',
|
|
148
|
+
const MARKS = { completed: 'x', in_progress: '>', pending: ' ', abandoned: '-' };
|
|
149
149
|
|
|
150
150
|
function progressLabel(phases) {
|
|
151
151
|
const { completed, abandoned, total } = todoCounts(phases);
|
|
@@ -159,7 +159,7 @@ function renderTodoList(phases) {
|
|
|
159
159
|
for (const phase of phases) {
|
|
160
160
|
lines.push(phase.name);
|
|
161
161
|
for (const task of phase.tasks) {
|
|
162
|
-
const detail = task.
|
|
162
|
+
const detail = task.note ? ` — ${task.note}` : '';
|
|
163
163
|
lines.push(` [${MARKS[task.status]}] ${task.content}${detail}`);
|
|
164
164
|
}
|
|
165
165
|
}
|
|
@@ -171,7 +171,6 @@ function summaryLine(phases, op, content) {
|
|
|
171
171
|
const parts = [progressLabel(phases), `${op}: ${content}`];
|
|
172
172
|
const current = tasks.find((task) => task.status === 'in_progress');
|
|
173
173
|
if (current) parts.push(`next: ${current.content}`);
|
|
174
|
-
else if (tasks.some((task) => task.status === 'blocked')) parts.push('next: none (blocked items wait)');
|
|
175
174
|
else parts.push('all closed');
|
|
176
175
|
return parts.join(' · ');
|
|
177
176
|
}
|
|
@@ -218,7 +217,6 @@ const OPS = {
|
|
|
218
217
|
start(phases, args) {
|
|
219
218
|
const { task } = findTask(phases, args.item);
|
|
220
219
|
if (task.status === 'completed') throw new Error(`todo: "${task.content}" is completed and stays closed`);
|
|
221
|
-
if (task.status === 'blocked') throw new Error(`todo: "${task.content}" is blocked; unblock it first`);
|
|
222
220
|
for (const other of allTasks(phases)) if (other.status === 'in_progress') other.status = 'pending';
|
|
223
221
|
task.status = 'in_progress';
|
|
224
222
|
return task.content;
|
|
@@ -226,7 +224,6 @@ const OPS = {
|
|
|
226
224
|
done(phases, args) {
|
|
227
225
|
const { task } = findTask(phases, args.item);
|
|
228
226
|
task.status = 'completed';
|
|
229
|
-
delete task.blocker;
|
|
230
227
|
const note = oneLine(args.note);
|
|
231
228
|
if (note) task.note = note;
|
|
232
229
|
return task.content;
|
|
@@ -235,23 +232,6 @@ const OPS = {
|
|
|
235
232
|
const { task } = findTask(phases, args.item);
|
|
236
233
|
if (task.status === 'completed') throw new Error(`todo: "${task.content}" is completed and stays closed`);
|
|
237
234
|
task.status = 'abandoned';
|
|
238
|
-
delete task.blocker;
|
|
239
|
-
return task.content;
|
|
240
|
-
},
|
|
241
|
-
block(phases, args) {
|
|
242
|
-
const { task } = findTask(phases, args.item);
|
|
243
|
-
if (task.status === 'completed' || task.status === 'abandoned') {
|
|
244
|
-
throw new Error(`todo: "${task.content}" is ${task.status}; only open items can block`);
|
|
245
|
-
}
|
|
246
|
-
task.status = 'blocked';
|
|
247
|
-
task.blocker = itemText(args.reason, 'block reason');
|
|
248
|
-
return task.content;
|
|
249
|
-
},
|
|
250
|
-
unblock(phases, args) {
|
|
251
|
-
const { task } = findTask(phases, args.item);
|
|
252
|
-
if (task.status !== 'blocked') throw new Error(`todo: "${task.content}" is not blocked`);
|
|
253
|
-
task.status = 'pending';
|
|
254
|
-
delete task.blocker;
|
|
255
235
|
return task.content;
|
|
256
236
|
},
|
|
257
237
|
append(phases, args) {
|
|
@@ -312,10 +292,7 @@ export function executeTodoTool(session, args = {}) {
|
|
|
312
292
|
export function notDoneReport(session) {
|
|
313
293
|
const unfinished = unfinishedTodoItems(session);
|
|
314
294
|
if (!unfinished.length) return '';
|
|
315
|
-
return [
|
|
316
|
-
'Not done:',
|
|
317
|
-
...unfinished.map((task) => `- ${task.content}${task.blocker ? ` (blocked: ${task.blocker})` : ''}`),
|
|
318
|
-
].join('\n');
|
|
295
|
+
return ['Not done:', ...unfinished.map((task) => `- ${task.content}`)].join('\n');
|
|
319
296
|
}
|
|
320
297
|
|
|
321
298
|
/** The open list as a hidden reminder (after compaction, or appended to a
|
|
@@ -335,7 +312,7 @@ const LEGACY_GOAL_TASK_STATUS = {
|
|
|
335
312
|
in_progress: 'in_progress',
|
|
336
313
|
completed: 'completed',
|
|
337
314
|
dropped: 'abandoned',
|
|
338
|
-
awaiting_approval: '
|
|
315
|
+
awaiting_approval: 'pending',
|
|
339
316
|
};
|
|
340
317
|
|
|
341
318
|
/** Move a legacy Goal record's tasks into the session's list (once; the Goal
|
|
@@ -352,7 +329,7 @@ export function adoptLegacyGoalTasks(session, legacyTasks) {
|
|
|
352
329
|
if (!content || existing.has(content)) continue;
|
|
353
330
|
existing.add(content);
|
|
354
331
|
const status = LEGACY_GOAL_TASK_STATUS[oneLine(raw?.status).toLowerCase()] || 'pending';
|
|
355
|
-
adopted.push(
|
|
332
|
+
adopted.push({ content, status });
|
|
356
333
|
}
|
|
357
334
|
if (!adopted.length) return false;
|
|
358
335
|
const name = phases.length ? 'Goal' : DEFAULT_TODO_PHASE;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The model-facing `todo` step list. Its description is the only guidance the
|
|
2
2
|
// model gets about it: nothing is added to the system prompt or rules.
|
|
3
|
-
export const TODO_OPS = Object.freeze(['init', 'start', 'done', 'drop', '
|
|
4
|
-
export const TODO_STATUSES = Object.freeze(['pending', 'in_progress', 'completed', 'abandoned'
|
|
3
|
+
export const TODO_OPS = Object.freeze(['init', 'start', 'done', 'drop', 'append', 'rm', 'view']);
|
|
4
|
+
export const TODO_STATUSES = Object.freeze(['pending', 'in_progress', 'completed', 'abandoned']);
|
|
5
5
|
export const MAX_TODO_ITEMS = 50;
|
|
6
6
|
export const MAX_TODO_TEXT_LENGTH = 200;
|
|
7
7
|
|
|
@@ -19,7 +19,7 @@ export const TODO_TOOL = Object.freeze({
|
|
|
19
19
|
agentHidden: false,
|
|
20
20
|
},
|
|
21
21
|
description:
|
|
22
|
-
'The step list for this request; the Lead and each agent keep their own. Use it whenever the work has three or more steps or several asks (a delegated brief with several parts counts); skip it only for a single step or a plain answer. Create it before the first real action: init with every ask as its own item, in order, covering investigation through verification. A follow-up that adds to the request: append its asks and any steps you discover; init is for a new, unrelated request and refuses while items are open. An item is named by its outcome in 3-8 words and keeps that exact wording; it is how you refer to it — lost the wording: view, never guess. Keep it current while you work, not at the end: the moment an item is finished and its result is read, mark it done with your next call — never batch completions. The runtime keeps exactly one item in progress; done moves it to the next. Send todo beside your next real tool call; when no real call is due, call it alone rather than skip the update.
|
|
22
|
+
'The step list for this request; the Lead and each agent keep their own. Use it whenever the work has three or more steps or several asks (a delegated brief with several parts counts); skip it only for a single step or a plain answer. Create it before the first real action: init with every ask as its own item, in order, covering investigation through verification. A follow-up that adds to the request: append its asks and any steps you discover; init is for a new, unrelated request and refuses while items are open. An item is named by its outcome in 3-8 words and keeps that exact wording; it is how you refer to it — lost the wording: view, never guess. Keep it current while you work, not at the end: the moment an item is finished and its result is read, mark it done with your next call — never batch completions. The runtime keeps exactly one item in progress; done moves it to the next. Send todo beside your next real tool call; when no real call is due, call it alone rather than skip the update. Mark an item done only after reading its result; an item waiting on the user, an agent or a shell stays open.',
|
|
23
23
|
inputSchema: {
|
|
24
24
|
type: 'object',
|
|
25
25
|
properties: {
|
|
@@ -36,10 +36,9 @@ export const TODO_TOOL = Object.freeze({
|
|
|
36
36
|
},
|
|
37
37
|
description: 'init: named phases instead of items.',
|
|
38
38
|
},
|
|
39
|
-
item: { type: 'string', description: 'start/done/drop/
|
|
39
|
+
item: { type: 'string', description: 'start/done/drop/rm: exact item wording.' },
|
|
40
40
|
phase: { type: 'string', description: 'append: target phase (default last; new name adds one).' },
|
|
41
41
|
note: { type: 'string', description: 'done: optional one-line evidence.' },
|
|
42
|
-
reason: { type: 'string', description: 'block: what it waits on.' },
|
|
43
42
|
},
|
|
44
43
|
required: ['op'],
|
|
45
44
|
additionalProperties: false,
|
|
@@ -21,9 +21,7 @@ const WARM_MARGIN_RATIO = 0.1;
|
|
|
21
21
|
|
|
22
22
|
/** How long the cache a saved request wrote or read stays readable, in ms:
|
|
23
23
|
* Infinity when it does not expire (openai-oauth), 0 when it is not cached.
|
|
24
|
-
* Anthropic: the request's message-tail tier (5m / 1h); OpenAI:
|
|
25
|
-
* that holds the conversation (the Lead's 12h breakpoint covers only the
|
|
26
|
-
* stable tools/instructions prefix). */
|
|
24
|
+
* Anthropic: the request's message-tail tier (5m / 1h); OpenAI: 30m. */
|
|
27
25
|
function requestCacheLifetimeMs(request) {
|
|
28
26
|
const name = request?.provider?.name;
|
|
29
27
|
if (name === 'openai-oauth') return Infinity;
|
|
@@ -319,10 +319,13 @@ export function invalidateContextUsageSnapshot(sessionRef) {
|
|
|
319
319
|
|
|
320
320
|
function providerPressureTokens(sessionRef, usage) {
|
|
321
321
|
if (!usage || typeof usage !== 'object') return 0;
|
|
322
|
-
|
|
322
|
+
// Billed input can repeat context (Gemini long decode); the context input
|
|
323
|
+
// the provider reports then replaces both billed prompt figures.
|
|
324
|
+
const contextInput = Math.max(0, Number(usage.contextInputTokens) || 0);
|
|
325
|
+
const input = contextInput || Math.max(0, Number(usage.inputTokens) || 0);
|
|
323
326
|
const cachedRead = Math.max(0, Number(usage.cachedTokens) || 0);
|
|
324
327
|
const cacheWrite = Math.max(0, Number(usage.cacheWriteTokens) || 0);
|
|
325
|
-
const explicitPrompt = Math.max(0, Number(usage.promptTokens) || 0);
|
|
328
|
+
const explicitPrompt = contextInput || Math.max(0, Number(usage.promptTokens) || 0);
|
|
326
329
|
const normalizedPrompt = providerInputExcludesCache(sessionRef?.provider) ? input + cachedRead + cacheWrite : input;
|
|
327
330
|
const prompt = Math.max(explicitPrompt, normalizedPrompt);
|
|
328
331
|
const output = Math.max(0, Number(usage.outputTokens) || 0);
|
|
@@ -15,13 +15,7 @@
|
|
|
15
15
|
import { resolvePluginData } from '../../../../../shared/plugin-paths.mjs';
|
|
16
16
|
import { awaitingBackgroundWork, beginUserCycle } from '../../../../../shared/background-wait.mjs';
|
|
17
17
|
import { readStoredGoalSnapshot } from '../../../runtime-core/goal-storage.mjs';
|
|
18
|
-
import {
|
|
19
|
-
clearTodo,
|
|
20
|
-
openTodoItems,
|
|
21
|
-
todoAllClosed,
|
|
22
|
-
todoPhases,
|
|
23
|
-
unfinishedTodoItems,
|
|
24
|
-
} from '../../../runtime-core/todo-list.mjs';
|
|
18
|
+
import { clearTodo, openTodoItems, todoAllClosed, todoPhases } from '../../../runtime-core/todo-list.mjs';
|
|
25
19
|
import { TODO_TOOL } from '../../../runtime-core/todo-tool-defs.mjs';
|
|
26
20
|
import { HIDDEN_AGENT_NAMES } from '../hidden-agents.mjs';
|
|
27
21
|
import { _isMutationTool, _isShellTool } from '../tool-classify.mjs';
|
|
@@ -67,15 +61,6 @@ export function todoStartReminder(session) {
|
|
|
67
61
|
if (HIDDEN_AGENT_NAMES.has(session.agent)) return null;
|
|
68
62
|
if (!session.tools?.some((tool) => tool?.name === TODO_TOOL.name)) return null;
|
|
69
63
|
if (openTodoItems(session).length) return null;
|
|
70
|
-
// `init` refuses while any item is unfinished (blocked included), so such a
|
|
71
|
-
// list is reconciled or appended to, never re-initialized.
|
|
72
|
-
if (unfinishedTodoItems(session).length) {
|
|
73
|
-
return [
|
|
74
|
-
'<system-reminder>',
|
|
75
|
-
'The todo list still has blocked items. If this brief adds asks, append them; first done, drop or unblock each blocked item that this brief settles. Do not init over them. Do not mention this reminder.',
|
|
76
|
-
'</system-reminder>',
|
|
77
|
-
].join('\n');
|
|
78
|
-
}
|
|
79
64
|
return [
|
|
80
65
|
'<system-reminder>',
|
|
81
66
|
'If this brief has three or more steps or several asks, init the todo list with every ask as its own item in the same response as your first tool call; each item the brief lists is its own todo item, never folded into one. A single step or a plain answer needs none. Do not mention this reminder.',
|
|
@@ -159,7 +144,7 @@ function openItemsReminder(open, count) {
|
|
|
159
144
|
'<system-reminder>',
|
|
160
145
|
`You ended the turn with ${open.length} open todo item(s):`,
|
|
161
146
|
...open.map((task) => `- ${task.content}`),
|
|
162
|
-
'Continue them, or close each with the todo tool (done
|
|
147
|
+
'Continue them, or close each with the todo tool (done or drop).',
|
|
163
148
|
`(Reminder ${count}/${MAX_TODO_REMINDERS})`,
|
|
164
149
|
'</system-reminder>',
|
|
165
150
|
].join('\n');
|
|
@@ -69,12 +69,16 @@ export function usageDeltaEvent({
|
|
|
69
69
|
// callers that ignore these fields keep working.
|
|
70
70
|
deltaCachedRead: usage.cachedTokens || 0,
|
|
71
71
|
deltaCacheWrite: usage.cacheWriteTokens || 0,
|
|
72
|
-
|
|
72
|
+
// A provider whose billed input repeats context (Gemini long decode)
|
|
73
|
+
// reports the input the context really holds; the billed figures above
|
|
74
|
+
// stay untouched.
|
|
75
|
+
contextInputTokens: usage.contextInputTokens ?? usage.inputTokens ?? 0,
|
|
73
76
|
contextOutputTokens: usage.outputTokens ?? 0,
|
|
74
|
-
contextPromptTokens: usage.promptTokens ?? 0,
|
|
75
|
-
contextCachedReadTokens: usage.cachedTokens ?? 0,
|
|
77
|
+
contextPromptTokens: usage.contextInputTokens ?? usage.promptTokens ?? 0,
|
|
78
|
+
contextCachedReadTokens: usage.contextCachedTokens ?? usage.cachedTokens ?? 0,
|
|
76
79
|
contextCacheWriteTokens: usage.cacheWriteTokens ?? 0,
|
|
77
80
|
contextMeasuredTokens: measuredContextTokens(usage),
|
|
81
|
+
...(usage.contextInputTokens != null ? { contextOutputInWindow: true } : {}),
|
|
78
82
|
sendTools,
|
|
79
83
|
ts: Date.now(),
|
|
80
84
|
};
|
|
@@ -25,6 +25,7 @@ import { holdTurnUntilDurable } from './turn-durability.mjs';
|
|
|
25
25
|
import { recordProviderContextBaseline } from '../loop/compact-policy.mjs';
|
|
26
26
|
import { throwIfAborted } from '../../../../shared/abort-race.mjs';
|
|
27
27
|
import { appendAssistantTurnMessage, persistProviderState, recordAskUsage } from './ask-turn-commit.mjs';
|
|
28
|
+
import { CLOSE_PROVENANCE_VERSION } from '../../../../shared/agent-reap-state.mjs';
|
|
28
29
|
|
|
29
30
|
export function attachAssistantTranscriptCompletion(messages, completion, turnStartedAt = 0) {
|
|
30
31
|
if (!Array.isArray(messages) || !completion || typeof completion !== 'object') return false;
|
|
@@ -127,8 +128,14 @@ export async function commitAskTurn({ sessionId, opened, prepared, result, rawTr
|
|
|
127
128
|
if (runtime.prepareCloseSnapshot === prepareCloseSnapshot) {
|
|
128
129
|
runtime.prepareCloseSnapshot = null;
|
|
129
130
|
}
|
|
130
|
-
|
|
131
|
-
session.
|
|
131
|
+
const completedAt = Date.now();
|
|
132
|
+
session.updatedAt = completedAt;
|
|
133
|
+
session.lastUsedAt = completedAt;
|
|
134
|
+
// Owner closes from here on are recorded on this record, and only a
|
|
135
|
+
// completed turn (never a rewind or other bookkeeping that moves
|
|
136
|
+
// lastUsedAt) lifts an earlier one (agent-reap-state.mjs).
|
|
137
|
+
session.closeProvenance = CLOSE_PROVENANCE_VERSION;
|
|
138
|
+
session.lastTurnCompletedAt = completedAt;
|
|
132
139
|
applyAskTerminalUsageTotals(session, result, {
|
|
133
140
|
skipTotalsIfIncremental: runtime?.usageMetricsTurnIncremental === true,
|
|
134
141
|
});
|