@jjh32456/longlive 0.0.0-stage → 2.0.0
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/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// WP6 · L4 merge (DESIGN §2.4/§5.8, K20).
|
|
2
|
+
//
|
|
3
|
+
// Two distinct things share the "L4 merge" name:
|
|
4
|
+
// 1. Small-write coalescing (§5.8): deterministic, always on. Two adjacent
|
|
5
|
+
// queued proposals for the same op+target merge when each segment is
|
|
6
|
+
// <=2KB and the result is <=4KB. The later proposal is absorbed into the
|
|
7
|
+
// earlier one and marked superseded; it is never split back automatically.
|
|
8
|
+
// 2. The daily L4c journal fold (§2.4): LLM-assisted, gated by
|
|
9
|
+
// routerL4MergeEnabled (default false). This module only exposes a pure
|
|
10
|
+
// planner so the tick can stay mockable and the disabled path has zero
|
|
11
|
+
// side effects.
|
|
12
|
+
//
|
|
13
|
+
// Everything here is pure: no fs, no clock, no audit. The proposal engine
|
|
14
|
+
// performs the two file writes and the audit row.
|
|
15
|
+
|
|
16
|
+
import crypto from 'node:crypto';
|
|
17
|
+
|
|
18
|
+
import { localDayKey } from './paths.mjs';
|
|
19
|
+
|
|
20
|
+
export const SMALL_WRITE_SEGMENT_MAX_BYTES = 2048;
|
|
21
|
+
export const SMALL_WRITE_MERGED_MAX_BYTES = 4096;
|
|
22
|
+
export const SMALL_WRITE_SEPARATOR = '\n\n---\n\n';
|
|
23
|
+
|
|
24
|
+
export const L4_MERGE_AFTER_HOUR = 4;
|
|
25
|
+
export const L4_MIN_ROUNDS = 3;
|
|
26
|
+
export const L4_MAX_PER_SESSION_PER_DAY = 1;
|
|
27
|
+
export const L4_MAX_PER_DAY = 5;
|
|
28
|
+
export const L4_CONTENT_MAX_CHARS = 600;
|
|
29
|
+
|
|
30
|
+
function sha256Hex(text) {
|
|
31
|
+
// Kept local to avoid importing proposals.mjs (that module imports this one).
|
|
32
|
+
return crypto.createHash('sha256').update(String(text), 'utf8').digest('hex');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function normalizeContentForHash(content) {
|
|
36
|
+
return String(content ?? '')
|
|
37
|
+
.replace(/\r\n?/gu, '\n')
|
|
38
|
+
.split('\n')
|
|
39
|
+
.map((line) => line.replace(/[ \t]+$/u, ''))
|
|
40
|
+
.join('\n');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function dedupeKeyFor(op, target, content) {
|
|
44
|
+
return `sha256:${sha256Hex(`${op}\u0000${target}\u0000${normalizeContentForHash(content)}`)}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function byteLength(text) {
|
|
48
|
+
return Buffer.byteLength(String(text ?? ''), 'utf8');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function sameSha(left, right) {
|
|
52
|
+
const normalize = (value) => {
|
|
53
|
+
if (typeof value !== 'string' || value === '') return null;
|
|
54
|
+
return value.startsWith('sha256:') ? value.slice(7) : value;
|
|
55
|
+
};
|
|
56
|
+
return normalize(left) === normalize(right);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function truncated(text, maxChars) {
|
|
60
|
+
const value = String(text ?? '').replace(/\s+/gu, ' ').trim();
|
|
61
|
+
if (value.length <= maxChars) return value;
|
|
62
|
+
return value.slice(0, Math.max(0, maxChars - 1)).trimEnd() + '…';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Decide whether two proposals may coalesce. Every clause is required
|
|
67
|
+
* (DESIGN §5.8): same target, same op, same mergeKey, queue-adjacent, each
|
|
68
|
+
* segment <=2KB, merged <=4KB, and both baseShas still match the target.
|
|
69
|
+
*
|
|
70
|
+
* `currentSha` is optional for pure tests; production always passes it. A null
|
|
71
|
+
* currentSha is a legitimate "target does not exist yet" snapshot (journal
|
|
72
|
+
* append), so null===null passes the revalidation.
|
|
73
|
+
*/
|
|
74
|
+
export function canMergeSmallWrite(previous, next, { adjacent = true, currentSha = undefined } = {}) {
|
|
75
|
+
const no = (code, extra = {}) => ({ ok: false, code, reason: code, ...extra });
|
|
76
|
+
if (!previous || !next) return no('missing-proposal');
|
|
77
|
+
if (previous.status !== 'pending' || next.status !== 'pending') return no('not-pending');
|
|
78
|
+
if (!previous.queue?.ticket || !next.queue?.ticket) return no('missing-ticket');
|
|
79
|
+
if (previous.id && next.id && previous.id === next.id) return no('same-proposal');
|
|
80
|
+
if (previous.target !== next.target) return no('target-mismatch');
|
|
81
|
+
if (previous.op !== next.op) return no('op-mismatch');
|
|
82
|
+
if (!previous.mergeKey || previous.mergeKey !== next.mergeKey) return no('merge-key-mismatch');
|
|
83
|
+
if (adjacent !== true) return no('not-adjacent');
|
|
84
|
+
if (typeof previous.content !== 'string' || typeof next.content !== 'string') return no('content-missing');
|
|
85
|
+
if (currentSha !== undefined
|
|
86
|
+
&& (!sameSha(previous.baseSha, currentSha) || !sameSha(next.baseSha, currentSha))) {
|
|
87
|
+
return no('base-moved');
|
|
88
|
+
}
|
|
89
|
+
const previousBytes = byteLength(previous.content);
|
|
90
|
+
const nextBytes = byteLength(next.content);
|
|
91
|
+
if (previousBytes > SMALL_WRITE_SEGMENT_MAX_BYTES || nextBytes > SMALL_WRITE_SEGMENT_MAX_BYTES) {
|
|
92
|
+
return no('segment-too-large', { previousBytes, nextBytes, limit: SMALL_WRITE_SEGMENT_MAX_BYTES });
|
|
93
|
+
}
|
|
94
|
+
const content = `${previous.content}${SMALL_WRITE_SEPARATOR}${next.content}`;
|
|
95
|
+
const bytes = byteLength(content);
|
|
96
|
+
if (bytes > SMALL_WRITE_MERGED_MAX_BYTES) {
|
|
97
|
+
return no('merged-too-large', { previousBytes, nextBytes, bytes, limit: SMALL_WRITE_MERGED_MAX_BYTES });
|
|
98
|
+
}
|
|
99
|
+
return { ok: true, content, bytes, previousBytes, nextBytes };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Build the keeper/absorbed pair. The keeper keeps its ticket and gains the
|
|
104
|
+
* absorbed body (first segment first); the absorbed proposal becomes
|
|
105
|
+
* `superseded` and points back with queue.mergedInto. `dedupeKey` is recomputed
|
|
106
|
+
* for the merged body, which is the §5.8 "afterSha" obligation for this store.
|
|
107
|
+
*/
|
|
108
|
+
export function planSmallWriteMerge(previous, next, { at = null, adjacent = true, currentSha = undefined } = {}) {
|
|
109
|
+
const check = canMergeSmallWrite(previous, next, { adjacent, currentSha });
|
|
110
|
+
if (!check.ok) return check;
|
|
111
|
+
const stamp = at ?? new Date().toISOString();
|
|
112
|
+
const keeper = {
|
|
113
|
+
...previous,
|
|
114
|
+
content: check.content,
|
|
115
|
+
dedupeKey: dedupeKeyFor(previous.op, previous.target, check.content),
|
|
116
|
+
rev: (Number(previous.rev) || 0) + 1,
|
|
117
|
+
updatedAt: stamp,
|
|
118
|
+
stateLog: [
|
|
119
|
+
...(Array.isArray(previous.stateLog) ? previous.stateLog : []),
|
|
120
|
+
{
|
|
121
|
+
at: stamp,
|
|
122
|
+
from: 'pending',
|
|
123
|
+
to: 'pending',
|
|
124
|
+
by: 'router-merge',
|
|
125
|
+
note: `merged-in:${next.queue.ticket}`,
|
|
126
|
+
},
|
|
127
|
+
],
|
|
128
|
+
};
|
|
129
|
+
const absorbed = {
|
|
130
|
+
...next,
|
|
131
|
+
status: 'superseded',
|
|
132
|
+
rev: (Number(next.rev) || 0) + 1,
|
|
133
|
+
updatedAt: stamp,
|
|
134
|
+
queue: {
|
|
135
|
+
...next.queue,
|
|
136
|
+
mergedInto: previous.id,
|
|
137
|
+
supersededBy: previous.id,
|
|
138
|
+
},
|
|
139
|
+
stateLog: [
|
|
140
|
+
...(Array.isArray(next.stateLog) ? next.stateLog : []),
|
|
141
|
+
{
|
|
142
|
+
at: stamp,
|
|
143
|
+
from: 'pending',
|
|
144
|
+
to: 'superseded',
|
|
145
|
+
by: 'router-merge',
|
|
146
|
+
note: `merged-into:${previous.queue.ticket}`,
|
|
147
|
+
},
|
|
148
|
+
],
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
ok: true,
|
|
152
|
+
keeper,
|
|
153
|
+
absorbed,
|
|
154
|
+
keeperId: previous.id,
|
|
155
|
+
keeperTicket: previous.queue.ticket,
|
|
156
|
+
absorbedId: next.id,
|
|
157
|
+
absorbedTicket: next.queue.ticket,
|
|
158
|
+
bytes: check.bytes,
|
|
159
|
+
previousBytes: check.previousBytes,
|
|
160
|
+
nextBytes: check.nextBytes,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Pure L4c planner. Returns proposal *inputs* (the caller proposes them); it
|
|
166
|
+
* never reads the memory tree and never calls a model. Disabled is an exact
|
|
167
|
+
* no-op: no clock use beyond the caller's Date, no audit, no writes.
|
|
168
|
+
*
|
|
169
|
+
* `sessions` entries: { sessionId, goal, roundsSinceLastMerge, isSubagent,
|
|
170
|
+
* parentSessionId }. `proposals` entries: { id, origin:{sessionId}, title,
|
|
171
|
+
* queue:{ticket} }. `state`: { day, count, sessions:{ [sessionId]:{ day } } }.
|
|
172
|
+
*/
|
|
173
|
+
export function planL4Merge({ enabled = false, now = new Date(), sessions = [], proposals = [], state = {} } = {}) {
|
|
174
|
+
if (enabled !== true) return { ok: true, enabled: false, proposals: [], reason: 'disabled' };
|
|
175
|
+
const at = now instanceof Date ? now : new Date(now);
|
|
176
|
+
if (!Number.isFinite(at.getTime())) return { ok: true, enabled: true, proposals: [], reason: 'invalid-clock' };
|
|
177
|
+
if (at.getHours() < L4_MERGE_AFTER_HOUR) {
|
|
178
|
+
return { ok: true, enabled: true, proposals: [], reason: 'before-window' };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const day = localDayKey(at);
|
|
182
|
+
const current = {
|
|
183
|
+
day,
|
|
184
|
+
count: state?.day === day && Number.isInteger(state.count) ? state.count : 0,
|
|
185
|
+
sessions: state?.day === day && state.sessions && typeof state.sessions === 'object' ? { ...state.sessions } : {},
|
|
186
|
+
};
|
|
187
|
+
if (current.count >= L4_MAX_PER_DAY) {
|
|
188
|
+
return { ok: true, enabled: true, proposals: [], day, state: current, reason: 'quota' };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const bySession = new Map();
|
|
192
|
+
for (const proposal of proposals) {
|
|
193
|
+
const sessionId = proposal?.origin?.sessionId;
|
|
194
|
+
if (typeof sessionId !== 'string' || sessionId === '') continue;
|
|
195
|
+
if (!bySession.has(sessionId)) bySession.set(sessionId, []);
|
|
196
|
+
bySession.get(sessionId).push(proposal);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const out = [];
|
|
200
|
+
const seen = new Set();
|
|
201
|
+
for (const session of sessions) {
|
|
202
|
+
if (current.count >= L4_MAX_PER_DAY) break;
|
|
203
|
+
const sessionId = session?.sessionId;
|
|
204
|
+
if (typeof sessionId !== 'string' || sessionId === '' || seen.has(sessionId)) continue;
|
|
205
|
+
seen.add(sessionId);
|
|
206
|
+
if (session.isSubagent === true || session.parentSessionId) continue;
|
|
207
|
+
if (Number(session.roundsSinceLastMerge) < L4_MIN_ROUNDS) continue;
|
|
208
|
+
if (current.sessions[sessionId]?.day === day) continue;
|
|
209
|
+
|
|
210
|
+
const submitted = bySession.get(sessionId) ?? [];
|
|
211
|
+
if (submitted.length === 0) continue;
|
|
212
|
+
const titles = submitted.map((proposal) => truncated(proposal.title, 48)).filter(Boolean);
|
|
213
|
+
const content = buildL4JournalContent({
|
|
214
|
+
goal: session.goal,
|
|
215
|
+
titles,
|
|
216
|
+
nextTicket: submitted[0]?.queue?.ticket,
|
|
217
|
+
});
|
|
218
|
+
const proposal = {
|
|
219
|
+
op: 'journal.append',
|
|
220
|
+
target: `journal/${day.slice(0, 7)}.md`,
|
|
221
|
+
title: truncated(`L4 归并 ${day} ${sessionId}`, 120),
|
|
222
|
+
content,
|
|
223
|
+
risk: 'medium',
|
|
224
|
+
evidence: [
|
|
225
|
+
`live:${sessionId}`,
|
|
226
|
+
...submitted.slice(0, 3).map((item) => `proposal:${item.id}`),
|
|
227
|
+
],
|
|
228
|
+
};
|
|
229
|
+
out.push(proposal);
|
|
230
|
+
current.count += 1;
|
|
231
|
+
current.sessions[sessionId] = { day, at: at.toISOString() };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
ok: true,
|
|
236
|
+
enabled: true,
|
|
237
|
+
day,
|
|
238
|
+
proposals: out,
|
|
239
|
+
state: current,
|
|
240
|
+
reason: out.length > 0 ? 'eligible' : 'none-eligible',
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Exactly three bullets, always <=600 chars (DESIGN §2.4). */
|
|
245
|
+
export function buildL4JournalContent({ goal = '', titles = [], nextTicket = null } = {}) {
|
|
246
|
+
const goalText = truncated(goal, 120) || '(本会话未记录目标)';
|
|
247
|
+
const picked = titles.slice(0, 3).map((title) => truncated(title, 48));
|
|
248
|
+
while (picked.length < 3) picked.push('(无)');
|
|
249
|
+
const ticket = truncated(nextTicket, 16) || '待处理提案';
|
|
250
|
+
return [
|
|
251
|
+
`- 目标:${goalText}`,
|
|
252
|
+
`- 近期提案:${picked.join(';')}`,
|
|
253
|
+
`- 下一步:处理 ${ticket} 后回写本会话结论。`,
|
|
254
|
+
].join('\n').slice(0, L4_CONTENT_MAX_CHARS);
|
|
255
|
+
}
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
// Router 1.1.0 WP5 — provider/model resolution and host failure mapping.
|
|
2
|
+
//
|
|
3
|
+
// Binding inputs (2026-11-05), repo root of the router-1100 workspace:
|
|
4
|
+
// DECISIONS-WP5.md D-WP5-1..6
|
|
5
|
+
// MODEL-PROVIDER-CONTRACT.md (host DSH 0.2.1-rc.5)
|
|
6
|
+
//
|
|
7
|
+
// Resolution order is fixed by D-WP5-1:
|
|
8
|
+
// 1) explicit routerModel (anything but "auto")
|
|
9
|
+
// 2) ctx.get('agentDefaultModel').currentSelection() when the provider matches
|
|
10
|
+
// 3) llm.listModels(provider), first non-preview id (MODEL_AUTO_PICKED_LIST_ORDER)
|
|
11
|
+
// 4) blocked E_NO_PROVIDER with candidates
|
|
12
|
+
// There is deliberately no version ranking, no guessing, and no hardcoded model id.
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_PROVIDER = 'deepseek-official';
|
|
15
|
+
export const AUTO_MODEL = 'auto';
|
|
16
|
+
|
|
17
|
+
export const MODEL_AUTO_PICKED_LIST_ORDER = 'MODEL_AUTO_PICKED_LIST_ORDER';
|
|
18
|
+
export const MODEL_UNLISTED = 'MODEL_UNLISTED';
|
|
19
|
+
export const REASONING_EFFORT_UNSUPPORTED = 'REASONING_EFFORT_UNSUPPORTED';
|
|
20
|
+
export const PROVIDER_FALLBACK = 'PROVIDER_FALLBACK';
|
|
21
|
+
export const MODEL_AUTO_UNRESOLVED = 'MODEL_AUTO_UNRESOLVED';
|
|
22
|
+
|
|
23
|
+
const PREVIEW_RE = /(?:^|[-_.])(preview|experimental|beta|alpha|rc\d*)(?:$|[-_.])/i;
|
|
24
|
+
|
|
25
|
+
export function isPreviewModelId(id) {
|
|
26
|
+
return PREVIEW_RE.test(String(id ?? ''));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function readService(ctx, name) {
|
|
30
|
+
try {
|
|
31
|
+
if (!ctx || typeof ctx.get !== 'function') return null;
|
|
32
|
+
return ctx.get(name) ?? null;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function nonemptyString(value) {
|
|
39
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : '';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Detached copy: callers must never hold the host's selection object.
|
|
43
|
+
export function readCurrentSelection(ctx) {
|
|
44
|
+
const service = readService(ctx, 'agentDefaultModel');
|
|
45
|
+
if (!service || typeof service.currentSelection !== 'function') return null;
|
|
46
|
+
try {
|
|
47
|
+
const selection = service.currentSelection();
|
|
48
|
+
if (!selection || typeof selection !== 'object') return null;
|
|
49
|
+
const provider = nonemptyString(selection.provider);
|
|
50
|
+
const model = nonemptyString(selection.model);
|
|
51
|
+
if (!provider || !model || model === AUTO_MODEL) return null;
|
|
52
|
+
const out = { provider, model };
|
|
53
|
+
const effort = nonemptyString(selection.reasoningEffort);
|
|
54
|
+
if (effort) out.reasoningEffort = effort;
|
|
55
|
+
return out;
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function providerIdsOf(raw) {
|
|
62
|
+
const ids = [];
|
|
63
|
+
if (Array.isArray(raw)) {
|
|
64
|
+
for (const item of raw) {
|
|
65
|
+
const id = typeof item === 'string' ? item : item?.id;
|
|
66
|
+
if (nonemptyString(id)) ids.push(id.trim());
|
|
67
|
+
}
|
|
68
|
+
} else if (raw && typeof raw === 'object') {
|
|
69
|
+
for (const id of Object.keys(raw)) {
|
|
70
|
+
if (nonemptyString(id)) ids.push(id.trim());
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return [...new Set(ids)];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Advisory only. A missing listProviders() means "cannot verify", not "no provider".
|
|
77
|
+
export async function listProviderIds(llm) {
|
|
78
|
+
if (!llm || typeof llm.listProviders !== 'function') return { ok: false, ids: null };
|
|
79
|
+
try {
|
|
80
|
+
return { ok: true, ids: providerIdsOf(await llm.listProviders()) };
|
|
81
|
+
} catch {
|
|
82
|
+
return { ok: false, ids: null };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function modelIdsOf(raw) {
|
|
87
|
+
let list = [];
|
|
88
|
+
if (Array.isArray(raw)) list = raw;
|
|
89
|
+
else if (raw && typeof raw === 'object') {
|
|
90
|
+
list = Array.isArray(raw.models) ? raw.models : Array.isArray(raw.data) ? raw.data : [];
|
|
91
|
+
}
|
|
92
|
+
const ids = [];
|
|
93
|
+
for (const item of list) {
|
|
94
|
+
const id = typeof item === 'string' ? item : item?.id ?? item?.model ?? item?.name;
|
|
95
|
+
if (nonemptyString(id) && id.trim() !== AUTO_MODEL) ids.push(id.trim());
|
|
96
|
+
}
|
|
97
|
+
return [...new Set(ids)];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Host contract calls listModels(provider); older WP3 mocks accepted {provider}.
|
|
101
|
+
export async function listModelIds(llm, provider) {
|
|
102
|
+
if (!llm || typeof llm.listModels !== 'function') return { ok: false, ids: [] };
|
|
103
|
+
let raw;
|
|
104
|
+
try {
|
|
105
|
+
raw = await llm.listModels(provider);
|
|
106
|
+
} catch {
|
|
107
|
+
try {
|
|
108
|
+
raw = await llm.listModels({ provider });
|
|
109
|
+
} catch {
|
|
110
|
+
return { ok: false, ids: [] };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return { ok: true, ids: modelIdsOf(raw) };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function supportedReasoningEffort(llm, provider, model, effort, warnings) {
|
|
117
|
+
const wanted = nonemptyString(effort);
|
|
118
|
+
if (!wanted) return null;
|
|
119
|
+
if (!llm || typeof llm.resolveModelInfo !== 'function') return wanted;
|
|
120
|
+
let info;
|
|
121
|
+
try {
|
|
122
|
+
info = await llm.resolveModelInfo(provider, model);
|
|
123
|
+
} catch {
|
|
124
|
+
// Metadata is advisory; a probe failure must not drop a requested effort.
|
|
125
|
+
return wanted;
|
|
126
|
+
}
|
|
127
|
+
const declared = info?.reasoning?.efforts;
|
|
128
|
+
if (Array.isArray(declared) && declared.length > 0) {
|
|
129
|
+
const ids = declared
|
|
130
|
+
.map((entry) => (typeof entry === 'string' ? entry : entry?.id))
|
|
131
|
+
.filter((entry) => nonemptyString(entry));
|
|
132
|
+
if (ids.length > 0 && !ids.includes(wanted)) {
|
|
133
|
+
if (!warnings.includes(REASONING_EFFORT_UNSUPPORTED)) warnings.push(REASONING_EFFORT_UNSUPPORTED);
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return wanted;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function blocked(reason, message, extra = {}) {
|
|
141
|
+
return {
|
|
142
|
+
ok: false,
|
|
143
|
+
code: 'E_NO_PROVIDER',
|
|
144
|
+
reason,
|
|
145
|
+
message,
|
|
146
|
+
candidates: Array.isArray(extra.candidates) ? extra.candidates : [],
|
|
147
|
+
...extra,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function candidatesText(candidates) {
|
|
152
|
+
return candidates.length > 0 ? candidates.join(', ') : 'none';
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Resolve the effective provider/model pair for one start (and for auto re-resolve).
|
|
157
|
+
*
|
|
158
|
+
* @param {object} input
|
|
159
|
+
* @param {object} input.config normalized Router config (provider, model, providerExplicit)
|
|
160
|
+
* @param {object} input.ctx plugin context (ctx.get only; ctx.llm is forbidden)
|
|
161
|
+
* @param {object|null} input.llm llm service or null
|
|
162
|
+
* @param {string|null} [input.explicitReasoningEffort] future/lead-provided effort override
|
|
163
|
+
* @returns {Promise<object>} {ok:true, provider, providerSource, providerExplicit,
|
|
164
|
+
* providerCandidates, auto, model, modelSource, reasoningEffort, warnings, candidates}
|
|
165
|
+
* or {ok:false, code:'E_NO_PROVIDER', reason, message, candidates}
|
|
166
|
+
*/
|
|
167
|
+
export async function resolveModelTarget({ config, ctx, llm, explicitReasoningEffort = null } = {}) {
|
|
168
|
+
const cfg = config && typeof config === 'object' ? config : {};
|
|
169
|
+
const warnings = [];
|
|
170
|
+
const configuredProvider = nonemptyString(cfg.provider);
|
|
171
|
+
const configuredModel = nonemptyString(cfg.model);
|
|
172
|
+
const providerExplicit = cfg.providerExplicit === true;
|
|
173
|
+
const selection = readCurrentSelection(ctx);
|
|
174
|
+
|
|
175
|
+
// ---- provider (D-WP5-6) -------------------------------------------------
|
|
176
|
+
let provider;
|
|
177
|
+
let providerSource;
|
|
178
|
+
if (providerExplicit && configuredProvider) {
|
|
179
|
+
provider = configuredProvider;
|
|
180
|
+
providerSource = 'explicit';
|
|
181
|
+
} else if (selection) {
|
|
182
|
+
provider = selection.provider;
|
|
183
|
+
providerSource = 'host-default';
|
|
184
|
+
} else if (configuredProvider && configuredProvider !== DEFAULT_PROVIDER) {
|
|
185
|
+
provider = configuredProvider;
|
|
186
|
+
providerSource = 'configured';
|
|
187
|
+
} else {
|
|
188
|
+
provider = DEFAULT_PROVIDER;
|
|
189
|
+
providerSource = 'default';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const providerList = await listProviderIds(llm);
|
|
193
|
+
let providerCandidates = providerList.ids;
|
|
194
|
+
if (Array.isArray(providerCandidates) && providerCandidates.length === 0) {
|
|
195
|
+
return blocked('no_providers', 'llm.listProviders() returned no providers', {
|
|
196
|
+
candidates: [],
|
|
197
|
+
providerExplicit,
|
|
198
|
+
providerSource,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
if (Array.isArray(providerCandidates) && !providerCandidates.includes(provider)) {
|
|
202
|
+
if (providerSource === 'explicit') {
|
|
203
|
+
return blocked(
|
|
204
|
+
'provider_not_registered',
|
|
205
|
+
`provider "${provider}" is not registered (candidates: ${candidatesText(providerCandidates)})`,
|
|
206
|
+
{ candidates: providerCandidates, providerExplicit, providerSource },
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
if (providerCandidates.includes(DEFAULT_PROVIDER)) {
|
|
210
|
+
provider = DEFAULT_PROVIDER;
|
|
211
|
+
providerSource = 'default';
|
|
212
|
+
} else {
|
|
213
|
+
provider = providerCandidates[0];
|
|
214
|
+
providerSource = 'fallback';
|
|
215
|
+
warnings.push(PROVIDER_FALLBACK);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- model (D-WP5-1/2/3) ------------------------------------------------
|
|
220
|
+
const explicitModel = configuredModel && configuredModel !== AUTO_MODEL ? configuredModel : '';
|
|
221
|
+
|
|
222
|
+
if (explicitModel) {
|
|
223
|
+
const listed = await listModelIds(llm, provider);
|
|
224
|
+
let unlisted = false;
|
|
225
|
+
if (listed.ok && listed.ids.length > 0 && !listed.ids.includes(explicitModel)) {
|
|
226
|
+
unlisted = true;
|
|
227
|
+
warnings.push(MODEL_UNLISTED);
|
|
228
|
+
}
|
|
229
|
+
const inherited = nonemptyString(explicitReasoningEffort);
|
|
230
|
+
const reasoningEffort = inherited
|
|
231
|
+
? await supportedReasoningEffort(llm, provider, explicitModel, inherited, warnings)
|
|
232
|
+
: null;
|
|
233
|
+
return {
|
|
234
|
+
ok: true,
|
|
235
|
+
provider,
|
|
236
|
+
providerSource,
|
|
237
|
+
providerExplicit,
|
|
238
|
+
providerCandidates,
|
|
239
|
+
auto: false,
|
|
240
|
+
model: explicitModel,
|
|
241
|
+
modelSource: 'explicit',
|
|
242
|
+
reasoningEffort,
|
|
243
|
+
warnings,
|
|
244
|
+
unlisted,
|
|
245
|
+
candidates: listed.ids,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (!configuredModel) {
|
|
250
|
+
return blocked('empty_model', 'routerProvider/routerModel is empty', {
|
|
251
|
+
candidates: providerCandidates ?? [],
|
|
252
|
+
providerExplicit,
|
|
253
|
+
providerSource,
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// configuredModel === 'auto'
|
|
258
|
+
const hostMatch = selection && selection.provider === provider ? selection.model : '';
|
|
259
|
+
let model = '';
|
|
260
|
+
let modelSource = '';
|
|
261
|
+
let reasoningEffort = null;
|
|
262
|
+
|
|
263
|
+
if (hostMatch) {
|
|
264
|
+
model = hostMatch;
|
|
265
|
+
modelSource = 'host-default';
|
|
266
|
+
const wanted = nonemptyString(explicitReasoningEffort) || nonemptyString(selection.reasoningEffort);
|
|
267
|
+
reasoningEffort = await supportedReasoningEffort(llm, provider, model, wanted, warnings);
|
|
268
|
+
} else {
|
|
269
|
+
const listed = await listModelIds(llm, provider);
|
|
270
|
+
if (!listed.ok || listed.ids.length === 0) {
|
|
271
|
+
return blocked(
|
|
272
|
+
'no_model_candidates',
|
|
273
|
+
`routerModel=auto could not be resolved: llm.listModels("${provider}") returned no models`,
|
|
274
|
+
{ candidates: [], providerExplicit, providerSource },
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
const stable = listed.ids.filter((id) => !isPreviewModelId(id));
|
|
278
|
+
if (stable.length === 0) {
|
|
279
|
+
return blocked(
|
|
280
|
+
'no_stable_model_candidate',
|
|
281
|
+
`routerModel=auto could not be resolved: all candidates are preview/experimental (candidates: ${candidatesText(listed.ids)})`,
|
|
282
|
+
{ candidates: listed.ids, providerExplicit, providerSource },
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
model = stable[0];
|
|
286
|
+
modelSource = 'list-order';
|
|
287
|
+
warnings.push(MODEL_AUTO_PICKED_LIST_ORDER);
|
|
288
|
+
const wanted = nonemptyString(explicitReasoningEffort) || nonemptyString(selection?.reasoningEffort);
|
|
289
|
+
reasoningEffort = await supportedReasoningEffort(llm, provider, model, wanted, warnings);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return {
|
|
293
|
+
ok: true,
|
|
294
|
+
provider,
|
|
295
|
+
providerSource,
|
|
296
|
+
providerExplicit,
|
|
297
|
+
providerCandidates,
|
|
298
|
+
auto: true,
|
|
299
|
+
model,
|
|
300
|
+
modelSource,
|
|
301
|
+
reasoningEffort,
|
|
302
|
+
warnings,
|
|
303
|
+
unlisted: false,
|
|
304
|
+
candidates: [],
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// Re-resolve path used by the `llm/adapters-updated` listener. Never throws.
|
|
309
|
+
export async function resolveAutoModelOnly({ config, ctx, llm } = {}) {
|
|
310
|
+
try {
|
|
311
|
+
return await resolveModelTarget({ config, ctx, llm, explicitReasoningEffort: null });
|
|
312
|
+
} catch (error) {
|
|
313
|
+
return blocked('resolver_error', `model resolver failed: ${error?.message ?? 'unknown error'}`, { candidates: [] });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* D-WP5-5 host failure mapping.
|
|
319
|
+
* terminal=true means Router blocks with routerCode. retryable=true keeps the
|
|
320
|
+
* existing backoff path and never turns a transient provider hiccup into a
|
|
321
|
+
* permanent block.
|
|
322
|
+
*/
|
|
323
|
+
export function mapProviderFailure(code, options = {}) {
|
|
324
|
+
const hostCode = nonemptyString(code) || 'UNKNOWN';
|
|
325
|
+
const upper = hostCode.toUpperCase();
|
|
326
|
+
const rawRetry = Number(options.retryAfterMs);
|
|
327
|
+
const retryAfterMs = Number.isFinite(rawRetry) && rawRetry >= 0 ? Math.min(rawRetry, 300000) : null;
|
|
328
|
+
|
|
329
|
+
if (upper === 'ABORTED') {
|
|
330
|
+
return { routerCode: 'E_ABORTED', hostCode, terminal: false, aborted: true, retryable: false, retryAfterMs: null };
|
|
331
|
+
}
|
|
332
|
+
if (['NO_ADAPTER', 'MISSING_CREDENTIAL', 'INVALID_CREDENTIAL', 'AUTH'].includes(upper)) {
|
|
333
|
+
return { routerCode: 'E_NO_PROVIDER', hostCode, terminal: true, reason: 'provider_auth', retryAfterMs: null };
|
|
334
|
+
}
|
|
335
|
+
if (upper === 'RATE_LIMIT' || upper === 'ACCOUNT_QUOTA' || upper === 'HTTP_429') {
|
|
336
|
+
return { routerCode: 'E_RATE_LIMITED', hostCode, terminal: false, rateLimited: true, retryable: true, retryAfterMs };
|
|
337
|
+
}
|
|
338
|
+
if (upper === 'QUOTA') {
|
|
339
|
+
return { routerCode: 'E_QUOTA', hostCode, terminal: true, retryAfterMs: null };
|
|
340
|
+
}
|
|
341
|
+
if (upper === 'CONTEXT_WINDOW_EXCEEDED') {
|
|
342
|
+
return { routerCode: 'E_CONTEXT_WINDOW', hostCode, terminal: true, retryAfterMs: null };
|
|
343
|
+
}
|
|
344
|
+
if (['TIMEOUT', 'TRANSPORT', 'SERVER', 'EMPTY_RESPONSE'].includes(upper) || /^HTTP_5\d\d$/.test(upper)) {
|
|
345
|
+
return { routerCode: 'E_PROVIDER_FAILED', hostCode, terminal: false, retryable: true, retryAfterMs };
|
|
346
|
+
}
|
|
347
|
+
return { routerCode: 'E_PROVIDER_FAILED', hostCode, terminal: true, retryAfterMs: null };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
export const HOST_AUTH_CODES = Object.freeze(['NO_ADAPTER', 'MISSING_CREDENTIAL', 'INVALID_CREDENTIAL', 'AUTH']);
|