@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,517 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* D6 runtime — the Cordis side of the tool-surface trimmer.
|
|
3
|
+
*
|
|
4
|
+
* Design constraints, in order:
|
|
5
|
+
* 1. The first `tools.resolve()` of a session must already see the reduced
|
|
6
|
+
* surface. `agent/inbox/claimed` is emitted synchronously inside
|
|
7
|
+
* ReactLoopInbox.claim, before preStep calls tools.resolve, so this is the
|
|
8
|
+
* only hook that can freeze the allowlist in time on both host shapes.
|
|
9
|
+
* For a session restored after a host restart the first claim is turn N>1;
|
|
10
|
+
* the runtime still freezes there (once per process), see onClaimed.
|
|
11
|
+
* 2. The allowlist is frozen for the session. `tool_search` is the only
|
|
12
|
+
* operation allowed to grow it, and it grows by appending at the end.
|
|
13
|
+
* 3. 0.2.2 filters through `agent.ctx.tools.restrict({deny})`; 0.2.1 does too
|
|
14
|
+
* when the service exists, and the `system-prompt/assemble` adapter keeps
|
|
15
|
+
* the same frozen set on hosts whose assemble result owns `tools`.
|
|
16
|
+
* 4. Any unexpected input shape or thrown host call degrades to the full
|
|
17
|
+
* surface. A broken filter must never cost the session its tools.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
assembleShape,
|
|
22
|
+
filterAssembly,
|
|
23
|
+
messageText,
|
|
24
|
+
selectAllowlist,
|
|
25
|
+
} from './surface.js';
|
|
26
|
+
import { warnOnce } from '../host-version.js';
|
|
27
|
+
|
|
28
|
+
export const TOOL_SEARCH_NAME = 'tool_search';
|
|
29
|
+
|
|
30
|
+
/** The model-facing definition, exported so the budget test measures the real thing. */
|
|
31
|
+
export const TOOL_SEARCH_SPEC = {
|
|
32
|
+
name: TOOL_SEARCH_NAME,
|
|
33
|
+
description:
|
|
34
|
+
'List tools trimmed from this session, or request one. Call with names to append them ' +
|
|
35
|
+
'to the tool list; call with query to search. Added tools appear at the end on the next step.',
|
|
36
|
+
// Host contract (`dsh-tools` `defineTool`): `parameters` is a map of argument
|
|
37
|
+
// name -> *value schema*, not a JSON Schema object. Wrapping this in
|
|
38
|
+
// {type:'object', properties} makes 0.2.2-rc.1 throw
|
|
39
|
+
// "parameters.type must be a value schema object" while it builds the tool.
|
|
40
|
+
parameters: {
|
|
41
|
+
names: {
|
|
42
|
+
type: 'array',
|
|
43
|
+
items: { type: 'string' },
|
|
44
|
+
description: 'Exact trimmed tool names to add.',
|
|
45
|
+
},
|
|
46
|
+
query: {
|
|
47
|
+
type: 'string',
|
|
48
|
+
description: 'Keyword search over trimmed tool names and descriptions.',
|
|
49
|
+
},
|
|
50
|
+
limit: {
|
|
51
|
+
type: 'integer',
|
|
52
|
+
description: 'Maximum matches to list (1-20, default 8).',
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
output: {
|
|
56
|
+
schema: { type: 'object', additionalProperties: true },
|
|
57
|
+
// Host contract (`dsh-tools` pipeline.createSuccessResult): the return value
|
|
58
|
+
// of `render` becomes the tool-result message `content` verbatim. 0.2.2
|
|
59
|
+
// walks that content as typed blocks (dsh-llm `contentHasImage` calls
|
|
60
|
+
// `content.some(...)`), so a string makes the host throw
|
|
61
|
+
// "content.some is not a function". Every other tool in this package renders
|
|
62
|
+
// through `OUTPUT_TEXT`; tool_search must use the same array-of-text-blocks
|
|
63
|
+
// shape.
|
|
64
|
+
render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const MAX_MATCHES = 20;
|
|
69
|
+
const MAX_DESCRIPTION = 180;
|
|
70
|
+
|
|
71
|
+
function loggerOf(ctx) {
|
|
72
|
+
try {
|
|
73
|
+
const logger = typeof ctx?.logger === 'function' ? ctx.logger('longlive') : ctx?.logger;
|
|
74
|
+
return logger && typeof logger === 'object' ? logger : null;
|
|
75
|
+
} catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function info(ctx, text) {
|
|
81
|
+
const logger = loggerOf(ctx);
|
|
82
|
+
if (logger && typeof logger.info === 'function') {
|
|
83
|
+
try {
|
|
84
|
+
logger.info(text);
|
|
85
|
+
return;
|
|
86
|
+
} catch {
|
|
87
|
+
/* fall through */
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
console.log(`[dsh-longlive] ${text}`);
|
|
92
|
+
} catch {
|
|
93
|
+
/* a host without console must not break the plugin */
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function warn(ctx, text) {
|
|
98
|
+
warnOnce(ctx, text);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A host message is a real user turn only when the host says so. */
|
|
102
|
+
function isRealUserMessage(message) {
|
|
103
|
+
if (message === null || typeof message !== 'object') return false;
|
|
104
|
+
const kind = message.source?.kind;
|
|
105
|
+
if (kind !== undefined && kind !== null && kind !== 'user') return false;
|
|
106
|
+
if (message.role !== 'user' && kind !== 'user') return false;
|
|
107
|
+
return messageText(message).trim().length > 0;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Visible model-facing schemas for one agent, with graceful fallbacks. */
|
|
111
|
+
function listTools(agent) {
|
|
112
|
+
const tools = agent?.ctx?.tools;
|
|
113
|
+
if (!tools) return [];
|
|
114
|
+
try {
|
|
115
|
+
if (typeof tools.schemas === 'function') {
|
|
116
|
+
const value = tools.schemas(agent);
|
|
117
|
+
if (Array.isArray(value)) return value;
|
|
118
|
+
}
|
|
119
|
+
} catch {
|
|
120
|
+
/* try definitions()/view() below */
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
if (typeof tools.definitions === 'function') {
|
|
124
|
+
const value = tools.definitions(agent);
|
|
125
|
+
if (Array.isArray(value)) return value;
|
|
126
|
+
if (Array.isArray(value?.tools)) return value.tools;
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
/* try view() below */
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
if (typeof tools.view === 'function') {
|
|
133
|
+
const view = tools.view(agent);
|
|
134
|
+
const visible = view?.visible;
|
|
135
|
+
if (visible instanceof Map) {
|
|
136
|
+
return [...visible.values()].map((entry) => entry?.definition ?? entry).filter(Boolean);
|
|
137
|
+
}
|
|
138
|
+
if (Array.isArray(visible)) return visible;
|
|
139
|
+
}
|
|
140
|
+
} catch {
|
|
141
|
+
/* no visible schemas */
|
|
142
|
+
}
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Latest live goal objective, if the goals service is not injected. */
|
|
147
|
+
function readGoal(agent) {
|
|
148
|
+
try {
|
|
149
|
+
const goal = agent?.ctx?.goals?.get?.(agent) ?? agent?.ctx?.goals?.get?.(agent?.session);
|
|
150
|
+
const objective = goal?.objective ?? goal?.goal?.objective;
|
|
151
|
+
const phase = goal?.phase ?? goal?.goal?.phase;
|
|
152
|
+
if (typeof objective === 'string' && phase !== 'complete' && phase !== 'cleared') return objective;
|
|
153
|
+
} catch {
|
|
154
|
+
/* fall through to the event log */
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
const events = agent?.session?.snapshotEvents?.() ?? agent?.session?.eventsSnapshot?.();
|
|
158
|
+
if (!Array.isArray(events)) return '';
|
|
159
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
160
|
+
const event = events[index];
|
|
161
|
+
if (event?.type !== 'goal/change') continue;
|
|
162
|
+
const data = event.data ?? {};
|
|
163
|
+
const goal = data.goal ?? data.change?.goal ?? null;
|
|
164
|
+
if (!goal || typeof goal.objective !== 'string') continue;
|
|
165
|
+
if (goal.phase === 'complete' || goal.phase === 'cleared') return '';
|
|
166
|
+
return goal.objective;
|
|
167
|
+
}
|
|
168
|
+
} catch {
|
|
169
|
+
/* a session without goals is the normal case */
|
|
170
|
+
}
|
|
171
|
+
return '';
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function requestableNames(agent, names) {
|
|
175
|
+
const tools = agent?.ctx?.tools;
|
|
176
|
+
if (!tools || typeof tools.view !== 'function') return names;
|
|
177
|
+
try {
|
|
178
|
+
const view = tools.view(agent);
|
|
179
|
+
const restrictable = view?.restrictableNames;
|
|
180
|
+
if (restrictable instanceof Set) return names.filter((name) => restrictable.has(name));
|
|
181
|
+
if (Array.isArray(restrictable)) return names.filter((name) => restrictable.includes(name));
|
|
182
|
+
} catch {
|
|
183
|
+
/* let restrict() report the real error */
|
|
184
|
+
}
|
|
185
|
+
return names;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Apply the frozen allowlist as a host restriction.
|
|
190
|
+
* Returns false when the host has no scoped restrict() (the 0.2.1 shape).
|
|
191
|
+
*/
|
|
192
|
+
function applyRestriction(agent, state, restrictions) {
|
|
193
|
+
const tools = agent?.ctx?.tools;
|
|
194
|
+
if (!tools || typeof tools.restrict !== 'function') return false;
|
|
195
|
+
const deny = requestableNames(agent, state.deny);
|
|
196
|
+
const old = state.restriction;
|
|
197
|
+
let next = null;
|
|
198
|
+
try {
|
|
199
|
+
if (deny.length > 0) next = tools.restrict({ deny });
|
|
200
|
+
} catch (error) {
|
|
201
|
+
state.restriction = old;
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
state.restriction = next;
|
|
205
|
+
if (next) restrictions.add(next);
|
|
206
|
+
if (old) {
|
|
207
|
+
restrictions.delete(old);
|
|
208
|
+
try {
|
|
209
|
+
old();
|
|
210
|
+
} catch {
|
|
211
|
+
/* disposal is best effort */
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
state.applied = true;
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function descriptionOf(value) {
|
|
219
|
+
const text = typeof value?.description === 'string' ? value.description : '';
|
|
220
|
+
return text.length > MAX_DESCRIPTION ? `${text.slice(0, MAX_DESCRIPTION - 1)}…` : text;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function matchTrimmed(state, args) {
|
|
224
|
+
const trimmed = state.trimmed;
|
|
225
|
+
const names = Array.isArray(args?.names) ? args.names.filter((name) => typeof name === 'string') : [];
|
|
226
|
+
const query = typeof args?.query === 'string' ? args.query.trim() : '';
|
|
227
|
+
const requestable = trimmed.filter((name) => !state.allow.has(name));
|
|
228
|
+
let matches = [];
|
|
229
|
+
if (names.length > 0) {
|
|
230
|
+
const wanted = new Set(names);
|
|
231
|
+
matches = requestable.filter((name) => wanted.has(name));
|
|
232
|
+
} else if (query !== '') {
|
|
233
|
+
const needle = query.toLowerCase();
|
|
234
|
+
matches = requestable.filter((name) => {
|
|
235
|
+
const tool = state.byName.get(name);
|
|
236
|
+
return `${name} ${tool?.description ?? ''}`.toLowerCase().includes(needle);
|
|
237
|
+
});
|
|
238
|
+
} else {
|
|
239
|
+
matches = requestable;
|
|
240
|
+
}
|
|
241
|
+
const limitValue = Number(args?.limit);
|
|
242
|
+
const limit = Number.isFinite(limitValue) && limitValue > 0
|
|
243
|
+
? Math.min(Math.floor(limitValue), MAX_MATCHES)
|
|
244
|
+
: 8;
|
|
245
|
+
return matches.slice(0, limit);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function makeToolSearch(runtime) {
|
|
249
|
+
return {
|
|
250
|
+
...TOOL_SEARCH_SPEC,
|
|
251
|
+
// registerTools() owns the host-facing execute wrapper and calls invoke().
|
|
252
|
+
invoke: (args, config) => runtime.toolSearch(args, config),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* @param {{config?: object}} input
|
|
258
|
+
*/
|
|
259
|
+
export function createD6Runtime({ config = {} } = {}) {
|
|
260
|
+
const d6 = config?.d6 ?? {};
|
|
261
|
+
const dryRun = d6.dryRun === true;
|
|
262
|
+
const logTrim = d6.log !== false;
|
|
263
|
+
const states = new WeakMap();
|
|
264
|
+
const restrictions = new Set();
|
|
265
|
+
|
|
266
|
+
function stateFor(agent) {
|
|
267
|
+
if (!agent || (typeof agent !== 'object' && typeof agent !== 'function')) return null;
|
|
268
|
+
let state = states.get(agent);
|
|
269
|
+
if (!state) {
|
|
270
|
+
state = {
|
|
271
|
+
frozen: false,
|
|
272
|
+
task: 'general',
|
|
273
|
+
allow: new Set(),
|
|
274
|
+
deny: [],
|
|
275
|
+
requested: [],
|
|
276
|
+
trimmed: [],
|
|
277
|
+
byName: new Map(),
|
|
278
|
+
fullTools: [],
|
|
279
|
+
applied: false,
|
|
280
|
+
fallback: null,
|
|
281
|
+
restriction: null,
|
|
282
|
+
shape: null,
|
|
283
|
+
restrictAvailable: true,
|
|
284
|
+
};
|
|
285
|
+
states.set(agent, state);
|
|
286
|
+
}
|
|
287
|
+
return state;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Called from the synchronous `agent/inbox/claimed` listener.
|
|
292
|
+
*
|
|
293
|
+
* Freeze on the first real user turn this host process sees, not on literal
|
|
294
|
+
* turn 1. A session restored after a host restart resumes at turn N > 1, so
|
|
295
|
+
* the old `turn > 1` guard meant it could never freeze: `tool_search` stayed
|
|
296
|
+
* `D6_NOT_FROZEN` and the surface was never trimmed for the rest of its life
|
|
297
|
+
* (G3, docs/CONFIG.md §1.4). The `state.frozen` guard below keeps ordinary
|
|
298
|
+
* sessions on the original "freeze once, never re-freeze" semantics.
|
|
299
|
+
*/
|
|
300
|
+
function onClaimed(payload) {
|
|
301
|
+
try {
|
|
302
|
+
const agent = payload?.agent;
|
|
303
|
+
const message = payload?.message;
|
|
304
|
+
if (!agent) return;
|
|
305
|
+
const state = stateFor(agent);
|
|
306
|
+
if (!state || state.frozen) return;
|
|
307
|
+
if (!isRealUserMessage(message)) return;
|
|
308
|
+
|
|
309
|
+
state.frozen = true;
|
|
310
|
+
let selection;
|
|
311
|
+
let tools = [];
|
|
312
|
+
try {
|
|
313
|
+
const goal = readGoal(agent);
|
|
314
|
+
tools = listTools(agent);
|
|
315
|
+
selection = selectAllowlist({ goal, message, tools, config: d6 });
|
|
316
|
+
} catch (error) {
|
|
317
|
+
state.fallback = 'full';
|
|
318
|
+
warn(payload?.agent?.ctx ?? null, `[d6] selection failed, keeping the full surface: ${error?.message ?? error}`);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
state.task = selection.task;
|
|
323
|
+
state.trimmed = selection.trimmed;
|
|
324
|
+
state.fullTools = tools;
|
|
325
|
+
state.byName = new Map(state.fullTools.map((tool) => [tool.name, tool]));
|
|
326
|
+
state.allow = new Set(selection.allow);
|
|
327
|
+
state.deny = requestableNames(agent, selection.trimmed);
|
|
328
|
+
|
|
329
|
+
if (selection.fallback || selection.keepCount === 0) {
|
|
330
|
+
state.fallback = 'full';
|
|
331
|
+
warn(agent.ctx ?? null, '[d6] no tool survived the core filter, keeping the full surface');
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
if (logTrim) {
|
|
336
|
+
const names = state.trimmed.length > 0 ? state.trimmed.join(',') : '-';
|
|
337
|
+
info(
|
|
338
|
+
agent.ctx ?? null,
|
|
339
|
+
`[d6]${dryRun ? ' dry-run' : ''} task=${state.task} keep=${selection.keepCount} ` +
|
|
340
|
+
`trim=${state.trimmed.length} shape=${state.shape ?? 'pending'} names=${names}`,
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
if (dryRun) return;
|
|
344
|
+
|
|
345
|
+
try {
|
|
346
|
+
const applied = applyRestriction(agent, state, restrictions);
|
|
347
|
+
state.restrictAvailable = applied;
|
|
348
|
+
if (!applied) info(agent.ctx ?? null, '[d6] host has no tools.restrict(); using the 0.2.1 assemble adapter');
|
|
349
|
+
} catch (error) {
|
|
350
|
+
state.fallback = 'full';
|
|
351
|
+
state.applied = false;
|
|
352
|
+
warn(agent.ctx ?? null, `[d6] tools.restrict() failed, keeping the full surface: ${error?.message ?? error}`);
|
|
353
|
+
}
|
|
354
|
+
} catch (error) {
|
|
355
|
+
warn(null, `[d6] claimed hook failed: ${error?.message ?? error}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Called after the assemble waterfall's inner chain has produced a value. */
|
|
360
|
+
function onAssemble(assembly, context) {
|
|
361
|
+
try {
|
|
362
|
+
const agent = context?.agent ?? context?.scope;
|
|
363
|
+
const state = agent ? states.get(agent) : null;
|
|
364
|
+
if (!state || !state.frozen) return assembly;
|
|
365
|
+
const shape = assembleShape(assembly);
|
|
366
|
+
if (state.shape === null) {
|
|
367
|
+
state.shape = shape;
|
|
368
|
+
info(agent.ctx ?? null, `[d6] assemble shape=${shape}`);
|
|
369
|
+
}
|
|
370
|
+
if (dryRun || state.fallback === 'full') return assembly;
|
|
371
|
+
if (shape === '0.2.2') return assembly;
|
|
372
|
+
const result = filterAssembly(assembly, {
|
|
373
|
+
allow: state.allow,
|
|
374
|
+
requested: state.requested,
|
|
375
|
+
fullTools: state.fullTools,
|
|
376
|
+
});
|
|
377
|
+
if (result.fallback) {
|
|
378
|
+
state.fallback = 'full';
|
|
379
|
+
warn(agent.ctx ?? null, '[d6] assemble filter would be empty, keeping the full surface');
|
|
380
|
+
return assembly;
|
|
381
|
+
}
|
|
382
|
+
return result.assembly;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
try {
|
|
385
|
+
warn(null, `[d6] assemble adapter failed, keeping the full surface: ${error?.message ?? error}`);
|
|
386
|
+
} catch {
|
|
387
|
+
/* ignore */
|
|
388
|
+
}
|
|
389
|
+
return assembly;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** The body of the model-facing `tool_search` tool. */
|
|
394
|
+
function toolSearch(args, config) {
|
|
395
|
+
try {
|
|
396
|
+
const agent = config?.exec?.agent;
|
|
397
|
+
const state = agent ? states.get(agent) : null;
|
|
398
|
+
if (!state || !state.frozen) {
|
|
399
|
+
return { ok: false, error: 'D6_NOT_FROZEN', message: 'tool_search is only available on a frozen D6 session.' };
|
|
400
|
+
}
|
|
401
|
+
if (dryRun) {
|
|
402
|
+
return { ok: false, error: 'D6_DRY_RUN', message: 'D6 is in dry-run mode; the surface was not trimmed.' };
|
|
403
|
+
}
|
|
404
|
+
const matchedNames = matchTrimmed(state, args);
|
|
405
|
+
const hasRequest = (Array.isArray(args?.names) && args.names.length > 0) || (typeof args?.query === 'string' && args.query.trim() !== '');
|
|
406
|
+
const matched = matchedNames.map((name) => ({ name, description: descriptionOf(state.byName.get(name)) }));
|
|
407
|
+
if (!hasRequest) {
|
|
408
|
+
return {
|
|
409
|
+
ok: true,
|
|
410
|
+
task: state.task,
|
|
411
|
+
matched,
|
|
412
|
+
totalTrimmed: state.trimmed.length,
|
|
413
|
+
hint: 'Pass names to append tools, or query to search.',
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
if (matchedNames.length === 0) {
|
|
417
|
+
return { ok: true, task: state.task, added: [], matched: [], totalTrimmed: state.trimmed.length };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const beforeAllow = new Set(state.allow);
|
|
421
|
+
const beforeDeny = [...state.deny];
|
|
422
|
+
const beforeRequested = [...state.requested];
|
|
423
|
+
for (const name of matchedNames) {
|
|
424
|
+
state.allow.add(name);
|
|
425
|
+
if (!state.requested.includes(name)) state.requested.push(name);
|
|
426
|
+
state.deny = state.deny.filter((entry) => entry !== name);
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
if (state.restrictAvailable) {
|
|
430
|
+
const applied = applyRestriction(agent, state, restrictions);
|
|
431
|
+
state.restrictAvailable = applied || state.restrictAvailable;
|
|
432
|
+
}
|
|
433
|
+
} catch (error) {
|
|
434
|
+
state.allow = beforeAllow;
|
|
435
|
+
state.deny = beforeDeny;
|
|
436
|
+
state.requested = beforeRequested;
|
|
437
|
+
return { ok: false, error: 'D6_ADD_FAILED', message: String(error?.message ?? error) };
|
|
438
|
+
}
|
|
439
|
+
return {
|
|
440
|
+
ok: true,
|
|
441
|
+
task: state.task,
|
|
442
|
+
added: matchedNames,
|
|
443
|
+
matched,
|
|
444
|
+
totalTrimmed: state.trimmed.length,
|
|
445
|
+
note: 'Added tools appear at the end of the tool list on the next step.',
|
|
446
|
+
};
|
|
447
|
+
} catch (error) {
|
|
448
|
+
return { ok: false, error: 'D6_TOOL_SEARCH_FAILED', message: String(error?.message ?? error) };
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function dispose() {
|
|
453
|
+
for (const restriction of restrictions) {
|
|
454
|
+
try {
|
|
455
|
+
restriction();
|
|
456
|
+
} catch {
|
|
457
|
+
/* ignore */
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
restrictions.clear();
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
return { onClaimed, onAssemble, toolSearch, dispose, stateFor };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Register D6 if (and only if) `config.d6.enabled === true`.
|
|
468
|
+
*
|
|
469
|
+
* @returns {{enabled: boolean, tools: object[], runtime?: object}}
|
|
470
|
+
*/
|
|
471
|
+
export function registerD6(ctx, config = {}) {
|
|
472
|
+
if (config?.d6?.enabled !== true) return { enabled: false, tools: [] };
|
|
473
|
+
const runtime = createD6Runtime({ config });
|
|
474
|
+
const disposers = [];
|
|
475
|
+
try {
|
|
476
|
+
const dispose = ctx.on('agent/inbox/claimed', (payload) => runtime.onClaimed(payload));
|
|
477
|
+
if (typeof dispose === 'function') disposers.push(dispose);
|
|
478
|
+
} catch (error) {
|
|
479
|
+
warn(ctx, `[d6] cannot listen for agent/inbox/claimed: ${error?.message ?? error}`);
|
|
480
|
+
}
|
|
481
|
+
try {
|
|
482
|
+
const dispose = ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
|
483
|
+
let result = assembly;
|
|
484
|
+
try {
|
|
485
|
+
if (typeof next === 'function') result = await next();
|
|
486
|
+
} catch (error) {
|
|
487
|
+
warn(ctx, `[d6] inner assemble failed, keeping the full surface: ${error?.message ?? error}`);
|
|
488
|
+
return assembly;
|
|
489
|
+
}
|
|
490
|
+
return runtime.onAssemble(result, context);
|
|
491
|
+
});
|
|
492
|
+
if (typeof dispose === 'function') disposers.push(dispose);
|
|
493
|
+
} catch (error) {
|
|
494
|
+
warn(ctx, `[d6] cannot listen for system-prompt/assemble: ${error?.message ?? error}`);
|
|
495
|
+
}
|
|
496
|
+
if (typeof ctx?.effect === 'function') {
|
|
497
|
+
try {
|
|
498
|
+
ctx.effect(() => () => {
|
|
499
|
+
for (const dispose of disposers) {
|
|
500
|
+
try {
|
|
501
|
+
dispose();
|
|
502
|
+
} catch {
|
|
503
|
+
/* ignore */
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
runtime.dispose();
|
|
507
|
+
}, 'longlive.d6');
|
|
508
|
+
} catch {
|
|
509
|
+
/* fake context without an effect scope */
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return {
|
|
513
|
+
enabled: true,
|
|
514
|
+
tools: config?.d6?.dryRun === true ? [] : [makeToolSearch(runtime)],
|
|
515
|
+
runtime,
|
|
516
|
+
};
|
|
517
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* D6 — tool-surface trimming, pure decisions.
|
|
3
|
+
*
|
|
4
|
+
* Everything in this file is deliberately host-free: it takes plain tool
|
|
5
|
+
* schemas and a plain message, and returns plain sets/lists. The runtime in
|
|
6
|
+
* `runtime.js` owns the Cordis wiring and the per-session freeze; this file owns
|
|
7
|
+
* the policy that the unit tests pin.
|
|
8
|
+
*
|
|
9
|
+
* The one rule that is not policy: the core surface is never trimmed. A
|
|
10
|
+
* trimmed tool is still reachable through `tool_search`, which lifts its
|
|
11
|
+
* restriction and lets the host append it at the end of the next request.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export const CORE_EXACT = Object.freeze([
|
|
15
|
+
'read',
|
|
16
|
+
'write',
|
|
17
|
+
'edit',
|
|
18
|
+
'pwsh',
|
|
19
|
+
'glob',
|
|
20
|
+
'grep',
|
|
21
|
+
'todo',
|
|
22
|
+
'todo_write',
|
|
23
|
+
'tool_search',
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
/** Tools the spec names individually, plus every session_* / memory_* tool. */
|
|
27
|
+
export function isCoreTool(name) {
|
|
28
|
+
if (typeof name !== 'string' || name === '') return false;
|
|
29
|
+
if (CORE_EXACT.includes(name)) return true;
|
|
30
|
+
return name.startsWith('session_') || name.startsWith('memory_');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const CODE_WORDS = [
|
|
34
|
+
'代码', '编程', '实现', '修复', '测试', '重构', '构建', '部署', '脚本', '函数',
|
|
35
|
+
'接口', '仓库', '编译', '调试', '报错', '类型', '单元测试', '命令行', '补丁', '提交',
|
|
36
|
+
'code', 'coding', 'implement', 'fix', 'bug', 'refactor', 'test', 'build', 'deploy',
|
|
37
|
+
'script', 'function', 'api', 'repo', 'compile', 'debug', 'typescript', 'javascript',
|
|
38
|
+
'python', 'rust', 'golang', 'patch', 'commit', 'lint', 'cli',
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
const MEDIA_WORDS = [
|
|
42
|
+
'图片', '图像', '照片', '视频', '音频', '音乐', '歌曲', '语音', '编曲', '混音',
|
|
43
|
+
'作曲', '乐谱', '扒谱', '分轨', '视觉', '海报', '封面', '表情包', '绘画', '渲染',
|
|
44
|
+
'动画', '镜头', '配音', '朗读', '生成图', '生成视频', '设计图',
|
|
45
|
+
'image', 'photo', 'picture', 'video', 'audio', 'music', 'song', 'sound', 'speech',
|
|
46
|
+
'voice', 'render', 'draw', 'paint', 'visual', 'poster', 'cover', 'meme', 'animation',
|
|
47
|
+
'blender', 'libtv', 'seedance', 'ace studio', 'midi', 'score',
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
const MEDIA_TOOL_RE = /(image|video|audio|music|song|sound|speech|voice|media|meme|render|draw|paint|photo|visual|poster|cover|blender|libtv|seedance|ace[-_ ]?studio|midi|图片|图像|视频|音频|音乐|语音|表情|绘|渲染)/i;
|
|
51
|
+
|
|
52
|
+
const SKIP_DENY = new Set(['run_code', 'tool_search']);
|
|
53
|
+
|
|
54
|
+
/** Count keyword hits, longest words first so a phrase is not double-counted. */
|
|
55
|
+
function scoreWords(haystack, words) {
|
|
56
|
+
const text = haystack.toLowerCase();
|
|
57
|
+
let score = 0;
|
|
58
|
+
for (const word of words) {
|
|
59
|
+
if (!text.includes(word)) continue;
|
|
60
|
+
score += 1;
|
|
61
|
+
if (word.includes(' ')) score += 1;
|
|
62
|
+
}
|
|
63
|
+
return score;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** User-visible text from a host message, a plain string, or a goal object. */
|
|
67
|
+
export function messageText(message) {
|
|
68
|
+
if (typeof message === 'string') return message;
|
|
69
|
+
if (message === null || typeof message !== 'object') return '';
|
|
70
|
+
if (typeof message.text === 'string') return message.text;
|
|
71
|
+
if (typeof message.objective === 'string') return message.objective;
|
|
72
|
+
const content = message.content;
|
|
73
|
+
if (typeof content === 'string') return content;
|
|
74
|
+
if (!Array.isArray(content)) return '';
|
|
75
|
+
const parts = [];
|
|
76
|
+
for (const block of content) {
|
|
77
|
+
if (typeof block === 'string') parts.push(block);
|
|
78
|
+
else if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text);
|
|
79
|
+
}
|
|
80
|
+
return parts.join('\n');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Pick the task family for the first turn. A tie goes to "code" because the
|
|
85
|
+
* code surface is the smaller one and tool_search can recover a media tool.
|
|
86
|
+
*/
|
|
87
|
+
export function classifyTask(goal, message) {
|
|
88
|
+
const text = `${messageText(goal)}\n${messageText(message)}`;
|
|
89
|
+
const media = scoreWords(text, MEDIA_WORDS);
|
|
90
|
+
const code = scoreWords(text, CODE_WORDS);
|
|
91
|
+
if (media > code && media > 0) return 'media';
|
|
92
|
+
if (code > 0) return 'code';
|
|
93
|
+
if (media > 0) return 'media';
|
|
94
|
+
return 'general';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Tools that are obviously useful for a media task even without a matching name. */
|
|
98
|
+
const MEDIA_EXTRA = new Set(['present', 'load_workspace_dependencies']);
|
|
99
|
+
|
|
100
|
+
function isMediaTool(tool, name) {
|
|
101
|
+
if (MEDIA_EXTRA.has(name)) return true;
|
|
102
|
+
// Match the NAME, not the description: a generic tool's description often
|
|
103
|
+
// mentions images/media in passing (decompress, subagent research, ...) and
|
|
104
|
+
// would drag unrelated tools into the media surface.
|
|
105
|
+
return MEDIA_TOOL_RE.test(name);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Compute the frozen allowlist.
|
|
110
|
+
*
|
|
111
|
+
* @param {{goal?: unknown, message?: unknown, tools?: object[], config?: object}} input
|
|
112
|
+
* @returns {{task: string, allow: string[], trimmed: string[], toolNames: string[],
|
|
113
|
+
* keepCount: number, trimmedCount: number, fallback: boolean, reason: string}}
|
|
114
|
+
*/
|
|
115
|
+
export function selectAllowlist({ goal = '', message = '', tools = [], config = {} } = {}) {
|
|
116
|
+
const task = classifyTask(goal, message);
|
|
117
|
+
const list = Array.isArray(tools) ? tools.filter((tool) => typeof tool?.name === 'string' && tool.name !== '') : [];
|
|
118
|
+
const allow = [];
|
|
119
|
+
const trimmed = [];
|
|
120
|
+
const names = [];
|
|
121
|
+
for (const tool of list) {
|
|
122
|
+
const name = tool.name;
|
|
123
|
+
names.push(name);
|
|
124
|
+
let keep = isCoreTool(name);
|
|
125
|
+
if (!keep && task === 'media' && isMediaTool(tool, name)) keep = true;
|
|
126
|
+
// A few profiles want an explicit extra set (tests and future configs).
|
|
127
|
+
if (!keep && Array.isArray(config.keepTools) && config.keepTools.includes(name)) keep = true;
|
|
128
|
+
if (keep) allow.push(name);
|
|
129
|
+
else if (!SKIP_DENY.has(name)) trimmed.push(name);
|
|
130
|
+
}
|
|
131
|
+
// tool_search is core even when a fake context did not include it.
|
|
132
|
+
if (!allow.includes('tool_search')) allow.unshift('tool_search');
|
|
133
|
+
const keepCount = allow.filter((name) => names.includes(name)).length;
|
|
134
|
+
const fallback = keepCount === 0;
|
|
135
|
+
const reason = fallback
|
|
136
|
+
? 'no visible tool survived the core filter'
|
|
137
|
+
: `task=${task}; keep=${keepCount}; trim=${trimmed.length}`;
|
|
138
|
+
return { task, allow, trimmed, toolNames: names, keepCount, trimmedCount: trimmed.length, fallback, reason };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Detect which host shape an assemble waterfall value has. */
|
|
142
|
+
export function assembleShape(assembly) {
|
|
143
|
+
if (Array.isArray(assembly?.tools)) return '0.2.1';
|
|
144
|
+
return '0.2.2';
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 0.2.1 compatibility: the host returns `assembly.tools` and trusts the
|
|
149
|
+
* waterfall's value. Keep only the frozen surface, then append tools the model
|
|
150
|
+
* requested through tool_search at the END so the cached prefix is untouched.
|
|
151
|
+
* 0.2.2 returns `assembly.tools === undefined`; there is nothing to filter here
|
|
152
|
+
* because the earlier `tools.restrict()` already filtered the provider.
|
|
153
|
+
*/
|
|
154
|
+
export function filterAssembly(assembly, { allow, requested = [], fullTools = [] } = {}) {
|
|
155
|
+
const shape = assembleShape(assembly);
|
|
156
|
+
if (shape === '0.2.2') return { assembly, shape, changed: false, appended: [] };
|
|
157
|
+
if (!(allow instanceof Set) || allow.size === 0) return { assembly, shape, changed: false, appended: [] };
|
|
158
|
+
const tools = assembly.tools;
|
|
159
|
+
const requestedSet = new Set(requested.filter((name) => !isCoreTool(name)));
|
|
160
|
+
const kept = [];
|
|
161
|
+
for (const tool of tools) {
|
|
162
|
+
if (typeof tool?.name !== 'string') continue;
|
|
163
|
+
if (requestedSet.has(tool.name)) continue;
|
|
164
|
+
if (isCoreTool(tool.name) || allow.has(tool.name)) kept.push(tool);
|
|
165
|
+
}
|
|
166
|
+
if (kept.length === 0) return { assembly, shape, changed: false, appended: [], fallback: true };
|
|
167
|
+
const seen = new Set(kept.map((tool) => tool.name));
|
|
168
|
+
const byName = new Map((Array.isArray(fullTools) ? fullTools : []).map((tool) => [tool.name, tool]));
|
|
169
|
+
const append = [];
|
|
170
|
+
for (const name of requested) {
|
|
171
|
+
if (seen.has(name) || isCoreTool(name)) continue;
|
|
172
|
+
const tool = byName.get(name);
|
|
173
|
+
if (tool === undefined) continue;
|
|
174
|
+
kept.push(tool);
|
|
175
|
+
append.push(name);
|
|
176
|
+
seen.add(name);
|
|
177
|
+
}
|
|
178
|
+
const changed = kept.length !== tools.length || append.length > 0;
|
|
179
|
+
const result = changed ? { ...assembly, tools: kept } : assembly;
|
|
180
|
+
return { assembly: result, shape, changed, appended: append };
|
|
181
|
+
}
|