counterparts 0.1.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/CONSTITUTION.md +68 -0
- package/LICENSE +21 -0
- package/README.md +348 -0
- package/docs/ELI5.md +84 -0
- package/docs/QUICKSTART.md +1258 -0
- package/docs/module-map.md +81 -0
- package/package.json +63 -0
- package/src/adapters/claude-code/CONTRACT.md +606 -0
- package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
- package/src/adapters/claude-code/NOTES.md +1055 -0
- package/src/adapters/claude-code/bin/hook.ts +820 -0
- package/src/adapters/claude-code/bin/runner.ts +522 -0
- package/src/adapters/claude-code/config.ts +778 -0
- package/src/adapters/claude-code/credentials.ts +199 -0
- package/src/adapters/claude-code/doctor.ts +2557 -0
- package/src/adapters/claude-code/embed-client.ts +617 -0
- package/src/adapters/claude-code/hooks.ts +2240 -0
- package/src/adapters/claude-code/index.ts +224 -0
- package/src/adapters/claude-code/interpret-client.ts +395 -0
- package/src/adapters/claude-code/page-writer.ts +462 -0
- package/src/adapters/claude-code/primacy.ts +162 -0
- package/src/adapters/claude-code/spawn.ts +241 -0
- package/src/adapters/claude-code/standdown.ts +536 -0
- package/src/adapters/claude-code/transcript.ts +661 -0
- package/src/adapters/claude-code/vectors.ts +415 -0
- package/src/adapters/cli/CONTRACT.md +255 -0
- package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
- package/src/adapters/cli/NOTES.md +936 -0
- package/src/adapters/cli/bin/counterparts.ts +74 -0
- package/src/adapters/cli/commands.ts +6095 -0
- package/src/adapters/cli/export.ts +766 -0
- package/src/adapters/cli/index.ts +103 -0
- package/src/adapters/cli/install.ts +670 -0
- package/src/adapters/cli/removal.ts +1186 -0
- package/src/adapters/cli/repair-dates.ts +659 -0
- package/src/adapters/cli/self-page.ts +229 -0
- package/src/adapters/cli/snapshot.ts +279 -0
- package/src/adapters/cli/start-fresh.ts +1228 -0
- package/src/adapters/config-path.ts +342 -0
- package/src/adapters/dashboard/CONTRACT.md +67 -0
- package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
- package/src/adapters/dashboard/NOTES.md +474 -0
- package/src/adapters/dashboard/activity.ts +121 -0
- package/src/adapters/dashboard/ansi.ts +82 -0
- package/src/adapters/dashboard/bin/dashboard.ts +479 -0
- package/src/adapters/dashboard/browse.ts +298 -0
- package/src/adapters/dashboard/identity.ts +182 -0
- package/src/adapters/dashboard/index.ts +183 -0
- package/src/adapters/dashboard/layout.ts +149 -0
- package/src/adapters/dashboard/registries.ts +291 -0
- package/src/adapters/dashboard/resolve.ts +206 -0
- package/src/adapters/dashboard/source.ts +48 -0
- package/src/adapters/dashboard/status.ts +327 -0
- package/src/adapters/dashboard/stories.ts +194 -0
- package/src/adapters/dashboard/web/app.html +1731 -0
- package/src/adapters/dashboard/web/brain.html +463 -0
- package/src/adapters/dashboard/web/fired.ts +31 -0
- package/src/adapters/dashboard/web/flow.ts +457 -0
- package/src/adapters/dashboard/web/narrate.ts +1042 -0
- package/src/adapters/dashboard/web/reveal.ts +135 -0
- package/src/adapters/dashboard/web/server.ts +287 -0
- package/src/adapters/dashboard/web/views.ts +1744 -0
- package/src/adapters/expansions.ts +569 -0
- package/src/adapters/fired.ts +1580 -0
- package/src/adapters/mcp/CONTRACT.md +240 -0
- package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
- package/src/adapters/mcp/NOTES.md +205 -0
- package/src/adapters/mcp/bin/serve.ts +349 -0
- package/src/adapters/mcp/deliberate.ts +619 -0
- package/src/adapters/mcp/index.ts +101 -0
- package/src/adapters/mcp/protocol.ts +170 -0
- package/src/adapters/mcp/server.ts +1740 -0
- package/src/adapters/mcp/stdio.ts +56 -0
- package/src/adapters/mcp/tools.ts +779 -0
- package/src/adapters/scopes.ts +657 -0
- package/src/adapters/sessions.ts +402 -0
- package/src/adapters/snapshots.ts +1069 -0
- package/src/adapters/stance-env.ts +137 -0
- package/src/core/associate/CONTRACT.md +118 -0
- package/src/core/associate/INTERFACE-GAPS.md +173 -0
- package/src/core/associate/NOTES.md +194 -0
- package/src/core/associate/buffer.ts +66 -0
- package/src/core/associate/edges.ts +188 -0
- package/src/core/associate/index.ts +570 -0
- package/src/core/associate/pending.ts +383 -0
- package/src/core/associate/spread.ts +149 -0
- package/src/core/associate/tunables.ts +123 -0
- package/src/core/bridge.ts +272 -0
- package/src/core/briefing.ts +67 -0
- package/src/core/counterpart.ts +3855 -0
- package/src/core/encode/CONTRACT.md +151 -0
- package/src/core/encode/INTERFACE-GAPS.md +135 -0
- package/src/core/encode/NOTES.md +146 -0
- package/src/core/encode/aliases.ts +71 -0
- package/src/core/encode/battery.ts +284 -0
- package/src/core/encode/chunk.ts +265 -0
- package/src/core/encode/emotion.ts +119 -0
- package/src/core/encode/floor.ts +76 -0
- package/src/core/encode/index.ts +100 -0
- package/src/core/encode/precision.ts +162 -0
- package/src/core/encode/preselect.ts +269 -0
- package/src/core/encode/salience.ts +108 -0
- package/src/core/encode/secrets.ts +265 -0
- package/src/core/encode/tunables.ts +99 -0
- package/src/core/encode/types.ts +286 -0
- package/src/core/encode/words.ts +75 -0
- package/src/core/handoff/CONTRACT.md +199 -0
- package/src/core/handoff/INTERFACE-GAPS.md +166 -0
- package/src/core/handoff/NOTES.md +206 -0
- package/src/core/handoff/index.ts +957 -0
- package/src/core/mint.ts +279 -0
- package/src/core/observer.ts +28 -0
- package/src/core/physics/CONTRACT.md +341 -0
- package/src/core/physics/NOTES.md +155 -0
- package/src/core/physics/clock.ts +51 -0
- package/src/core/physics/index.ts +1054 -0
- package/src/core/prospective/CONTRACT.md +137 -0
- package/src/core/prospective/INTERFACE-GAPS.md +112 -0
- package/src/core/prospective/NOTES.md +160 -0
- package/src/core/prospective/derive.ts +188 -0
- package/src/core/prospective/index.ts +1030 -0
- package/src/core/prospective/tunables.ts +72 -0
- package/src/core/prospective/windows.ts +187 -0
- package/src/core/recall/CONTRACT.md +326 -0
- package/src/core/recall/INTERFACE-GAPS.md +163 -0
- package/src/core/recall/NOTES.md +472 -0
- package/src/core/recall/activate.ts +521 -0
- package/src/core/recall/cues.ts +275 -0
- package/src/core/recall/gate.ts +441 -0
- package/src/core/recall/index.ts +692 -0
- package/src/core/recall/probe.ts +239 -0
- package/src/core/recall/reference.ts +201 -0
- package/src/core/recall/render.ts +285 -0
- package/src/core/recall/session.ts +403 -0
- package/src/core/recall/tunables.ts +329 -0
- package/src/core/remember/CONTRACT.md +293 -0
- package/src/core/remember/INTERFACE-GAPS.md +189 -0
- package/src/core/remember/NOTES.md +373 -0
- package/src/core/remember/fallback.ts +452 -0
- package/src/core/remember/index.ts +103 -0
- package/src/core/remember/owner-strike-seam.ts +479 -0
- package/src/core/remember/proposals.ts +609 -0
- package/src/core/remember/spans.ts +1310 -0
- package/src/core/remember/tunables.ts +111 -0
- package/src/core/remember/updates.ts +198 -0
- package/src/core/retrieval.ts +96 -0
- package/src/core/revision.ts +441 -0
- package/src/core/schemas/CONTRACT.md +190 -0
- package/src/core/schemas/INTERFACE-GAPS.md +172 -0
- package/src/core/schemas/NOTES.md +260 -0
- package/src/core/schemas/aliases.ts +160 -0
- package/src/core/schemas/index.ts +1459 -0
- package/src/core/schemas/tunables.ts +44 -0
- package/src/core/schemas/types.ts +387 -0
- package/src/core/self/CONTRACT.md +459 -0
- package/src/core/self/INTERFACE-GAPS.md +284 -0
- package/src/core/self/NOTES.md +1057 -0
- package/src/core/self/briefing.ts +980 -0
- package/src/core/self/episodes.ts +483 -0
- package/src/core/self/freeze.ts +103 -0
- package/src/core/self/identity.ts +604 -0
- package/src/core/self/index.ts +2130 -0
- package/src/core/self/journal-file.ts +760 -0
- package/src/core/self/page.ts +404 -0
- package/src/core/self/tunables.ts +244 -0
- package/src/core/self/writer.ts +714 -0
- package/src/core/sleep/CONTRACT.md +298 -0
- package/src/core/sleep/INTERFACE-GAPS.md +262 -0
- package/src/core/sleep/NOTES.md +770 -0
- package/src/core/sleep/briefing.ts +86 -0
- package/src/core/sleep/consolidate.ts +241 -0
- package/src/core/sleep/cycle.ts +598 -0
- package/src/core/sleep/decay.ts +237 -0
- package/src/core/sleep/dedup.ts +373 -0
- package/src/core/sleep/index.ts +112 -0
- package/src/core/sleep/log.ts +116 -0
- package/src/core/sleep/markers.ts +164 -0
- package/src/core/sleep/prune.ts +170 -0
- package/src/core/sleep/strength-cache.ts +176 -0
- package/src/core/sleep/tunables.ts +135 -0
- package/src/core/sleep/types.ts +542 -0
- package/src/core/store/CONTRACT.md +446 -0
- package/src/core/store/NOTES.md +1068 -0
- package/src/core/store/cache.ts +709 -0
- package/src/core/store/db.ts +275 -0
- package/src/core/store/errors.ts +134 -0
- package/src/core/store/index.ts +2450 -0
- package/src/core/store/operational.ts +610 -0
- package/src/core/store/owner-op-seam.ts +428 -0
- package/src/core/store/paths.ts +494 -0
- package/src/core/store/prose.ts +165 -0
- package/src/core/store/render.ts +87 -0
- package/src/core/store/walk-seam.ts +78 -0
- package/src/core/types.ts +68 -0
- package/tools/install-loop/run.sh +1063 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `adapters/claude-code/` — the launch adapter's public surface.
|
|
3
|
+
*
|
|
4
|
+
* The dependency direction is one-way and asserted by a test: the core imports
|
|
5
|
+
* NOTHING from this directory (CONTRACT §5 G1, constitution line 5). Everything
|
|
6
|
+
* this file exports is host-shaped; everything it imports from `../../core/` is
|
|
7
|
+
* host-agnostic.
|
|
8
|
+
*/
|
|
9
|
+
export {
|
|
10
|
+
ANTHROPIC_ENDPOINT,
|
|
11
|
+
ANTHROPIC_VERSION,
|
|
12
|
+
API_KEY_ENV,
|
|
13
|
+
CAPABILITIES,
|
|
14
|
+
DEFAULT_EMBED_MODEL,
|
|
15
|
+
DEFAULT_INTERPRET_MODEL,
|
|
16
|
+
EMBED_KEY_ENV,
|
|
17
|
+
TUNABLES,
|
|
18
|
+
VOYAGE_ENDPOINT,
|
|
19
|
+
capabilities,
|
|
20
|
+
embedSeat,
|
|
21
|
+
embedderState,
|
|
22
|
+
interpretSeat,
|
|
23
|
+
PAGE_WRITER_FALLBACK_MODE,
|
|
24
|
+
loadConfig,
|
|
25
|
+
pageWriterMode,
|
|
26
|
+
seatStatus,
|
|
27
|
+
} from "./config.js";
|
|
28
|
+
export type {
|
|
29
|
+
AdapterConfig,
|
|
30
|
+
CapabilityName,
|
|
31
|
+
CapabilityReport,
|
|
32
|
+
LoadedConfig,
|
|
33
|
+
ModelSeat,
|
|
34
|
+
SeatStatus,
|
|
35
|
+
SeatVerdict,
|
|
36
|
+
} from "./config.js";
|
|
37
|
+
|
|
38
|
+
export {
|
|
39
|
+
CREDENTIAL_FILE_EVENT,
|
|
40
|
+
CREDENTIAL_NAMES,
|
|
41
|
+
credentialRow,
|
|
42
|
+
loadCredentials,
|
|
43
|
+
permissionWarning,
|
|
44
|
+
} from "./credentials.js";
|
|
45
|
+
export type { CredentialLoad } from "./credentials.js";
|
|
46
|
+
|
|
47
|
+
export {
|
|
48
|
+
AUTHORSHIP_DAYS,
|
|
49
|
+
CHECKOUT_BUDGET_MS,
|
|
50
|
+
CHECKOUT_TIMEOUT_MS,
|
|
51
|
+
NOTICE_MAX_CHARS,
|
|
52
|
+
NOTICE_TAIL,
|
|
53
|
+
SESSION_NOTICE_BUDGET_MS,
|
|
54
|
+
SEVERITIES,
|
|
55
|
+
anyRed,
|
|
56
|
+
checkoutIsGraded,
|
|
57
|
+
doctorFindings,
|
|
58
|
+
noticeMessage,
|
|
59
|
+
pageWriterFindings,
|
|
60
|
+
readCheckout,
|
|
61
|
+
RESTORE_STEPS,
|
|
62
|
+
readCounterpartOpen,
|
|
63
|
+
reportJson,
|
|
64
|
+
reportLines,
|
|
65
|
+
worstFirst,
|
|
66
|
+
} from "./doctor.js";
|
|
67
|
+
export type {
|
|
68
|
+
CheckoutReading,
|
|
69
|
+
DoctorInput,
|
|
70
|
+
Finding,
|
|
71
|
+
GitRunner,
|
|
72
|
+
OpenReading,
|
|
73
|
+
Severity,
|
|
74
|
+
} from "./doctor.js";
|
|
75
|
+
|
|
76
|
+
export {
|
|
77
|
+
stopAsk,
|
|
78
|
+
BOUNDARY_KIND,
|
|
79
|
+
ClaudeCodeAdapter,
|
|
80
|
+
HOOKS,
|
|
81
|
+
ASK_SEPARATOR_BYTES,
|
|
82
|
+
PAGE_WRITER_TOOL,
|
|
83
|
+
SCOPE_ASK,
|
|
84
|
+
SCOPE_ASK_BYTES,
|
|
85
|
+
SCOPE_PATIENCE_DEFERRALS,
|
|
86
|
+
SESSION_ENDING,
|
|
87
|
+
SPAWN_REFUSAL_PREFIX,
|
|
88
|
+
SPAWN_START_COUNT_KEY,
|
|
89
|
+
SPAWN_START_DATE_KEY,
|
|
90
|
+
substanceOf,
|
|
91
|
+
wakeOutcome,
|
|
92
|
+
} from "./hooks.js";
|
|
93
|
+
export type {
|
|
94
|
+
AdapterEvent,
|
|
95
|
+
AdapterOptions,
|
|
96
|
+
HookInput,
|
|
97
|
+
HookName,
|
|
98
|
+
HookResult,
|
|
99
|
+
HostTurn,
|
|
100
|
+
SessionEndingHook,
|
|
101
|
+
WakeOutcome,
|
|
102
|
+
} from "./hooks.js";
|
|
103
|
+
|
|
104
|
+
export { InterpretError, SYSTEM_PROMPT, extractJson, interpretClient, readStream } from "./interpret-client.js";
|
|
105
|
+
export type { FetchLike, InterpretClientOptions, InterpretRefusal, StreamRead } from "./interpret-client.js";
|
|
106
|
+
|
|
107
|
+
export {
|
|
108
|
+
EmbedError,
|
|
109
|
+
callBudget,
|
|
110
|
+
createEmbedder,
|
|
111
|
+
embedClient,
|
|
112
|
+
openEmbedder,
|
|
113
|
+
wellFormed,
|
|
114
|
+
} from "./embed-client.js";
|
|
115
|
+
export type {
|
|
116
|
+
ChunkFailure,
|
|
117
|
+
EmbedBatch,
|
|
118
|
+
EmbedClientOptions,
|
|
119
|
+
EmbedFn,
|
|
120
|
+
EmbedRefusal,
|
|
121
|
+
EmbedderStats,
|
|
122
|
+
LiveEmbedder,
|
|
123
|
+
LiveEmbedderOptions,
|
|
124
|
+
} from "./embed-client.js";
|
|
125
|
+
|
|
126
|
+
export {
|
|
127
|
+
DEFAULT_HOST_COMMAND,
|
|
128
|
+
KILL_GRACE_MS,
|
|
129
|
+
MCP_SELF_PAGE_TOOL,
|
|
130
|
+
PAGE_WRITER_ENV,
|
|
131
|
+
PERMISSION_MODE,
|
|
132
|
+
REAP_GRACE_MS,
|
|
133
|
+
planPageWriter,
|
|
134
|
+
runPageWriter,
|
|
135
|
+
} from "./page-writer.js";
|
|
136
|
+
export type {
|
|
137
|
+
ChildResult,
|
|
138
|
+
PageWriterPlan,
|
|
139
|
+
PageWriterPlanInput,
|
|
140
|
+
PageWriterRefusal,
|
|
141
|
+
PageWriterRunResult,
|
|
142
|
+
PageWriterStarter,
|
|
143
|
+
} from "./page-writer.js";
|
|
144
|
+
|
|
145
|
+
export { DATA_DIR_ENV, SCOPE_ENV, SESSION_ENV, WATCHDOG_ENV, planSpawn, spawnDetached } from "./spawn.js";
|
|
146
|
+
export type { PlanInput, SpawnOutcome, SpawnPlan, SpawnRefusal, Spawner } from "./spawn.js";
|
|
147
|
+
|
|
148
|
+
export {
|
|
149
|
+
BACKFILL_LIMIT,
|
|
150
|
+
LAG_PROMPT_BYTES,
|
|
151
|
+
LAG_REPLY_BYTES,
|
|
152
|
+
backfillVectors,
|
|
153
|
+
lagText,
|
|
154
|
+
laggedSemantic,
|
|
155
|
+
} from "./vectors.js";
|
|
156
|
+
export type { BackfillReport, LagReport } from "./vectors.js";
|
|
157
|
+
|
|
158
|
+
export {
|
|
159
|
+
COUNTERPARTS_HOOK_COMMAND,
|
|
160
|
+
FOREIGN_MARKERS,
|
|
161
|
+
NO_ARRIVAL,
|
|
162
|
+
WAKE_HEAD_MAX_BYTES,
|
|
163
|
+
WAKE_HEAD_MAX_LINES,
|
|
164
|
+
attributePeers,
|
|
165
|
+
classifyBlock,
|
|
166
|
+
parseTranscript,
|
|
167
|
+
readTranscript,
|
|
168
|
+
readWakeArrival,
|
|
169
|
+
} from "./transcript.js";
|
|
170
|
+
export type {
|
|
171
|
+
PeerAttribution,
|
|
172
|
+
SentinelSighting,
|
|
173
|
+
TranscriptRead,
|
|
174
|
+
WakeArrival,
|
|
175
|
+
} from "./transcript.js";
|
|
176
|
+
|
|
177
|
+
export { AB_DIR_ENV, V2_OVERRIDE, abDir, assignmentHealth, assignmentPath, primacy, readAssignment } from "./primacy.js";
|
|
178
|
+
export type { Assignment, AssignmentHealth, AssignmentState, Primacy, PrimacyReason } from "./primacy.js";
|
|
179
|
+
|
|
180
|
+
import { Counterpart } from "../../core/counterpart.js";
|
|
181
|
+
import type { AdapterConfig } from "./config.js";
|
|
182
|
+
import { openEmbedder } from "./embed-client.js";
|
|
183
|
+
import type { LiveEmbedder, LiveEmbedderOptions } from "./embed-client.js";
|
|
184
|
+
import { ClaudeCodeAdapter } from "./hooks.js";
|
|
185
|
+
import type { AdapterOptions } from "./hooks.js";
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Open a brain for this host and wrap it in the hooks.
|
|
189
|
+
*
|
|
190
|
+
* The two host facts travel as ARGUMENTS, which is the whole charter: the
|
|
191
|
+
* injection ceiling the host reported becomes the core's `budgetBytes`, and the
|
|
192
|
+
* data directory is the one the configuration names — never one inherited from
|
|
193
|
+
* an ambient environment variable a caller happened to export (scar §2.13).
|
|
194
|
+
*/
|
|
195
|
+
export function openAdapter(
|
|
196
|
+
config: AdapterConfig,
|
|
197
|
+
opts: Omit<AdapterOptions, "counterpart" | "config"> & {
|
|
198
|
+
/** Injected so the whole path is provable without a socket. */
|
|
199
|
+
embedFetch?: LiveEmbedderOptions["fetch"];
|
|
200
|
+
/** Injected so a test can supply vectors without a client at all. */
|
|
201
|
+
embedder?: LiveEmbedder | null;
|
|
202
|
+
} = {},
|
|
203
|
+
): ClaudeCodeAdapter {
|
|
204
|
+
const { embedFetch, embedder: injected, ...adapterOpts } = opts;
|
|
205
|
+
const embedder =
|
|
206
|
+
injected !== undefined
|
|
207
|
+
? injected
|
|
208
|
+
: openEmbedder(config, embedFetch === undefined ? {} : { fetch: embedFetch });
|
|
209
|
+
const counterpart = Counterpart.open({
|
|
210
|
+
// Both halves of the same embedder: the SYNC face the store's index holds,
|
|
211
|
+
// and the LIVE face the novelty seam and the sweep's warm call use.
|
|
212
|
+
...(embedder === null ? {} : { embed: embedder.embed, vectors: embedder }),
|
|
213
|
+
...(config.dataDir === undefined ? {} : { dir: config.dataDir }),
|
|
214
|
+
...(config.injectionBudgetBytes === undefined
|
|
215
|
+
? {}
|
|
216
|
+
: { budgetBytes: config.injectionBudgetBytes }),
|
|
217
|
+
...(config.observer === undefined ? {} : { observer: config.observer }),
|
|
218
|
+
...(config.owner === undefined ? {} : { owner: config.owner }),
|
|
219
|
+
...(config.identity === undefined
|
|
220
|
+
? {}
|
|
221
|
+
: { identity: { name: config.identity.name, aliases: [...(config.identity.aliases ?? [])] } }),
|
|
222
|
+
});
|
|
223
|
+
return new ClaudeCodeAdapter({ counterpart, config, ...adapterOpts });
|
|
224
|
+
}
|
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The crash fallback's model call — the ONE place in this package that reaches
|
|
3
|
+
* a model API, and the only network code that exists at all.
|
|
4
|
+
*
|
|
5
|
+
* `remember/` owns the choreography (chunking, claim/consume, restore-on-throw)
|
|
6
|
+
* and deliberately holds no client; `INTERFACE-GAPS §3` says streaming, token
|
|
7
|
+
* headroom, retries and detachment belong to whoever injects the function. This
|
|
8
|
+
* is that injection, for this host.
|
|
9
|
+
*
|
|
10
|
+
* Five scars are load-bearing here, and each is a line you can point at:
|
|
11
|
+
*
|
|
12
|
+
* **E2** — a truncated JSON response is a FAILURE, not data. The stop reason
|
|
13
|
+
* is captured off the `message_delta` event and returned on the result;
|
|
14
|
+
* `remember/fallback.ts` checks it against `OK_STOP_REASONS` and records the
|
|
15
|
+
* chunk `TRUNCATED`, so its spans go back for the next boundary rather than a
|
|
16
|
+
* half-parsed harvest becoming memory.
|
|
17
|
+
*
|
|
18
|
+
* **E3** — the call STREAMS. A non-streaming long generation dies as a fake
|
|
19
|
+
* connection timeout, and the socket ceiling that decides "long" is a host
|
|
20
|
+
* fact this adapter reports rather than the core assuming (scar §2.18).
|
|
21
|
+
*
|
|
22
|
+
* **§2.14** — the response is never sliced between the first brace and the
|
|
23
|
+
* last. `extractJson` walks the text with a real string/escape-aware scanner,
|
|
24
|
+
* and the VALIDATOR is `remember/`'s own `intake()`, downstream: structured
|
|
25
|
+
* output pins shape, the validator pins meaning, and this file does neither by
|
|
26
|
+
* regex.
|
|
27
|
+
*
|
|
28
|
+
* **§2.18** — the credential comes from ONE configured source the package
|
|
29
|
+
* names: `ANTHROPIC_API_KEY` in the environment, or — where the host gives a
|
|
30
|
+
* process no environment to inherit, which is what this host does to its hooks
|
|
31
|
+
* — the file `credentialsFile` names, loaded into that same variable at the
|
|
32
|
+
* process entry point. Never a rotation list, never a per-key cursor, and
|
|
33
|
+
* never a file found by convention. Missing means a NAMED refusal before any
|
|
34
|
+
* socket is opened, not a mysterious failure at the far end.
|
|
35
|
+
*
|
|
36
|
+
* **§2.15** — the model id comes from the adapter's own seat knob with a
|
|
37
|
+
* pinned default, and a placeholder that has expired refuses the call.
|
|
38
|
+
*
|
|
39
|
+
* There is no SDK and no dependency: `fetch` is the runtime's.
|
|
40
|
+
*/
|
|
41
|
+
import type { InterpretFn, InterpretResult, SweepChunk } from "../../core/remember/index.js";
|
|
42
|
+
|
|
43
|
+
import {
|
|
44
|
+
ANTHROPIC_ENDPOINT,
|
|
45
|
+
ANTHROPIC_VERSION,
|
|
46
|
+
API_KEY_ENV,
|
|
47
|
+
TUNABLES,
|
|
48
|
+
interpretSeat,
|
|
49
|
+
} from "./config.js";
|
|
50
|
+
import type { AdapterConfig } from "./config.js";
|
|
51
|
+
|
|
52
|
+
/** Every way this client refuses, by name. A refusal is never a silent empty. */
|
|
53
|
+
export type InterpretRefusal =
|
|
54
|
+
| "NO_API_KEY"
|
|
55
|
+
| "SEAT_UNUSABLE"
|
|
56
|
+
| "HTTP_ERROR"
|
|
57
|
+
| "NO_BODY"
|
|
58
|
+
| "NO_JSON_IN_RESPONSE";
|
|
59
|
+
|
|
60
|
+
export class InterpretError extends Error {
|
|
61
|
+
/** `remember/`'s `errCode()` lifts this into the chunk's telemetry. */
|
|
62
|
+
readonly code: InterpretRefusal;
|
|
63
|
+
readonly detail: Record<string, string | number>;
|
|
64
|
+
|
|
65
|
+
constructor(code: InterpretRefusal, detail: Record<string, string | number> = {}) {
|
|
66
|
+
super(`${code}${Object.keys(detail).length > 0 ? ` ${JSON.stringify(detail)}` : ""}`);
|
|
67
|
+
this.name = "InterpretError";
|
|
68
|
+
this.code = code;
|
|
69
|
+
this.detail = detail;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Injected so a test can prove the whole path without a socket. */
|
|
74
|
+
export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
75
|
+
|
|
76
|
+
export interface InterpretClientOptions {
|
|
77
|
+
config?: AdapterConfig;
|
|
78
|
+
/** Defaults to `globalThis.fetch`. A test supplies its own; nothing else does. */
|
|
79
|
+
fetch?: FetchLike;
|
|
80
|
+
/** Today, ISO — the date a placeholder seat's expiry is judged against. */
|
|
81
|
+
today?: string;
|
|
82
|
+
/** Output headroom. Too little is how E2's incident happens. */
|
|
83
|
+
maxTokens?: number;
|
|
84
|
+
/** Telemetry: ids, counts, reasons. Never span text, never response text. */
|
|
85
|
+
onEvent?: (name: string, data: Record<string, string | number | boolean | null>) => void;
|
|
86
|
+
/** Aborts the request. The watchdog's hand on the socket. */
|
|
87
|
+
signal?: AbortSignal;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The prompt. It says what a proposal IS in `remember/`'s own vocabulary, and it
|
|
92
|
+
* asks for nothing the intake validator will not accept — but nothing here
|
|
93
|
+
* TRUSTS that: every field is re-validated downstream, and no privileged field
|
|
94
|
+
* exists to ask for, because `Proposal` has nowhere to put one (§4.1 G7).
|
|
95
|
+
*
|
|
96
|
+
* Three lessons of the 2026-08-26 replay review are load-bearing here:
|
|
97
|
+
* - the OWNER IS NAMED when the config knows them. The first real run minted
|
|
98
|
+
* 15 durable person-memories under a confabulated name ("Matt", appearing
|
|
99
|
+
* nowhere in the source) because nothing anchored who the transcripts
|
|
100
|
+
* belong to.
|
|
101
|
+
* - the KINDS ARE DEFINED. Named without definitions, `entity` came back
|
|
102
|
+
* ~60% events-filed-as-things and `place` 8-for-8 non-geographic — a spec
|
|
103
|
+
* absence, not a model failure.
|
|
104
|
+
* - ONE IDEA HAS TEETH, and a fragment gets `[]` instead of an essay (5 of
|
|
105
|
+
* 121 real calls answered tiny scraps with prose; throw-and-restore held,
|
|
106
|
+
* but the honest answer was always `[]`).
|
|
107
|
+
*
|
|
108
|
+
* **WHERE THE FIRST-PERSON INSTRUCTION LIVES, and why it is not here.** Since
|
|
109
|
+
* 2026-09-17 the fallback is WOKEN AS THE SELF: the chunk prompt carries the
|
|
110
|
+
* composed wake ahead of the transcript, fenced, and tells the reader to write
|
|
111
|
+
* what it learned in the first person and in its own voice. That instruction
|
|
112
|
+
* sits beside the wake, in `core/counterpart.ts#wrapSweepInterpret`, because
|
|
113
|
+
* this system prompt is built ONCE at construction and cannot know whether a
|
|
114
|
+
* given sweep has a self to point at — an instruction to speak as yourself,
|
|
115
|
+
* issued with no self attached, is worse than none. Everything here is about
|
|
116
|
+
* the PROPOSAL, and is unchanged.
|
|
117
|
+
*/
|
|
118
|
+
export function systemPrompt(identity?: {
|
|
119
|
+
readonly name: string;
|
|
120
|
+
readonly aliases?: readonly string[];
|
|
121
|
+
}): string {
|
|
122
|
+
const aka =
|
|
123
|
+
identity?.aliases !== undefined && identity.aliases.length > 0
|
|
124
|
+
? ` (also appearing as: ${identity.aliases.join(", ")})`
|
|
125
|
+
: "";
|
|
126
|
+
const owner =
|
|
127
|
+
identity === undefined
|
|
128
|
+
? [
|
|
129
|
+
"If the person the transcripts belong to is not named in them, write",
|
|
130
|
+
"'the owner' — NEVER guess or introduce a name the transcript does not",
|
|
131
|
+
"contain verbatim.",
|
|
132
|
+
]
|
|
133
|
+
: [
|
|
134
|
+
`The person these transcripts belong to is ${identity.name}${aka}.`,
|
|
135
|
+
`Refer to them as ${identity.name}. Never introduce any other name for`,
|
|
136
|
+
"them; a name not in the transcript verbatim does not exist.",
|
|
137
|
+
"This anchor is context, not material: never propose a memory whose",
|
|
138
|
+
"content restates it — memories come from the transcript alone.",
|
|
139
|
+
];
|
|
140
|
+
return [
|
|
141
|
+
"You are reading a transcript that its own author never got to summarize — the",
|
|
142
|
+
"session ended before the end-of-session write. Recover what was LEARNED, not",
|
|
143
|
+
"what was said.",
|
|
144
|
+
"",
|
|
145
|
+
...owner,
|
|
146
|
+
"",
|
|
147
|
+
"Return ONLY a JSON array. Each element is an object:",
|
|
148
|
+
" content (required, string) — the memory, in plain prose. ONE idea per",
|
|
149
|
+
" element: if a passage taught three things, return three elements.",
|
|
150
|
+
" Never bundle a day's status updates into one memory.",
|
|
151
|
+
" kind (optional) — exactly one of:",
|
|
152
|
+
" self — a lesson, trait, or practice of the AI assistant itself",
|
|
153
|
+
" person — a durable fact about a human (who they are, how they",
|
|
154
|
+
" work) — not an event they happened to be part of",
|
|
155
|
+
" entity — a durable named thing: a project, company, product,",
|
|
156
|
+
" system — not an event, status, or one-time change",
|
|
157
|
+
" skill — a reusable technique or how-to",
|
|
158
|
+
" place — a physical location",
|
|
159
|
+
" fact — everything else durable: events, decisions, states",
|
|
160
|
+
' title (optional, string) — a short handle.',
|
|
161
|
+
' claimed (optional, number 0-1) — how much this mattered.',
|
|
162
|
+
' salience (optional) — { relevance, emotional, predictive }, each 0-1.',
|
|
163
|
+
' feeling (optional) — { feeling, quote, subject }; quote must appear in the span.',
|
|
164
|
+
' aliases (optional, string[]) — other names for the thing.',
|
|
165
|
+
' updates (optional, string) — the id of a memory this revises, if one is named.',
|
|
166
|
+
"",
|
|
167
|
+
"Return [] when the transcript taught nothing. An empty array is a real answer,",
|
|
168
|
+
"and it is THE answer for a fragment too small to teach anything — never",
|
|
169
|
+
"commentary about the fragment.",
|
|
170
|
+
"Do not include commentary, markdown fences, or any text outside the array.",
|
|
171
|
+
].join("\n");
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The identity-less render, kept for callers and tests that predate the owner
|
|
175
|
+
* anchor. A configured host lets `interpretClient` build the anchored prompt. */
|
|
176
|
+
export const SYSTEM_PROMPT = systemPrompt();
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Build the `InterpretFn` `remember/`'s sweep takes. One chunk in, proposals and
|
|
180
|
+
* a stop reason out; every failure THROWS with a named code, because a throw is
|
|
181
|
+
* what makes `remember/` restore the chunk's spans (scar E6) instead of
|
|
182
|
+
* consuming them against nothing.
|
|
183
|
+
*/
|
|
184
|
+
export function interpretClient(opts: InterpretClientOptions = {}): InterpretFn {
|
|
185
|
+
const config = opts.config ?? {};
|
|
186
|
+
const doFetch = opts.fetch ?? ((globalThis as { fetch?: FetchLike }).fetch as FetchLike | undefined);
|
|
187
|
+
const maxTokens = opts.maxTokens ?? TUNABLES.MAX_OUTPUT_TOKENS;
|
|
188
|
+
const today = opts.today ?? new Date().toISOString().slice(0, 10);
|
|
189
|
+
const emit = opts.onEvent ?? ((): void => {});
|
|
190
|
+
// Anchored once, at construction: the owner's identity comes from the host's
|
|
191
|
+
// config, the same source the identity core uses — never inferred from text.
|
|
192
|
+
const system = systemPrompt(config.identity);
|
|
193
|
+
|
|
194
|
+
return async (chunk: SweepChunk): Promise<InterpretResult> => {
|
|
195
|
+
// ── the credential, from ONE source, checked BEFORE any socket ──────────
|
|
196
|
+
const key = process.env[API_KEY_ENV];
|
|
197
|
+
if (key === undefined || key.trim().length === 0) {
|
|
198
|
+
emit("interpret.refused", { chunk: chunk.index, code: "NO_API_KEY" });
|
|
199
|
+
throw new InterpretError("NO_API_KEY", { env: API_KEY_ENV });
|
|
200
|
+
}
|
|
201
|
+
// ── the seat, whose placeholder expires (scar §2.15) ────────────────────
|
|
202
|
+
const seat = interpretSeat(config, today);
|
|
203
|
+
if (!seat.usable) {
|
|
204
|
+
emit("interpret.refused", { chunk: chunk.index, code: "SEAT_UNUSABLE", status: seat.status });
|
|
205
|
+
throw new InterpretError("SEAT_UNUSABLE", { seat: seat.seat, status: seat.status });
|
|
206
|
+
}
|
|
207
|
+
if (doFetch === undefined) {
|
|
208
|
+
emit("interpret.refused", { chunk: chunk.index, code: "HTTP_ERROR", reason: "no-fetch" });
|
|
209
|
+
throw new InterpretError("HTTP_ERROR", { reason: "no-fetch" });
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const body = {
|
|
213
|
+
model: seat.id,
|
|
214
|
+
max_tokens: maxTokens,
|
|
215
|
+
// E3: long generations STREAM. This one can be long by construction — a
|
|
216
|
+
// chunk is thousands of bytes of transcript.
|
|
217
|
+
stream: true,
|
|
218
|
+
system,
|
|
219
|
+
messages: [{ role: "user", content: chunk.prompt }],
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
emit("interpret.call", {
|
|
223
|
+
chunk: chunk.index,
|
|
224
|
+
bytes: chunk.bytes,
|
|
225
|
+
spans: chunk.spans.length,
|
|
226
|
+
model: seat.id,
|
|
227
|
+
seat: seat.status,
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const response = await doFetch(ANTHROPIC_ENDPOINT, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: {
|
|
233
|
+
"content-type": "application/json",
|
|
234
|
+
"x-api-key": key,
|
|
235
|
+
"anthropic-version": ANTHROPIC_VERSION,
|
|
236
|
+
},
|
|
237
|
+
body: JSON.stringify(body),
|
|
238
|
+
...(opts.signal === undefined ? {} : { signal: opts.signal }),
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
if (!response.ok) {
|
|
242
|
+
emit("interpret.refused", { chunk: chunk.index, code: "HTTP_ERROR", status: response.status });
|
|
243
|
+
throw new InterpretError("HTTP_ERROR", { status: response.status });
|
|
244
|
+
}
|
|
245
|
+
if (response.body === null) {
|
|
246
|
+
emit("interpret.refused", { chunk: chunk.index, code: "NO_BODY" });
|
|
247
|
+
throw new InterpretError("NO_BODY", {});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const read = await readStream(response.body);
|
|
251
|
+
emit("interpret.done", {
|
|
252
|
+
chunk: chunk.index,
|
|
253
|
+
stopReason: read.stopReason,
|
|
254
|
+
chars: read.text.length,
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// E2, HALF ONE: the stop reason travels back UNJUDGED. `remember/` owns the
|
|
258
|
+
// OK list and the TRUNCATED verdict; two opinions on what counts as a clean
|
|
259
|
+
// completion is how they drift apart.
|
|
260
|
+
if (read.stopReason !== null && read.stopReason !== "end_turn") {
|
|
261
|
+
return { proposals: [], stopReason: read.stopReason };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const parsed = extractJson(read.text);
|
|
265
|
+
if (parsed === null) {
|
|
266
|
+
// Distinguishable from "returned nothing": the model said something and
|
|
267
|
+
// it was not an array (scar §2.4).
|
|
268
|
+
emit("interpret.refused", { chunk: chunk.index, code: "NO_JSON_IN_RESPONSE" });
|
|
269
|
+
throw new InterpretError("NO_JSON_IN_RESPONSE", { chars: read.text.length });
|
|
270
|
+
}
|
|
271
|
+
return {
|
|
272
|
+
proposals: parsed,
|
|
273
|
+
...(read.stopReason === null ? {} : { stopReason: read.stopReason }),
|
|
274
|
+
};
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export interface StreamRead {
|
|
279
|
+
readonly text: string;
|
|
280
|
+
/** From `message_delta`. Null when the stream ended without stating one. */
|
|
281
|
+
readonly stopReason: string | null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Consume the SSE stream, keeping exactly two things: the concatenated text and
|
|
286
|
+
* the stop reason. Everything else — usage, ids, block indices — is the API's
|
|
287
|
+
* bookkeeping, and none of it is content this package needs.
|
|
288
|
+
*
|
|
289
|
+
* A malformed `data:` line is SKIPPED, not fatal: a stream that carried real
|
|
290
|
+
* deltas and one bad frame still produced text, and dropping the whole harvest
|
|
291
|
+
* for a frame we could not parse would be the opposite of E6.
|
|
292
|
+
*/
|
|
293
|
+
export async function readStream(stream: ReadableStream<Uint8Array>): Promise<StreamRead> {
|
|
294
|
+
const reader = stream.getReader();
|
|
295
|
+
const decoder = new TextDecoder();
|
|
296
|
+
let buffer = "";
|
|
297
|
+
let text = "";
|
|
298
|
+
let stopReason: string | null = null;
|
|
299
|
+
|
|
300
|
+
const handle = (line: string): void => {
|
|
301
|
+
if (!line.startsWith("data:")) return;
|
|
302
|
+
const payload = line.slice("data:".length).trim();
|
|
303
|
+
if (payload.length === 0 || payload === "[DONE]") return;
|
|
304
|
+
let event: Record<string, unknown>;
|
|
305
|
+
try {
|
|
306
|
+
event = JSON.parse(payload) as Record<string, unknown>;
|
|
307
|
+
} catch {
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const type = event["type"];
|
|
311
|
+
if (type === "content_block_delta") {
|
|
312
|
+
const delta = event["delta"] as Record<string, unknown> | undefined;
|
|
313
|
+
if (delta !== undefined && typeof delta["text"] === "string") text += delta["text"];
|
|
314
|
+
} else if (type === "message_delta") {
|
|
315
|
+
const delta = event["delta"] as Record<string, unknown> | undefined;
|
|
316
|
+
if (delta !== undefined && typeof delta["stop_reason"] === "string") {
|
|
317
|
+
stopReason = delta["stop_reason"];
|
|
318
|
+
}
|
|
319
|
+
} else if (type === "error") {
|
|
320
|
+
const error = event["error"] as Record<string, unknown> | undefined;
|
|
321
|
+
const kind = typeof error?.["type"] === "string" ? (error["type"] as string) : "stream-error";
|
|
322
|
+
// An in-stream error is a stop reason the OK list will reject, which is
|
|
323
|
+
// exactly the treatment a truncation gets — one path, not two.
|
|
324
|
+
stopReason = kind;
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
for (;;) {
|
|
329
|
+
const { done, value } = await reader.read();
|
|
330
|
+
if (done) break;
|
|
331
|
+
buffer += decoder.decode(value, { stream: true });
|
|
332
|
+
let cut = buffer.indexOf("\n");
|
|
333
|
+
while (cut >= 0) {
|
|
334
|
+
handle(buffer.slice(0, cut).trim());
|
|
335
|
+
buffer = buffer.slice(cut + 1);
|
|
336
|
+
cut = buffer.indexOf("\n");
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (buffer.trim().length > 0) handle(buffer.trim());
|
|
340
|
+
return { text, stopReason };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Find the first COMPLETE top-level JSON array in the text, by walking it with a
|
|
345
|
+
* scanner that knows about strings and escapes.
|
|
346
|
+
*
|
|
347
|
+
* The forbidden shortcut — slice from the first `[` to the last `]` — is scar
|
|
348
|
+
* §2.14: a bracket inside a quoted string moves the boundary and the parse
|
|
349
|
+
* fails on content that was perfectly well-formed. This walker cannot make that
|
|
350
|
+
* mistake because it never looks at a bracket that is inside a string.
|
|
351
|
+
*
|
|
352
|
+
* It returns the ARRAY's elements, unvalidated. Validation is `remember/`'s
|
|
353
|
+
* `intake()`, downstream, on purpose: the shape is pinned here and the MEANING
|
|
354
|
+
* is pinned there, and this file gets no opinion about the second.
|
|
355
|
+
*/
|
|
356
|
+
export function extractJson(text: string): unknown[] | null {
|
|
357
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
358
|
+
if (text[i] !== "[") continue;
|
|
359
|
+
const end = scanArray(text, i);
|
|
360
|
+
if (end === null) continue;
|
|
361
|
+
try {
|
|
362
|
+
const parsed: unknown = JSON.parse(text.slice(i, end + 1));
|
|
363
|
+
if (Array.isArray(parsed)) return parsed;
|
|
364
|
+
} catch {
|
|
365
|
+
// Not a valid array starting here; keep looking. A prose "[" in a preamble
|
|
366
|
+
// is exactly the case the naive slice gets wrong.
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** The index of the `]` closing the array that opens at `start`, or null. */
|
|
374
|
+
function scanArray(text: string, start: number): number | null {
|
|
375
|
+
let depth = 0;
|
|
376
|
+
let inString = false;
|
|
377
|
+
let escaped = false;
|
|
378
|
+
for (let i = start; i < text.length; i += 1) {
|
|
379
|
+
const ch = text[i];
|
|
380
|
+
if (inString) {
|
|
381
|
+
if (escaped) escaped = false;
|
|
382
|
+
else if (ch === "\\") escaped = true;
|
|
383
|
+
else if (ch === '"') inString = false;
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
if (ch === '"') inString = true;
|
|
387
|
+
else if (ch === "[" || ch === "{") depth += 1;
|
|
388
|
+
else if (ch === "]" || ch === "}") {
|
|
389
|
+
depth -= 1;
|
|
390
|
+
if (depth === 0) return ch === "]" ? i : null;
|
|
391
|
+
if (depth < 0) return null;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return null;
|
|
395
|
+
}
|