@caupulican/pi-adaptative 0.81.27 → 0.81.30
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 +32 -0
- package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
- package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
- package/dist/core/agent-session.d.ts +20 -3
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +73 -17
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +6 -0
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +35 -0
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +1 -1
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +5 -1
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +2 -0
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +31 -4
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/lane-tracker.d.ts +6 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +25 -3
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
- package/dist/core/autonomy/risk-assessment.js +1 -1
- package/dist/core/autonomy/risk-assessment.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +34 -1
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +204 -9
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/context/context-artifacts.d.ts.map +1 -1
- package/dist/core/context/context-artifacts.js +7 -6
- package/dist/core/context/context-artifacts.js.map +1 -1
- package/dist/core/context/context-store-retention.d.ts +12 -0
- package/dist/core/context/context-store-retention.d.ts.map +1 -0
- package/dist/core/context/context-store-retention.js +161 -0
- package/dist/core/context/context-store-retention.js.map +1 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +20 -4
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +18 -15
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +143 -38
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +7 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +28 -17
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost/daily-usage.d.ts +7 -3
- package/dist/core/cost/daily-usage.d.ts.map +1 -1
- package/dist/core/cost/daily-usage.js +10 -5
- package/dist/core/cost/daily-usage.js.map +1 -1
- package/dist/core/delegation/worker-result.d.ts.map +1 -1
- package/dist/core/delegation/worker-result.js +3 -0
- package/dist/core/delegation/worker-result.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +70 -5
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/export-html/template.js +2 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +52 -2
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +21 -19
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +5 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +36 -13
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts +16 -0
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +127 -30
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory-controller.d.ts +2 -0
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +18 -0
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-registry.d.ts +2 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -0
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts +2 -0
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +25 -14
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/runtime-arbiter.d.ts +11 -0
- package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
- package/dist/core/models/runtime-arbiter.js +35 -13
- package/dist/core/models/runtime-arbiter.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +5 -1
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +9 -3
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +19 -2
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +13 -5
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-analytics.d.ts +13 -7
- package/dist/core/session-analytics.d.ts.map +1 -1
- package/dist/core/session-analytics.js +155 -112
- package/dist/core/session-analytics.js.map +1 -1
- package/dist/core/tool-gate-controller.d.ts +3 -0
- package/dist/core/tool-gate-controller.d.ts.map +1 -1
- package/dist/core/tool-gate-controller.js +20 -15
- package/dist/core/tool-gate-controller.js.map +1 -1
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +54 -9
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-recovery-logger.d.ts +2 -0
- package/dist/core/tool-recovery-logger.d.ts.map +1 -1
- package/dist/core/tool-recovery-logger.js +32 -13
- package/dist/core/tool-recovery-logger.js.map +1 -1
- package/dist/core/tool-recovery-stats.d.ts +15 -0
- package/dist/core/tool-recovery-stats.d.ts.map +1 -0
- package/dist/core/tool-recovery-stats.js +206 -0
- package/dist/core/tool-recovery-stats.js.map +1 -0
- package/dist/core/tool-selection/expected-utility.d.ts +51 -0
- package/dist/core/tool-selection/expected-utility.d.ts.map +1 -0
- package/dist/core/tool-selection/expected-utility.js +85 -0
- package/dist/core/tool-selection/expected-utility.js.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts +82 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.js +249 -0
- package/dist/core/tool-selection/tool-performance-store.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts +41 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.js +199 -0
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -0
- package/dist/core/tools/delegate-status.d.ts +9 -0
- package/dist/core/tools/delegate-status.d.ts.map +1 -0
- package/dist/core/tools/delegate-status.js +61 -0
- package/dist/core/tools/delegate-status.js.map +1 -0
- package/dist/core/tools/delegate.d.ts +13 -0
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +28 -4
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/run-toolkit-script.d.ts +3 -0
- package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
- package/dist/core/tools/run-toolkit-script.js +17 -7
- package/dist/core/tools/run-toolkit-script.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +12 -1
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +19 -9
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
- package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
- package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +18 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.js +9 -28
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/utils/streaming-lines.d.ts +20 -0
- package/dist/utils/streaming-lines.d.ts.map +1 -0
- package/dist/utils/streaming-lines.js +79 -0
- package/dist/utils/streaming-lines.js.map +1 -0
- package/docs/extensions.md +2 -0
- package/docs/index.md +1 -1
- package/docs/integration-sweep-builder-blueprint-2026-07-09.md +365 -0
- package/docs/integration-sweep-resume-2026-07-09.md +407 -0
- package/docs/self-adaptation.md +7 -0
- package/docs/settings.md +7 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-artifacts.js","sourceRoot":"","sources":["../../../src/core/context/context-artifacts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAA2B,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AA0BnG,MAAM,UAAU,uBAAuB,CAAC,KAA6C,EAAkC;IACtH,OAAQ,KAA+B,CAAC,OAAO,KAAK,IAAI,CAAC;AAAA,CACzD;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CACjC,OAGC,EACQ;IACT,OAAO,UAAU,CAAC,QAAQ,CAAC;SACzB,MAAM,CACN;QACC,OAAO,CAAC,IAAI;QACZ,OAAO,CAAC,QAAQ,IAAI,EAAE;QACtB,OAAO,CAAC,OAAO,IAAI,EAAE;QACrB,OAAO,CAAC,IAAI,IAAI,EAAE;QAClB,OAAO,CAAC,cAAc,IAAI,EAAE;QAC5B,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC;QAC7B,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC;QAC5B,OAAO,CAAC,OAAO;KACf,CAAC,IAAI,CAAC,IAAI,CAAC,CACZ;SACA,MAAM,CAAC,KAAK,CAAC;SACb,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAAA,CACf;AAkCD,MAAM,UAAU,2BAA2B,GAAkB;IAC5D,MAAM,SAAS,GAAG,IAAI,GAAG,EAA0B,CAAC;IACpD,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IAEpC,OAA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CACF","sourcesContent":["/**\n * Artifact store abstraction (Phase 2): stable refs for raw large payloads, kept out of\n * band from prompt context. This module defines the `ArtifactStore` interface plus two\n * implementations: an in-memory one for tests, and `createFileArtifactStore` (session-\n * scoped, filesystem-backed). A SQLite-backed implementation waits until the Phase M0\n * storage-authority/location/concurrency decisions are accepted (see\n * docs/context-management-rework/memory-architecture.md).\n *\n * `createFileArtifactStore` is wired into live grep/find tool construction in\n * agent-session.ts (session-scoped under `<agentDir>/context-artifacts/<sessionId>/`).\n * References are registered at pack time and released when context-gc evicts the\n * corresponding grep/find tool result (opportunistic, conservative cleanup), with a\n * best-effort dispose-time sweep for zero-reference artifacts. Payloads are retrievable\n * out of band via the artifact_retrieve tool (context/artifact-retrieval.ts).\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { type ContextArtifactRef, estimateByteLength, estimateLineCount } from \"./context-item.ts\";\n\nexport interface ArtifactWriteRequest {\n\tkind: ContextArtifactRef[\"kind\"];\n\tcontent: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tsessionEntryId?: string;\n\tcreatedAtTurn: number;\n\treproducible: boolean;\n}\n\nexport interface ArtifactRecord {\n\tref: ContextArtifactRef;\n\tcontent: string;\n}\n\nexport type MissingArtifactReason = \"not_found\" | \"cleaned_up\";\n\nexport interface MissingArtifactMarker {\n\tid: string;\n\tmissing: true;\n\treason: MissingArtifactReason;\n}\n\nexport function isMissingArtifactMarker(value: ArtifactRecord | MissingArtifactMarker): value is MissingArtifactMarker {\n\treturn (value as MissingArtifactMarker).missing === true;\n}\n\n/**\n * Artifact id for a capture event, not merely a payload: it hashes every ref-defining\n * field (kind, tool/command/path, content, sessionEntryId, createdAtTurn, reproducible).\n * A repeat write with identical content but a different turn or session entry is a\n * distinct capture and must get a distinct id -- otherwise the later capture's metadata\n * would be silently discarded in favor of the first write. Only a truly identical\n * request (same capture, re-submitted) is idempotent under this id.\n */\nexport function generateArtifactId(\n\trequest: Pick<\n\t\tArtifactWriteRequest,\n\t\t\"kind\" | \"content\" | \"toolName\" | \"command\" | \"path\" | \"sessionEntryId\" | \"createdAtTurn\" | \"reproducible\"\n\t>,\n): string {\n\treturn createHash(\"sha256\")\n\t\t.update(\n\t\t\t[\n\t\t\t\trequest.kind,\n\t\t\t\trequest.toolName ?? \"\",\n\t\t\t\trequest.command ?? \"\",\n\t\t\t\trequest.path ?? \"\",\n\t\t\t\trequest.sessionEntryId ?? \"\",\n\t\t\t\tString(request.createdAtTurn),\n\t\t\t\tString(request.reproducible),\n\t\t\t\trequest.content,\n\t\t\t].join(\"\\0\"),\n\t\t)\n\t\t.digest(\"hex\")\n\t\t.slice(0, 24);\n}\n\nexport interface ArtifactStore {\n\twrite(request: ArtifactWriteRequest): ArtifactRecord;\n\tread(id: string): ArtifactRecord | MissingArtifactMarker;\n\t/**\n\t * Metadata-only lookup: the ref if `id` resolves to a live artifact, `undefined`\n\t * otherwise. Never loads the payload -- for the file store this must not touch the\n\t * payload file at all beyond an existence check, so a caller that only needs to know\n\t * \"does this still exist, and what are its ref fields\" (e.g. a per-turn audit pass)\n\t * never pays the cost of reading potentially large content off disk.\n\t */\n\treadRef(id: string): ContextArtifactRef | undefined;\n\thas(id: string): boolean;\n\t/**\n\t * Register that `holderId` (a context item id, session entry id, etc.) depends on this\n\t * artifact. Returns false if `id` does not exist (never written, or already cleaned\n\t * up) so a caller cannot believe it protected an artifact that was never registered.\n\t * Callers must fail closed (treat the artifact as unprotected) on a false return.\n\t */\n\taddReference(id: string, holderId: string): boolean;\n\t/** Release a previously registered dependency. Returns true only if a reference was actually removed. */\n\tremoveReference(id: string, holderId: string): boolean;\n\treferenceCount(id: string): number;\n\t/** Delete only artifacts with zero active references. Returns the ids actually deleted. */\n\tcleanup(): string[];\n}\n\ninterface StoredArtifact {\n\tref: ContextArtifactRef;\n\tcontent: string;\n\treferences: Set<string>;\n}\n\nexport function createInMemoryArtifactStore(): ArtifactStore {\n\tconst artifacts = new Map<string, StoredArtifact>();\n\tconst cleanedUp = new Set<string>();\n\n\treturn {\n\t\twrite(request: ArtifactWriteRequest): ArtifactRecord {\n\t\t\tconst id = generateArtifactId(request);\n\t\t\tconst existing = artifacts.get(id);\n\t\t\tif (existing) {\n\t\t\t\tcleanedUp.delete(id);\n\t\t\t\treturn { ref: existing.ref, content: existing.content };\n\t\t\t}\n\n\t\t\tconst ref: ContextArtifactRef = {\n\t\t\t\tid,\n\t\t\t\tkind: request.kind,\n\t\t\t\tsessionEntryId: request.sessionEntryId,\n\t\t\t\ttoolName: request.toolName,\n\t\t\t\tcommand: request.command,\n\t\t\t\tpath: request.path,\n\t\t\t\tbyteLength: estimateByteLength(request.content),\n\t\t\t\tlineCount: estimateLineCount(request.content),\n\t\t\t\tcreatedAtTurn: request.createdAtTurn,\n\t\t\t\treproducible: request.reproducible,\n\t\t\t};\n\t\t\tartifacts.set(id, { ref, content: request.content, references: new Set() });\n\t\t\tcleanedUp.delete(id);\n\t\t\treturn { ref, content: request.content };\n\t\t},\n\n\t\tread(id: string): ArtifactRecord | MissingArtifactMarker {\n\t\t\tconst stored = artifacts.get(id);\n\t\t\tif (!stored) {\n\t\t\t\treturn { id, missing: true, reason: cleanedUp.has(id) ? \"cleaned_up\" : \"not_found\" };\n\t\t\t}\n\t\t\treturn { ref: stored.ref, content: stored.content };\n\t\t},\n\n\t\treadRef(id: string): ContextArtifactRef | undefined {\n\t\t\treturn artifacts.get(id)?.ref;\n\t\t},\n\n\t\thas(id: string): boolean {\n\t\t\treturn artifacts.has(id);\n\t\t},\n\n\t\taddReference(id: string, holderId: string): boolean {\n\t\t\tconst stored = artifacts.get(id);\n\t\t\tif (!stored) return false;\n\t\t\tstored.references.add(holderId);\n\t\t\treturn true;\n\t\t},\n\n\t\tremoveReference(id: string, holderId: string): boolean {\n\t\t\tconst stored = artifacts.get(id);\n\t\t\tif (!stored) return false;\n\t\t\treturn stored.references.delete(holderId);\n\t\t},\n\n\t\treferenceCount(id: string): number {\n\t\t\treturn artifacts.get(id)?.references.size ?? 0;\n\t\t},\n\n\t\tcleanup(): string[] {\n\t\t\tconst deleted: string[] = [];\n\t\t\tfor (const [id, stored] of artifacts) {\n\t\t\t\tif (stored.references.size === 0) {\n\t\t\t\t\tartifacts.delete(id);\n\t\t\t\t\tcleanedUp.add(id);\n\t\t\t\t\tdeleted.push(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\nexport interface FileArtifactStoreOptions {\n\t/** Directory the store persists artifact payloads and metadata under. Created if missing. */\n\tbaseDir: string;\n}\n\ninterface PersistedArtifactMeta {\n\tref: ContextArtifactRef;\n\treferences: string[];\n}\n\nconst META_SUFFIX = \".meta.json\";\nconst PAYLOAD_SUFFIX = \".payload\";\n\n/**\n * Artifact ids are generated by `generateArtifactId` as a lowercase hex digest. Reject\n * anything else so a caller-supplied id (including one echoed back from model output)\n * can never be used as a path-traversal vector into `baseDir`.\n */\nfunction isSafeArtifactId(id: string): boolean {\n\treturn /^[0-9a-f]{1,64}$/.test(id);\n}\n\nfunction payloadPath(baseDir: string, id: string): string {\n\treturn join(baseDir, `${id}${PAYLOAD_SUFFIX}`);\n}\n\nfunction metaPath(baseDir: string, id: string): string {\n\treturn join(baseDir, `${id}${META_SUFFIX}`);\n}\n\nconst VALID_ARTIFACT_KINDS: ReadonlySet<ContextArtifactRef[\"kind\"]> = new Set([\n\t\"tool_output\",\n\t\"file_snapshot\",\n\t\"test_output\",\n\t\"diff\",\n\t\"transcript_slice\",\n]);\n\nfunction isValidArtifactRefShape(value: unknown): value is ContextArtifactRef {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst ref = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof ref.id === \"string\" &&\n\t\ttypeof ref.kind === \"string\" &&\n\t\tVALID_ARTIFACT_KINDS.has(ref.kind as ContextArtifactRef[\"kind\"]) &&\n\t\ttypeof ref.byteLength === \"number\" &&\n\t\ttypeof ref.createdAtTurn === \"number\" &&\n\t\ttypeof ref.reproducible === \"boolean\"\n\t);\n}\n\n/**\n * A parsed JSON value can be syntactically valid but semantically garbage (truncated\n * write, hand-edited file, future/incompatible format). Validate shape, not just parse\n * success, so a malformed sidecar can never produce an invalid ref or crash `cleanup()` --\n * it is treated as unusable/missing, the same as a sidecar that doesn't exist.\n */\nfunction isValidPersistedArtifactMeta(value: unknown): value is PersistedArtifactMeta {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst meta = value as Record<string, unknown>;\n\treturn (\n\t\tisValidArtifactRefShape(meta.ref) &&\n\t\tArray.isArray(meta.references) &&\n\t\tmeta.references.every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction readMeta(baseDir: string, id: string): PersistedArtifactMeta | undefined {\n\tconst path = metaPath(baseDir, id);\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n\t\treturn isValidPersistedArtifactMeta(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction writeMeta(baseDir: string, id: string, meta: PersistedArtifactMeta): void {\n\twriteFileSync(metaPath(baseDir, id), JSON.stringify(meta), \"utf8\");\n}\n\n/**\n * Filesystem-backed `ArtifactStore`: payload and metadata (including reference holder ids)\n * are written to `baseDir` so content, ref fields, and cleanup-protecting references all\n * survive recreating the store (e.g. across a process restart against the same\n * directory) -- unlike the in-memory store, which loses everything when the instance is\n * dropped. No SQLite or other index is used; each artifact's metadata is a small sidecar\n * JSON file next to its payload file, per the \"keep SQLite out of scope unless a minimal\n * metadata shape is unavoidable\" constraint for this slice.\n *\n * The one thing that does NOT survive recreation: the missing-artifact reason\n * distinction. A fresh instance has no in-memory record of which ids it personally\n * cleaned up, so a previously-cleaned-up id reads back as \"not_found\" rather than\n * \"cleaned_up\" after a restart. This still always returns an explicit missing marker,\n * never fabricated or empty content -- it only affects which of the two reason codes is\n * reported.\n */\nexport function createFileArtifactStore(options: FileArtifactStoreOptions): ArtifactStore {\n\tconst baseDir = options.baseDir;\n\tmkdirSync(baseDir, { recursive: true });\n\tconst cleanedUpThisInstance = new Set<string>();\n\n\treturn {\n\t\twrite(request: ArtifactWriteRequest): ArtifactRecord {\n\t\t\tconst id = generateArtifactId(request);\n\t\t\tconst existingMeta = readMeta(baseDir, id);\n\t\t\tconst existingPayloadPath = payloadPath(baseDir, id);\n\t\t\tif (existingMeta && existsSync(existingPayloadPath)) {\n\t\t\t\tcleanedUpThisInstance.delete(id);\n\t\t\t\treturn { ref: existingMeta.ref, content: readFileSync(existingPayloadPath, \"utf8\") };\n\t\t\t}\n\n\t\t\tconst ref: ContextArtifactRef = {\n\t\t\t\tid,\n\t\t\t\tkind: request.kind,\n\t\t\t\tsessionEntryId: request.sessionEntryId,\n\t\t\t\ttoolName: request.toolName,\n\t\t\t\tcommand: request.command,\n\t\t\t\tpath: request.path,\n\t\t\t\tbyteLength: estimateByteLength(request.content),\n\t\t\t\tlineCount: estimateLineCount(request.content),\n\t\t\t\tcreatedAtTurn: request.createdAtTurn,\n\t\t\t\treproducible: request.reproducible,\n\t\t\t};\n\t\t\twriteFileSync(payloadPath(baseDir, id), request.content, \"utf8\");\n\t\t\twriteMeta(baseDir, id, { ref, references: [] });\n\t\t\tcleanedUpThisInstance.delete(id);\n\t\t\treturn { ref, content: request.content };\n\t\t},\n\n\t\tread(id: string): ArtifactRecord | MissingArtifactMarker {\n\t\t\tif (!isSafeArtifactId(id)) return { id, missing: true, reason: \"not_found\" };\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tconst pPath = payloadPath(baseDir, id);\n\t\t\tif (!meta || !existsSync(pPath)) {\n\t\t\t\treturn { id, missing: true, reason: cleanedUpThisInstance.has(id) ? \"cleaned_up\" : \"not_found\" };\n\t\t\t}\n\t\t\treturn { ref: meta.ref, content: readFileSync(pPath, \"utf8\") };\n\t\t},\n\n\t\treadRef(id: string): ContextArtifactRef | undefined {\n\t\t\tif (!isSafeArtifactId(id)) return undefined;\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tif (!meta || !existsSync(payloadPath(baseDir, id))) return undefined;\n\t\t\treturn meta.ref;\n\t\t},\n\n\t\thas(id: string): boolean {\n\t\t\tif (!isSafeArtifactId(id)) return false;\n\t\t\treturn readMeta(baseDir, id) !== undefined && existsSync(payloadPath(baseDir, id));\n\t\t},\n\n\t\taddReference(id: string, holderId: string): boolean {\n\t\t\tif (!isSafeArtifactId(id)) return false;\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tif (!meta || !existsSync(payloadPath(baseDir, id))) return false;\n\t\t\tif (!meta.references.includes(holderId)) {\n\t\t\t\tmeta.references.push(holderId);\n\t\t\t\twriteMeta(baseDir, id, meta);\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\n\t\tremoveReference(id: string, holderId: string): boolean {\n\t\t\tif (!isSafeArtifactId(id)) return false;\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tif (!meta) return false;\n\t\t\tconst index = meta.references.indexOf(holderId);\n\t\t\tif (index === -1) return false;\n\t\t\tmeta.references.splice(index, 1);\n\t\t\twriteMeta(baseDir, id, meta);\n\t\t\treturn true;\n\t\t},\n\n\t\treferenceCount(id: string): number {\n\t\t\tif (!isSafeArtifactId(id)) return 0;\n\t\t\treturn readMeta(baseDir, id)?.references.length ?? 0;\n\t\t},\n\n\t\tcleanup(): string[] {\n\t\t\tconst deleted: string[] = [];\n\t\t\tfor (const entry of readdirSync(baseDir)) {\n\t\t\t\tif (!entry.endsWith(META_SUFFIX)) continue;\n\t\t\t\tconst id = entry.slice(0, -META_SUFFIX.length);\n\t\t\t\tif (!isSafeArtifactId(id)) continue;\n\t\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\t\tif (!meta || meta.references.length > 0) continue;\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(metaPath(baseDir, id));\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(payloadPath(baseDir, id));\n\t\t\t\t} catch {\n\t\t\t\t\t// Payload already gone; metadata removal above is what matters for reachability.\n\t\t\t\t}\n\t\t\t\tcleanedUpThisInstance.add(id);\n\t\t\t\tdeleted.push(id);\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-artifacts.js","sourceRoot":"","sources":["../../../src/core/context/context-artifacts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAA2B,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AA0BnG,MAAM,UAAU,uBAAuB,CAAC,KAA6C,EAAkC;IACtH,OAAQ,KAA+B,CAAC,OAAO,KAAK,IAAI,CAAC;AAAA,CACzD;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CACjC,OAGC,EACQ;IACT,MAAM,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;IAClC,KAAK,MAAM,KAAK,IAAI;QACnB,OAAO,CAAC,IAAI;QACZ,OAAO,CAAC,QAAQ,IAAI,EAAE;QACtB,OAAO,CAAC,OAAO,IAAI,EAAE;QACrB,OAAO,CAAC,IAAI,IAAI,EAAE;QAClB,OAAO,CAAC,cAAc,IAAI,EAAE;QAC5B,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC;QAC7B,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC;KAC5B,EAAE,CAAC;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM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AAC,MAAM,CAAC;oBACR,SAAS;gBACV,CAAC;gBACD,IAAI,CAAC;oBACJ,UAAU,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;gBACtC,CAAC;gBAAC,MAAM,CAAC;oBACR,iFAAiF;gBAClF,CAAC;gBACD,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;gBAC9B,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAClB,CAAC;YACD,OAAO,OAAO,CAAC;QAAA,CACf;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Artifact store abstraction (Phase 2): stable refs for raw large payloads, kept out of\n * band from prompt context. This module defines the `ArtifactStore` interface plus two\n * implementations: an in-memory one for tests, and `createFileArtifactStore` (session-\n * scoped, filesystem-backed). A SQLite-backed implementation waits until the Phase M0\n * storage-authority/location/concurrency decisions are accepted (see\n * docs/context-management-rework/memory-architecture.md).\n *\n * `createFileArtifactStore` is wired into live grep/find tool construction in\n * agent-session.ts (session-scoped under `<agentDir>/context-artifacts/<sessionId>/`).\n * References are registered at pack time and released when context-gc evicts the\n * corresponding grep/find tool result (opportunistic, conservative cleanup), with a\n * best-effort dispose-time sweep for zero-reference artifacts. Payloads are retrievable\n * out of band via the artifact_retrieve tool (context/artifact-retrieval.ts).\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { type ContextArtifactRef, estimateByteLength, estimateLineCount } from \"./context-item.ts\";\n\nexport interface ArtifactWriteRequest {\n\tkind: ContextArtifactRef[\"kind\"];\n\tcontent: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpath?: string;\n\tsessionEntryId?: string;\n\tcreatedAtTurn: number;\n\treproducible: boolean;\n}\n\nexport interface ArtifactRecord {\n\tref: ContextArtifactRef;\n\tcontent: string;\n}\n\nexport type MissingArtifactReason = \"not_found\" | \"cleaned_up\";\n\nexport interface MissingArtifactMarker {\n\tid: string;\n\tmissing: true;\n\treason: MissingArtifactReason;\n}\n\nexport function isMissingArtifactMarker(value: ArtifactRecord | MissingArtifactMarker): value is MissingArtifactMarker {\n\treturn (value as MissingArtifactMarker).missing === true;\n}\n\n/**\n * Artifact id for a capture event, not merely a payload: it hashes every ref-defining\n * field (kind, tool/command/path, content, sessionEntryId, createdAtTurn, reproducible).\n * A repeat write with identical content but a different turn or session entry is a\n * distinct capture and must get a distinct id -- otherwise the later capture's metadata\n * would be silently discarded in favor of the first write. Only a truly identical\n * request (same capture, re-submitted) is idempotent under this id.\n */\nexport function generateArtifactId(\n\trequest: Pick<\n\t\tArtifactWriteRequest,\n\t\t\"kind\" | \"content\" | \"toolName\" | \"command\" | \"path\" | \"sessionEntryId\" | \"createdAtTurn\" | \"reproducible\"\n\t>,\n): string {\n\tconst hash = createHash(\"sha256\");\n\tfor (const field of [\n\t\trequest.kind,\n\t\trequest.toolName ?? \"\",\n\t\trequest.command ?? \"\",\n\t\trequest.path ?? \"\",\n\t\trequest.sessionEntryId ?? \"\",\n\t\tString(request.createdAtTurn),\n\t\tString(request.reproducible),\n\t]) {\n\t\thash.update(field).update(\"\\0\");\n\t}\n\thash.update(request.content);\n\treturn hash.digest(\"hex\").slice(0, 24);\n}\n\nexport interface ArtifactStore {\n\twrite(request: ArtifactWriteRequest): ArtifactRecord;\n\tread(id: string): ArtifactRecord | MissingArtifactMarker;\n\t/**\n\t * Metadata-only lookup: the ref if `id` resolves to a live artifact, `undefined`\n\t * otherwise. Never loads the payload -- for the file store this must not touch the\n\t * payload file at all beyond an existence check, so a caller that only needs to know\n\t * \"does this still exist, and what are its ref fields\" (e.g. a per-turn audit pass)\n\t * never pays the cost of reading potentially large content off disk.\n\t */\n\treadRef(id: string): ContextArtifactRef | undefined;\n\thas(id: string): boolean;\n\t/**\n\t * Register that `holderId` (a context item id, session entry id, etc.) depends on this\n\t * artifact. Returns false if `id` does not exist (never written, or already cleaned\n\t * up) so a caller cannot believe it protected an artifact that was never registered.\n\t * Callers must fail closed (treat the artifact as unprotected) on a false return.\n\t */\n\taddReference(id: string, holderId: string): boolean;\n\t/** Release a previously registered dependency. Returns true only if a reference was actually removed. */\n\tremoveReference(id: string, holderId: string): boolean;\n\treferenceCount(id: string): number;\n\t/** Delete only artifacts with zero active references. Returns the ids actually deleted. */\n\tcleanup(): string[];\n}\n\ninterface StoredArtifact {\n\tref: ContextArtifactRef;\n\tcontent: string;\n\treferences: Set<string>;\n}\n\nexport function createInMemoryArtifactStore(): ArtifactStore {\n\tconst artifacts = new Map<string, StoredArtifact>();\n\tconst cleanedUp = new Set<string>();\n\n\treturn {\n\t\twrite(request: ArtifactWriteRequest): ArtifactRecord {\n\t\t\tconst id = generateArtifactId(request);\n\t\t\tconst existing = artifacts.get(id);\n\t\t\tif (existing) {\n\t\t\t\tcleanedUp.delete(id);\n\t\t\t\treturn { ref: existing.ref, content: existing.content };\n\t\t\t}\n\n\t\t\tconst ref: ContextArtifactRef = {\n\t\t\t\tid,\n\t\t\t\tkind: request.kind,\n\t\t\t\tsessionEntryId: request.sessionEntryId,\n\t\t\t\ttoolName: request.toolName,\n\t\t\t\tcommand: request.command,\n\t\t\t\tpath: request.path,\n\t\t\t\tbyteLength: estimateByteLength(request.content),\n\t\t\t\tlineCount: estimateLineCount(request.content),\n\t\t\t\tcreatedAtTurn: request.createdAtTurn,\n\t\t\t\treproducible: request.reproducible,\n\t\t\t};\n\t\t\tartifacts.set(id, { ref, content: request.content, references: new Set() });\n\t\t\tcleanedUp.delete(id);\n\t\t\treturn { ref, content: request.content };\n\t\t},\n\n\t\tread(id: string): ArtifactRecord | MissingArtifactMarker {\n\t\t\tconst stored = artifacts.get(id);\n\t\t\tif (!stored) {\n\t\t\t\treturn { id, missing: true, reason: cleanedUp.has(id) ? \"cleaned_up\" : \"not_found\" };\n\t\t\t}\n\t\t\treturn { ref: stored.ref, content: stored.content };\n\t\t},\n\n\t\treadRef(id: string): ContextArtifactRef | undefined {\n\t\t\treturn artifacts.get(id)?.ref;\n\t\t},\n\n\t\thas(id: string): boolean {\n\t\t\treturn artifacts.has(id);\n\t\t},\n\n\t\taddReference(id: string, holderId: string): boolean {\n\t\t\tconst stored = artifacts.get(id);\n\t\t\tif (!stored) return false;\n\t\t\tstored.references.add(holderId);\n\t\t\treturn true;\n\t\t},\n\n\t\tremoveReference(id: string, holderId: string): boolean {\n\t\t\tconst stored = artifacts.get(id);\n\t\t\tif (!stored) return false;\n\t\t\treturn stored.references.delete(holderId);\n\t\t},\n\n\t\treferenceCount(id: string): number {\n\t\t\treturn artifacts.get(id)?.references.size ?? 0;\n\t\t},\n\n\t\tcleanup(): string[] {\n\t\t\tconst deleted: string[] = [];\n\t\t\tfor (const [id, stored] of artifacts) {\n\t\t\t\tif (stored.references.size === 0) {\n\t\t\t\t\tartifacts.delete(id);\n\t\t\t\t\tcleanedUp.add(id);\n\t\t\t\t\tdeleted.push(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n\nexport interface FileArtifactStoreOptions {\n\t/** Directory the store persists artifact payloads and metadata under. Created if missing. */\n\tbaseDir: string;\n}\n\ninterface PersistedArtifactMeta {\n\tref: ContextArtifactRef;\n\treferences: string[];\n}\n\nconst META_SUFFIX = \".meta.json\";\nconst PAYLOAD_SUFFIX = \".payload\";\n\n/**\n * Artifact ids are generated by `generateArtifactId` as a lowercase hex digest. Reject\n * anything else so a caller-supplied id (including one echoed back from model output)\n * can never be used as a path-traversal vector into `baseDir`.\n */\nfunction isSafeArtifactId(id: string): boolean {\n\treturn /^[0-9a-f]{1,64}$/.test(id);\n}\n\nfunction payloadPath(baseDir: string, id: string): string {\n\treturn join(baseDir, `${id}${PAYLOAD_SUFFIX}`);\n}\n\nfunction metaPath(baseDir: string, id: string): string {\n\treturn join(baseDir, `${id}${META_SUFFIX}`);\n}\n\nconst VALID_ARTIFACT_KINDS: ReadonlySet<ContextArtifactRef[\"kind\"]> = new Set([\n\t\"tool_output\",\n\t\"file_snapshot\",\n\t\"test_output\",\n\t\"diff\",\n\t\"transcript_slice\",\n]);\n\nfunction isValidArtifactRefShape(value: unknown): value is ContextArtifactRef {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst ref = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof ref.id === \"string\" &&\n\t\ttypeof ref.kind === \"string\" &&\n\t\tVALID_ARTIFACT_KINDS.has(ref.kind as ContextArtifactRef[\"kind\"]) &&\n\t\ttypeof ref.byteLength === \"number\" &&\n\t\ttypeof ref.createdAtTurn === \"number\" &&\n\t\ttypeof ref.reproducible === \"boolean\"\n\t);\n}\n\n/**\n * A parsed JSON value can be syntactically valid but semantically garbage (truncated\n * write, hand-edited file, future/incompatible format). Validate shape, not just parse\n * success, so a malformed sidecar can never produce an invalid ref or crash `cleanup()` --\n * it is treated as unusable/missing, the same as a sidecar that doesn't exist.\n */\nfunction isValidPersistedArtifactMeta(value: unknown): value is PersistedArtifactMeta {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst meta = value as Record<string, unknown>;\n\treturn (\n\t\tisValidArtifactRefShape(meta.ref) &&\n\t\tArray.isArray(meta.references) &&\n\t\tmeta.references.every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction readMeta(baseDir: string, id: string): PersistedArtifactMeta | undefined {\n\tconst path = metaPath(baseDir, id);\n\tif (!existsSync(path)) return undefined;\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n\t\treturn isValidPersistedArtifactMeta(parsed) ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction writeMeta(baseDir: string, id: string, meta: PersistedArtifactMeta): void {\n\twriteFileSync(metaPath(baseDir, id), JSON.stringify(meta), \"utf8\");\n}\n\n/**\n * Filesystem-backed `ArtifactStore`: payload and metadata (including reference holder ids)\n * are written to `baseDir` so content, ref fields, and cleanup-protecting references all\n * survive recreating the store (e.g. across a process restart against the same\n * directory) -- unlike the in-memory store, which loses everything when the instance is\n * dropped. No SQLite or other index is used; each artifact's metadata is a small sidecar\n * JSON file next to its payload file, per the \"keep SQLite out of scope unless a minimal\n * metadata shape is unavoidable\" constraint for this slice.\n *\n * The one thing that does NOT survive recreation: the missing-artifact reason\n * distinction. A fresh instance has no in-memory record of which ids it personally\n * cleaned up, so a previously-cleaned-up id reads back as \"not_found\" rather than\n * \"cleaned_up\" after a restart. This still always returns an explicit missing marker,\n * never fabricated or empty content -- it only affects which of the two reason codes is\n * reported.\n */\nexport function createFileArtifactStore(options: FileArtifactStoreOptions): ArtifactStore {\n\tconst baseDir = options.baseDir;\n\tmkdirSync(baseDir, { recursive: true });\n\tconst cleanedUpThisInstance = new Set<string>();\n\n\treturn {\n\t\twrite(request: ArtifactWriteRequest): ArtifactRecord {\n\t\t\tconst id = generateArtifactId(request);\n\t\t\tconst existingMeta = readMeta(baseDir, id);\n\t\t\tconst existingPayloadPath = payloadPath(baseDir, id);\n\t\t\tif (existingMeta && existsSync(existingPayloadPath)) {\n\t\t\t\tcleanedUpThisInstance.delete(id);\n\t\t\t\treturn { ref: existingMeta.ref, content: readFileSync(existingPayloadPath, \"utf8\") };\n\t\t\t}\n\n\t\t\tconst ref: ContextArtifactRef = {\n\t\t\t\tid,\n\t\t\t\tkind: request.kind,\n\t\t\t\tsessionEntryId: request.sessionEntryId,\n\t\t\t\ttoolName: request.toolName,\n\t\t\t\tcommand: request.command,\n\t\t\t\tpath: request.path,\n\t\t\t\tbyteLength: estimateByteLength(request.content),\n\t\t\t\tlineCount: estimateLineCount(request.content),\n\t\t\t\tcreatedAtTurn: request.createdAtTurn,\n\t\t\t\treproducible: request.reproducible,\n\t\t\t};\n\t\t\twriteFileSync(payloadPath(baseDir, id), request.content, \"utf8\");\n\t\t\twriteMeta(baseDir, id, { ref, references: [] });\n\t\t\tcleanedUpThisInstance.delete(id);\n\t\t\treturn { ref, content: request.content };\n\t\t},\n\n\t\tread(id: string): ArtifactRecord | MissingArtifactMarker {\n\t\t\tif (!isSafeArtifactId(id)) return { id, missing: true, reason: \"not_found\" };\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tconst pPath = payloadPath(baseDir, id);\n\t\t\tif (!meta || !existsSync(pPath)) {\n\t\t\t\treturn { id, missing: true, reason: cleanedUpThisInstance.has(id) ? \"cleaned_up\" : \"not_found\" };\n\t\t\t}\n\t\t\treturn { ref: meta.ref, content: readFileSync(pPath, \"utf8\") };\n\t\t},\n\n\t\treadRef(id: string): ContextArtifactRef | undefined {\n\t\t\tif (!isSafeArtifactId(id)) return undefined;\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tif (!meta || !existsSync(payloadPath(baseDir, id))) return undefined;\n\t\t\treturn meta.ref;\n\t\t},\n\n\t\thas(id: string): boolean {\n\t\t\tif (!isSafeArtifactId(id)) return false;\n\t\t\treturn readMeta(baseDir, id) !== undefined && existsSync(payloadPath(baseDir, id));\n\t\t},\n\n\t\taddReference(id: string, holderId: string): boolean {\n\t\t\tif (!isSafeArtifactId(id)) return false;\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tif (!meta || !existsSync(payloadPath(baseDir, id))) return false;\n\t\t\tif (!meta.references.includes(holderId)) {\n\t\t\t\tmeta.references.push(holderId);\n\t\t\t\twriteMeta(baseDir, id, meta);\n\t\t\t}\n\t\t\treturn true;\n\t\t},\n\n\t\tremoveReference(id: string, holderId: string): boolean {\n\t\t\tif (!isSafeArtifactId(id)) return false;\n\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\tif (!meta) return false;\n\t\t\tconst index = meta.references.indexOf(holderId);\n\t\t\tif (index === -1) return false;\n\t\t\tmeta.references.splice(index, 1);\n\t\t\twriteMeta(baseDir, id, meta);\n\t\t\treturn true;\n\t\t},\n\n\t\treferenceCount(id: string): number {\n\t\t\tif (!isSafeArtifactId(id)) return 0;\n\t\t\treturn readMeta(baseDir, id)?.references.length ?? 0;\n\t\t},\n\n\t\tcleanup(): string[] {\n\t\t\tconst deleted: string[] = [];\n\t\t\tfor (const entry of readdirSync(baseDir)) {\n\t\t\t\tif (!entry.endsWith(META_SUFFIX)) continue;\n\t\t\t\tconst id = entry.slice(0, -META_SUFFIX.length);\n\t\t\t\tif (!isSafeArtifactId(id)) continue;\n\t\t\t\tconst meta = readMeta(baseDir, id);\n\t\t\t\tif (!meta || meta.references.length > 0) continue;\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(metaPath(baseDir, id));\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(payloadPath(baseDir, id));\n\t\t\t\t} catch {\n\t\t\t\t\t// Payload already gone; metadata removal above is what matters for reachability.\n\t\t\t\t}\n\t\t\t\tcleanedUpThisInstance.add(id);\n\t\t\t\tdeleted.push(id);\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface ContextStoreRetentionOptions {
|
|
2
|
+
maxAgeMs?: number;
|
|
3
|
+
maxSessionDirs?: number;
|
|
4
|
+
maxTotalBytes?: number;
|
|
5
|
+
now?: number;
|
|
6
|
+
}
|
|
7
|
+
export interface ContextStoreRetentionLease {
|
|
8
|
+
release(): void;
|
|
9
|
+
}
|
|
10
|
+
export declare function pruneContextStoreRoot(rootDir: string, options?: ContextStoreRetentionOptions): string[];
|
|
11
|
+
export declare function acquireContextStoreRetention(agentDir: string, sessionId: string, options?: ContextStoreRetentionOptions): ContextStoreRetentionLease;
|
|
12
|
+
//# sourceMappingURL=context-store-retention.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-store-retention.d.ts","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAsBA,MAAM,WAAW,4BAA4B;IAC5C,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,0BAA0B;IAC1C,OAAO,IAAI,IAAI,CAAC;CAChB;AAuFD,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,4BAAiC,GAAG,MAAM,EAAE,CAyB3G;AAED,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE,4BAAiC,GACxC,0BAA0B,CAkC5B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst ACTIVE_MARKER_PREFIX = \"active-\";\nconst ACTIVE_MARKER_SUFFIX = \".json\";\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\trelease(): void;\n}\n\ninterface SessionDirectory {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n\tactive: boolean;\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nfunction directoryBytes(path: string): number {\n\tlet total = 0;\n\tfor (const entry of readdirSync(path, { withFileTypes: true })) {\n\t\tconst child = join(path, entry.name);\n\t\ttry {\n\t\t\tif (entry.isDirectory()) total += directoryBytes(child);\n\t\t\telse total += lstatSync(child).size;\n\t\t} catch {\n\t\t\t// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction markerProcessIsAlive(path: string): boolean {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { pid?: unknown };\n\t\tif (typeof parsed.pid !== \"number\" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return false;\n\t\ttry {\n\t\t\tprocess.kill(parsed.pid, 0);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction cleanupStaleLeases(rootDir: string): void {\n\tconst leasesRoot = join(rootDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesRoot)) return;\n\tfor (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst leaseDir = join(leasesRoot, entry.name);\n\t\ttry {\n\t\t\tfor (const marker of readdirSync(leaseDir)) {\n\t\t\t\tconst markerPath = join(leaseDir, marker);\n\t\t\t\tif (!markerProcessIsAlive(markerPath)) unlinkSync(markerPath);\n\t\t\t}\n\t\t\trmdirSync(leaseDir);\n\t\t} catch {\n\t\t\t// A live marker or concurrent lease keeps the directory in place.\n\t\t}\n\t}\n}\n\nfunction inspectSessionDirectories(rootDir: string): SessionDirectory[] {\n\tif (!existsSync(rootDir)) return [];\n\tcleanupStaleLeases(rootDir);\n\tconst directories: SessionDirectory[] = [];\n\tfor (const entry of readdirSync(rootDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory() || entry.name === LEASES_DIRECTORY) continue;\n\t\tconst path = join(rootDir, entry.name);\n\t\ttry {\n\t\t\tconst leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);\n\t\t\tconst markerPaths = existsSync(leaseDir)\n\t\t\t\t? readdirSync(leaseDir)\n\t\t\t\t\t\t.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))\n\t\t\t\t\t\t.map((name) => join(leaseDir, name))\n\t\t\t\t: [];\n\t\t\tdirectories.push({\n\t\t\t\tpath,\n\t\t\t\tmtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),\n\t\t\t\tbytes: directoryBytes(path),\n\t\t\t\tactive: markerPaths.some(markerProcessIsAlive),\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore a directory that disappeared or became unreadable during the scan.\n\t\t}\n\t}\n\treturn directories;\n}\n\nexport function pruneContextStoreRoot(rootDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);\n\tconst maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst directories = inspectSessionDirectories(rootDir);\n\tconst removed: string[] = [];\n\tlet retainedCount = directories.length;\n\tlet retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);\n\tfor (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tif (directory.active) continue;\n\t\tconst expired = now - directory.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxSessionDirs;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\ttry {\n\t\t\trmSync(directory.path, { recursive: true, force: true });\n\t\t\tremoved.push(directory.path);\n\t\t\tretainedCount--;\n\t\t\tretainedBytes -= directory.bytes;\n\t\t} catch {\n\t\t\t// Retention is best-effort and must never block a live session.\n\t\t}\n\t}\n\treturn removed;\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tif (!/^[A-Za-z0-9_-]+$/.test(sessionId)) return { release: () => {} };\n\tconst roots = [join(agentDir, \"context-gc\"), join(agentDir, \"context-artifacts\")];\n\tconst markerPaths: string[] = [];\n\tfor (const root of roots) {\n\t\tconst sessionDir = join(root, sessionId);\n\t\ttry {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t\tconst leaseDir = join(root, LEASES_DIRECTORY, sessionId);\n\t\t\tmkdirSync(leaseDir, { recursive: true });\n\t\t\tconst markerPath = join(\n\t\t\t\tleaseDir,\n\t\t\t\t`${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`,\n\t\t\t);\n\t\t\twriteFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), \"utf-8\");\n\t\t\tmarkerPaths.push(markerPath);\n\t\t\tpruneContextStoreRoot(root, options);\n\t\t} catch {\n\t\t\t// Retention is best-effort; the caller can still use its normal store path.\n\t\t}\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tfor (const markerPath of markerPaths) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(markerPath);\n\t\t\t\t\trmdirSync(dirname(markerPath));\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
const LEASES_DIRECTORY = ".leases";
|
|
5
|
+
const ACTIVE_MARKER_PREFIX = "active-";
|
|
6
|
+
const ACTIVE_MARKER_SUFFIX = ".json";
|
|
7
|
+
const DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
8
|
+
const DEFAULT_MAX_SESSION_DIRS = 64;
|
|
9
|
+
const DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;
|
|
10
|
+
function positiveLimit(value, fallback) {
|
|
11
|
+
return value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
12
|
+
}
|
|
13
|
+
function directoryBytes(path) {
|
|
14
|
+
let total = 0;
|
|
15
|
+
for (const entry of readdirSync(path, { withFileTypes: true })) {
|
|
16
|
+
const child = join(path, entry.name);
|
|
17
|
+
try {
|
|
18
|
+
if (entry.isDirectory())
|
|
19
|
+
total += directoryBytes(child);
|
|
20
|
+
else
|
|
21
|
+
total += lstatSync(child).size;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return total;
|
|
28
|
+
}
|
|
29
|
+
function markerProcessIsAlive(path) {
|
|
30
|
+
try {
|
|
31
|
+
const parsed = JSON.parse(readFileSync(path, "utf-8"));
|
|
32
|
+
if (typeof parsed.pid !== "number" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0)
|
|
33
|
+
return false;
|
|
34
|
+
try {
|
|
35
|
+
process.kill(parsed.pid, 0);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
return error.code === "EPERM";
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function cleanupStaleLeases(rootDir) {
|
|
47
|
+
const leasesRoot = join(rootDir, LEASES_DIRECTORY);
|
|
48
|
+
if (!existsSync(leasesRoot))
|
|
49
|
+
return;
|
|
50
|
+
for (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {
|
|
51
|
+
if (!entry.isDirectory())
|
|
52
|
+
continue;
|
|
53
|
+
const leaseDir = join(leasesRoot, entry.name);
|
|
54
|
+
try {
|
|
55
|
+
for (const marker of readdirSync(leaseDir)) {
|
|
56
|
+
const markerPath = join(leaseDir, marker);
|
|
57
|
+
if (!markerProcessIsAlive(markerPath))
|
|
58
|
+
unlinkSync(markerPath);
|
|
59
|
+
}
|
|
60
|
+
rmdirSync(leaseDir);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// A live marker or concurrent lease keeps the directory in place.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function inspectSessionDirectories(rootDir) {
|
|
68
|
+
if (!existsSync(rootDir))
|
|
69
|
+
return [];
|
|
70
|
+
cleanupStaleLeases(rootDir);
|
|
71
|
+
const directories = [];
|
|
72
|
+
for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
|
|
73
|
+
if (!entry.isDirectory() || entry.name === LEASES_DIRECTORY)
|
|
74
|
+
continue;
|
|
75
|
+
const path = join(rootDir, entry.name);
|
|
76
|
+
try {
|
|
77
|
+
const leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);
|
|
78
|
+
const markerPaths = existsSync(leaseDir)
|
|
79
|
+
? readdirSync(leaseDir)
|
|
80
|
+
.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))
|
|
81
|
+
.map((name) => join(leaseDir, name))
|
|
82
|
+
: [];
|
|
83
|
+
directories.push({
|
|
84
|
+
path,
|
|
85
|
+
mtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),
|
|
86
|
+
bytes: directoryBytes(path),
|
|
87
|
+
active: markerPaths.some(markerProcessIsAlive),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// Ignore a directory that disappeared or became unreadable during the scan.
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return directories;
|
|
95
|
+
}
|
|
96
|
+
export function pruneContextStoreRoot(rootDir, options = {}) {
|
|
97
|
+
const now = options.now ?? Date.now();
|
|
98
|
+
const maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);
|
|
99
|
+
const maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);
|
|
100
|
+
const maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);
|
|
101
|
+
const directories = inspectSessionDirectories(rootDir);
|
|
102
|
+
const removed = [];
|
|
103
|
+
let retainedCount = directories.length;
|
|
104
|
+
let retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);
|
|
105
|
+
for (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {
|
|
106
|
+
if (directory.active)
|
|
107
|
+
continue;
|
|
108
|
+
const expired = now - directory.mtimeMs > maxAgeMs;
|
|
109
|
+
const overCount = retainedCount > maxSessionDirs;
|
|
110
|
+
const overBytes = retainedBytes > maxTotalBytes;
|
|
111
|
+
if (!expired && !overCount && !overBytes)
|
|
112
|
+
continue;
|
|
113
|
+
try {
|
|
114
|
+
rmSync(directory.path, { recursive: true, force: true });
|
|
115
|
+
removed.push(directory.path);
|
|
116
|
+
retainedCount--;
|
|
117
|
+
retainedBytes -= directory.bytes;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// Retention is best-effort and must never block a live session.
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return removed;
|
|
124
|
+
}
|
|
125
|
+
export function acquireContextStoreRetention(agentDir, sessionId, options = {}) {
|
|
126
|
+
if (!/^[A-Za-z0-9_-]+$/.test(sessionId))
|
|
127
|
+
return { release: () => { } };
|
|
128
|
+
const roots = [join(agentDir, "context-gc"), join(agentDir, "context-artifacts")];
|
|
129
|
+
const markerPaths = [];
|
|
130
|
+
for (const root of roots) {
|
|
131
|
+
const sessionDir = join(root, sessionId);
|
|
132
|
+
try {
|
|
133
|
+
mkdirSync(sessionDir, { recursive: true });
|
|
134
|
+
const leaseDir = join(root, LEASES_DIRECTORY, sessionId);
|
|
135
|
+
mkdirSync(leaseDir, { recursive: true });
|
|
136
|
+
const markerPath = join(leaseDir, `${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`);
|
|
137
|
+
writeFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), "utf-8");
|
|
138
|
+
markerPaths.push(markerPath);
|
|
139
|
+
pruneContextStoreRoot(root, options);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// Retention is best-effort; the caller can still use its normal store path.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
let released = false;
|
|
146
|
+
return {
|
|
147
|
+
release() {
|
|
148
|
+
if (released)
|
|
149
|
+
return;
|
|
150
|
+
released = true;
|
|
151
|
+
for (const markerPath of markerPaths) {
|
|
152
|
+
try {
|
|
153
|
+
unlinkSync(markerPath);
|
|
154
|
+
rmdirSync(dirname(markerPath));
|
|
155
|
+
}
|
|
156
|
+
catch { }
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
//# sourceMappingURL=context-store-retention.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-store-retention.js","sourceRoot":"","sources":["../../../src/core/context/context-store-retention.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,WAAW,EACX,YAAY,EACZ,SAAS,EACT,MAAM,EACN,QAAQ,EACR,UAAU,EACV,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE1C,MAAM,gBAAgB,GAAG,SAAS,CAAC;AACnC,MAAM,oBAAoB,GAAG,SAAS,CAAC;AACvC,MAAM,oBAAoB,GAAG,OAAO,C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C,GAAG,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;YAChG,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YAC7B,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtC,CAAC;QAAC,MAAM,CAAC;YACR,4EAA4E;QAC7E,CAAC;IACF,CAAC;IACD,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,OAAO;QACN,OAAO,GAAS;YACf,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;gBACtC,IAAI,CAAC;oBACJ,UAAU,CAAC,UAAU,CAAC,CAAC;oBACvB,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;gBAChC,CAAC;gBAAC,MAAM,CAAC,CAAA,CAAC;YACX,CAAC;QAAA,CACD;KACD,CAAC;AAAA,CACF","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tstatSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nconst LEASES_DIRECTORY = \".leases\";\nconst ACTIVE_MARKER_PREFIX = \"active-\";\nconst ACTIVE_MARKER_SUFFIX = \".json\";\nconst DEFAULT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_SESSION_DIRS = 64;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * 1024 * 1024;\n\nexport interface ContextStoreRetentionOptions {\n\tmaxAgeMs?: number;\n\tmaxSessionDirs?: number;\n\tmaxTotalBytes?: number;\n\tnow?: number;\n}\n\nexport interface ContextStoreRetentionLease {\n\trelease(): void;\n}\n\ninterface SessionDirectory {\n\tpath: string;\n\tmtimeMs: number;\n\tbytes: number;\n\tactive: boolean;\n}\n\nfunction positiveLimit(value: number | undefined, fallback: number): number {\n\treturn value !== undefined && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;\n}\n\nfunction directoryBytes(path: string): number {\n\tlet total = 0;\n\tfor (const entry of readdirSync(path, { withFileTypes: true })) {\n\t\tconst child = join(path, entry.name);\n\t\ttry {\n\t\t\tif (entry.isDirectory()) total += directoryBytes(child);\n\t\t\telse total += lstatSync(child).size;\n\t\t} catch {\n\t\t\t// Concurrent cleanup or an unreadable entry is ignored by best-effort retention.\n\t\t}\n\t}\n\treturn total;\n}\n\nfunction markerProcessIsAlive(path: string): boolean {\n\ttry {\n\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { pid?: unknown };\n\t\tif (typeof parsed.pid !== \"number\" || !Number.isSafeInteger(parsed.pid) || parsed.pid <= 0) return false;\n\t\ttry {\n\t\t\tprocess.kill(parsed.pid, 0);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\treturn (error as NodeJS.ErrnoException).code === \"EPERM\";\n\t\t}\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction cleanupStaleLeases(rootDir: string): void {\n\tconst leasesRoot = join(rootDir, LEASES_DIRECTORY);\n\tif (!existsSync(leasesRoot)) return;\n\tfor (const entry of readdirSync(leasesRoot, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst leaseDir = join(leasesRoot, entry.name);\n\t\ttry {\n\t\t\tfor (const marker of readdirSync(leaseDir)) {\n\t\t\t\tconst markerPath = join(leaseDir, marker);\n\t\t\t\tif (!markerProcessIsAlive(markerPath)) unlinkSync(markerPath);\n\t\t\t}\n\t\t\trmdirSync(leaseDir);\n\t\t} catch {\n\t\t\t// A live marker or concurrent lease keeps the directory in place.\n\t\t}\n\t}\n}\n\nfunction inspectSessionDirectories(rootDir: string): SessionDirectory[] {\n\tif (!existsSync(rootDir)) return [];\n\tcleanupStaleLeases(rootDir);\n\tconst directories: SessionDirectory[] = [];\n\tfor (const entry of readdirSync(rootDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory() || entry.name === LEASES_DIRECTORY) continue;\n\t\tconst path = join(rootDir, entry.name);\n\t\ttry {\n\t\t\tconst leaseDir = join(rootDir, LEASES_DIRECTORY, entry.name);\n\t\t\tconst markerPaths = existsSync(leaseDir)\n\t\t\t\t? readdirSync(leaseDir)\n\t\t\t\t\t\t.filter((name) => name.startsWith(ACTIVE_MARKER_PREFIX) && name.endsWith(ACTIVE_MARKER_SUFFIX))\n\t\t\t\t\t\t.map((name) => join(leaseDir, name))\n\t\t\t\t: [];\n\t\t\tdirectories.push({\n\t\t\t\tpath,\n\t\t\t\tmtimeMs: Math.max(statSync(path).mtimeMs, ...markerPaths.map((markerPath) => statSync(markerPath).mtimeMs)),\n\t\t\t\tbytes: directoryBytes(path),\n\t\t\t\tactive: markerPaths.some(markerProcessIsAlive),\n\t\t\t});\n\t\t} catch {\n\t\t\t// Ignore a directory that disappeared or became unreadable during the scan.\n\t\t}\n\t}\n\treturn directories;\n}\n\nexport function pruneContextStoreRoot(rootDir: string, options: ContextStoreRetentionOptions = {}): string[] {\n\tconst now = options.now ?? Date.now();\n\tconst maxAgeMs = positiveLimit(options.maxAgeMs, DEFAULT_MAX_AGE_MS);\n\tconst maxSessionDirs = positiveLimit(options.maxSessionDirs, DEFAULT_MAX_SESSION_DIRS);\n\tconst maxTotalBytes = positiveLimit(options.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES);\n\tconst directories = inspectSessionDirectories(rootDir);\n\tconst removed: string[] = [];\n\tlet retainedCount = directories.length;\n\tlet retainedBytes = directories.reduce((sum, directory) => sum + directory.bytes, 0);\n\tfor (const directory of directories.sort((left, right) => left.mtimeMs - right.mtimeMs)) {\n\t\tif (directory.active) continue;\n\t\tconst expired = now - directory.mtimeMs > maxAgeMs;\n\t\tconst overCount = retainedCount > maxSessionDirs;\n\t\tconst overBytes = retainedBytes > maxTotalBytes;\n\t\tif (!expired && !overCount && !overBytes) continue;\n\t\ttry {\n\t\t\trmSync(directory.path, { recursive: true, force: true });\n\t\t\tremoved.push(directory.path);\n\t\t\tretainedCount--;\n\t\t\tretainedBytes -= directory.bytes;\n\t\t} catch {\n\t\t\t// Retention is best-effort and must never block a live session.\n\t\t}\n\t}\n\treturn removed;\n}\n\nexport function acquireContextStoreRetention(\n\tagentDir: string,\n\tsessionId: string,\n\toptions: ContextStoreRetentionOptions = {},\n): ContextStoreRetentionLease {\n\tif (!/^[A-Za-z0-9_-]+$/.test(sessionId)) return { release: () => {} };\n\tconst roots = [join(agentDir, \"context-gc\"), join(agentDir, \"context-artifacts\")];\n\tconst markerPaths: string[] = [];\n\tfor (const root of roots) {\n\t\tconst sessionDir = join(root, sessionId);\n\t\ttry {\n\t\t\tmkdirSync(sessionDir, { recursive: true });\n\t\t\tconst leaseDir = join(root, LEASES_DIRECTORY, sessionId);\n\t\t\tmkdirSync(leaseDir, { recursive: true });\n\t\t\tconst markerPath = join(\n\t\t\t\tleaseDir,\n\t\t\t\t`${ACTIVE_MARKER_PREFIX}${process.pid}-${randomUUID()}${ACTIVE_MARKER_SUFFIX}`,\n\t\t\t);\n\t\t\twriteFileSync(markerPath, JSON.stringify({ pid: process.pid, touchedAt: Date.now() }), \"utf-8\");\n\t\t\tmarkerPaths.push(markerPath);\n\t\t\tpruneContextStoreRoot(root, options);\n\t\t} catch {\n\t\t\t// Retention is best-effort; the caller can still use its normal store path.\n\t\t}\n\t}\n\tlet released = false;\n\treturn {\n\t\trelease(): void {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tfor (const markerPath of markerPaths) {\n\t\t\t\ttry {\n\t\t\t\t\tunlinkSync(markerPath);\n\t\t\t\t\trmdirSync(dirname(markerPath));\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t},\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-gc.d.ts","sourceRoot":"","sources":["../../src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,EAAE,MAAM,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,iBAAiB,GAAG,mBAAmB,GAAG,uBAAuB,CAAC;IAC1E,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;yCAEqC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,qBAAqB,EAAE,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,MAAM,EAAE,eAAe,CAAC;CACxB;AAuBD,eAAO,MAAM,2BAA2B,EAAE,2BA6BzC,CAAC;AA6CF,wBAAgB,oBAAoB,CAAC,QAAQ,CAAC,EAAE,iBAAiB,GAAG,2BAA2B,CAE9F;AAwND,wBAAgB,cAAc,CAC7B,QAAQ,EAAE,YAAY,EAAE,EACxB,WAAW,EAAE,iBAAiB,GAAG;IAChC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CAClC,GACC,eAAe,CAkHjB","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { estimateTokens } from \"@caupulican/pi-agent-core/node\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai\";\nimport { normalizePath } from \"../utils/paths.ts\";\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean;\n\t/** Number of newest Automata/Mind injected pages to preserve verbatim. */\n\tpreserveRecentPages?: number;\n\t/** Minimum provider-visible text chars before a stale semantic memory page is packed. */\n\tminChars?: number;\n\t/** Markers that identify deterministic Automata/Mind context pages. */\n\tmarkers?: string[];\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean;\n\t/** Number of most recent AgentMessage rows to preserve verbatim. */\n\tpreserveRecentMessages?: number;\n\t/** Minimum provider-visible text chars before a stale tool result is packed. */\n\tminToolResultChars?: number;\n\t/** Tool names eligible for stale result packing. */\n\ttools?: string[];\n\t/** Provider-context control for deterministic Automata/Mind semantic memory pages. */\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface NormalizedContextGcSettings extends Omit<Required<ContextGcSettings>, \"semanticMemory\"> {\n\tsemanticMemory: Required<SemanticMemoryGcSettings>;\n}\n\n/**\n * Brain-curation hooks (both optional; absent hooks are byte-for-byte today's behavior).\n * `resolveDigest` is a pure lookup keyed by the record's content hash — it must return the digest\n * already fenced in the untrusted-content boundary (e.g. BrainCurator.getDigest), with the fence's\n * nonce fixed once at store time, since GC re-renders the stub from raw messages on every request\n * and renders the returned string VERBATIM. `onPacked` lets the caller enqueue digest work with the\n * exact original text at the moment it is packed.\n */\nexport interface ContextGcCurationHooks {\n\tresolveDigest?: (digestKey: string) => string | undefined;\n\tonPacked?: (record: ContextGcPackedRecord, originalText: string) => void;\n}\n\nexport interface ContextGcOptions extends NormalizedContextGcSettings {\n\tcwd: string;\n\tstorageDir?: string;\n\twritePayloads?: boolean;\n\tcuration?: ContextGcCurationHooks;\n}\n\nexport interface ContextGcPackedRecord {\n\ttoolName: string;\n\ttoolCallId: string;\n\tmessageIndex: number;\n\treason: \"superseded-read\" | \"stale-tool-result\" | \"stale-semantic-memory\";\n\toriginalChars: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tstoragePath?: string;\n\tpath?: string;\n\tcommand?: string;\n\tkey?: string;\n\t/** Brain-curator semantic digest of the packed content (model-generated; advisory only). Arrives\n\t * already fenced in the untrusted-content boundary (see ContextGcCurationHooks.resolveDigest) —\n\t * render verbatim, never re-wrap. */\n\tdigest?: string;\n}\n\nexport interface ContextGcReport {\n\tenabled: boolean;\n\tpackedCount: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tsavedTokens: number;\n\trecords: ContextGcPackedRecord[];\n}\n\nexport interface ContextGcResult {\n\tmessages: AgentMessage[];\n\treport: ContextGcReport;\n}\n\nconst DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS: Required<SemanticMemoryGcSettings> = {\n\tenabled: true,\n\tpreserveRecentPages: 1,\n\tminChars: 900,\n\tmarkers: [\n\t\t// Generic memory-subsystem recall page marker (brand-free). Provider-specific markers are\n\t\t// merged in dynamically at runtime via MemoryManager.getContextMarkers().\n\t\t\"<memory_context\",\n\t\t// Pre-existing provider-specific markers (to be generalized to provider-declared markers).\n\t\t\"<automata_context\",\n\t\t\"<automata_response\",\n\t\t\"<automata_query\",\n\t\t\"<automata_fetch\",\n\t\t\"<memory_lifecycle_audit\",\n\t\t\"<memory_lifecycle_purge\",\n\t\t\"<automata_doctor\",\n\t\t\"<automata_optimizer\",\n\t\t\"<automata_mesh\",\n\t],\n};\n\nexport const DEFAULT_CONTEXT_GC_SETTINGS: NormalizedContextGcSettings = {\n\tenabled: true,\n\tpreserveRecentMessages: 8,\n\tminToolResultChars: 1200,\n\ttools: [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"rg\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"ls\",\n\t\t\"skill_open\",\n\t\t\"automata_graph_status\",\n\t\t\"automata_graph_search\",\n\t\t\"automata_graph_query\",\n\t\t\"automata_graph_neighbors\",\n\t\t\"automata_graph_path\",\n\t\t\"automata_graph_pointer_pack\",\n\t\t\"learning_query_memory\",\n\t\t\"subagent\",\n\t\t\"delegate\",\n\t\t\"task_steps\",\n\t\t\"task_background\",\n\t\t\"task_goal\",\n\t\t\"run_ledger\",\n\t\t\"context_headroom_retrieve\",\n\t\t\"headroom_retrieve\",\n\t],\n\tsemanticMemory: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS,\n};\n\ntype ToolCallMeta = {\n\tid: string;\n\tname: string;\n\targs: Record<string, unknown>;\n\tmessageIndex: number;\n};\n\nfunction cap(text: string, limit = 220): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction normalizeSemanticMemoryGcSettings(settings?: SemanticMemoryGcSettings): Required<SemanticMemoryGcSettings> {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.enabled,\n\t\tpreserveRecentPages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentPages ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.preserveRecentPages),\n\t\t),\n\t\tminChars: Math.max(0, Math.floor(settings?.minChars ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.minChars)),\n\t\tmarkers:\n\t\t\tsettings?.markers && settings.markers.length > 0\n\t\t\t\t? settings.markers\n\t\t\t\t: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.markers,\n\t};\n}\n\nfunction normalizeContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_CONTEXT_GC_SETTINGS.enabled,\n\t\tpreserveRecentMessages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentMessages ?? DEFAULT_CONTEXT_GC_SETTINGS.preserveRecentMessages),\n\t\t),\n\t\tminToolResultChars: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.minToolResultChars ?? DEFAULT_CONTEXT_GC_SETTINGS.minToolResultChars),\n\t\t),\n\t\ttools: settings?.tools && settings.tools.length > 0 ? settings.tools : DEFAULT_CONTEXT_GC_SETTINGS.tools,\n\t\tsemanticMemory: normalizeSemanticMemoryGcSettings(settings?.semanticMemory),\n\t};\n}\n\nexport function getContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn normalizeContextGcSettings(settings);\n}\n\nfunction textContentParts(content: unknown): string[] | undefined {\n\tif (typeof content === \"string\") return [content];\n\tif (!Array.isArray(content)) return undefined;\n\tconst parts: string[] = [];\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null) return undefined;\n\t\tconst typed = part as { type?: string; text?: string; mimeType?: string };\n\t\tif (typed.type === \"text\" && typeof typed.text === \"string\") parts.push(typed.text);\n\t\telse if (typed.type === \"image\") return undefined;\n\t\telse return undefined;\n\t}\n\treturn parts;\n}\n\nfunction contentText(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content;\n\treturn textContentParts(content)?.join(\"\\n\");\n}\n\nfunction toolResultParts(message: ToolResultMessage): string[] {\n\tconst parts: string[] = [];\n\tfor (const part of message.content) {\n\t\tif (part.type === \"text\" && part.text) parts.push(part.text);\n\t\telse if (part.type === \"image\") parts.push(`[image ${part.mimeType}]`);\n\t}\n\treturn parts;\n}\n\nfunction toolResultText(message: ToolResultMessage): string {\n\treturn toolResultParts(message).join(\"\\n\");\n}\n\nfunction smallStringSlice(value: string, start?: number, end?: number): string {\n\tconst sliced = value.slice(start, end);\n\treturn sliced ? ` ${sliced}`.slice(1) : \"\";\n}\n\nfunction joinedPartsContainMarker(parts: string[], marker: string): boolean {\n\tif (marker.length === 0) return true;\n\tconst tailLength = marker.length - 1;\n\tlet tail = \"\";\n\tlet first = true;\n\tfor (const part of parts) {\n\t\tif (part.includes(marker)) return true;\n\t\tif (!first && `${tail}\\n${smallStringSlice(part, 0, tailLength)}`.includes(marker)) return true;\n\t\tif (tailLength === 0) tail = \"\";\n\t\telse if (part.length >= tailLength) tail = smallStringSlice(part, -tailLength);\n\t\telse tail = `${tail}${first ? \"\" : \"\\n\"}${part}`.slice(-tailLength);\n\t\tfirst = false;\n\t}\n\treturn false;\n}\n\nfunction joinedPartsContainAnyMarker(parts: string[], markers: readonly string[]): boolean {\n\treturn markers.some((marker) => joinedPartsContainMarker(parts, marker));\n}\n\nfunction isSemanticMemoryCustomMessage(message: AgentMessage): boolean {\n\tif (message.role !== \"custom\") return false;\n\tconst customType = String((message as { customType?: unknown }).customType ?? \"\").toLowerCase();\n\treturn customType.includes(\"automata\") || customType.includes(\"memory\") || customType.includes(\"mind\");\n}\n\nfunction agentMessageText(message: AgentMessage): string | undefined {\n\tif (message.role === \"toolResult\") return toolResultText(message);\n\tif (isSemanticMemoryCustomMessage(message)) return contentText((message as { content?: unknown }).content);\n\treturn undefined;\n}\n\nfunction semanticMessageHasMarker(message: AgentMessage, settings: Required<SemanticMemoryGcSettings>): boolean {\n\tif (message.role === \"toolResult\") return joinedPartsContainAnyMarker(toolResultParts(message), settings.markers);\n\tif (isSemanticMemoryCustomMessage(message)) {\n\t\tconst parts = textContentParts((message as { content?: unknown }).content);\n\t\treturn parts ? joinedPartsContainAnyMarker(parts, settings.markers) : false;\n\t}\n\treturn false;\n}\n\ninterface ContextGcPlan {\n\tcalls: Map<string, ToolCallMeta>;\n\tlatestReadByPath: Map<string, string>;\n\tsemanticIndexes: number[];\n}\n\nfunction normalizeToolPath(cwd: string, value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.trim() === \"\") return undefined;\n\tconst path = value.trim();\n\treturn normalizePath(isAbsolute(path) ? path : resolve(cwd, path));\n}\n\nfunction collectContextGcPlan(\n\tmessages: AgentMessage[],\n\tcwd: string,\n\tsemanticSettings: Required<SemanticMemoryGcSettings>,\n): ContextGcPlan {\n\tconst calls = new Map<string, ToolCallMeta>();\n\tconst readResultCallIds: string[] = [];\n\tconst semanticIndexes: number[] = [];\n\n\tfor (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n\t\tconst message = messages[messageIndex];\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\t\tcalls.set(part.id, {\n\t\t\t\t\tid: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\targs: part.arguments ?? {},\n\t\t\t\t\tmessageIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\" && message.toolName === \"read\") {\n\t\t\treadResultCallIds.push(message.toolCallId);\n\t\t}\n\n\t\tif (semanticSettings.enabled && semanticMessageHasMarker(message, semanticSettings)) {\n\t\t\tsemanticIndexes.push(messageIndex);\n\t\t}\n\t}\n\n\tconst latestReadByPath = new Map<string, string>();\n\tfor (const toolCallId of readResultCallIds) {\n\t\tconst call = calls.get(toolCallId);\n\t\tconst path = normalizeToolPath(cwd, call?.args.path);\n\t\tif (path) latestReadByPath.set(path, toolCallId);\n\t}\n\n\treturn { calls, latestReadByPath, semanticIndexes };\n}\n\nfunction storagePathFor(storageDir: string | undefined, key: string): string | undefined {\n\tif (!storageDir || !isAbsolute(storageDir)) return undefined;\n\treturn resolve(storageDir, `${key}.txt`);\n}\n\nfunction maybeStoreOriginal(options: ContextGcOptions, key: string, original: string): string | undefined {\n\tconst path = storagePathFor(options.storageDir, key);\n\tif (!path || !options.writePayloads) return path;\n\ttry {\n\t\tmkdirSync(options.storageDir!, { recursive: true });\n\t\tif (!existsSync(path)) writeFileSync(path, original, \"utf8\");\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn path;\n}\n\nfunction reasonText(record: ContextGcPackedRecord): string {\n\tif (record.reason === \"superseded-read\") return \"older read snapshot superseded by a later read of the same file\";\n\tif (record.reason === \"stale-semantic-memory\") {\n\t\treturn \"older Automata/Mind semantic context page outside the semantic-memory freshness window\";\n\t}\n\treturn \"stale bulky tool output outside the recent context window\";\n}\n\nfunction buildSummary(record: ContextGcPackedRecord): string {\n\tconst semantic = record.reason === \"stale-semantic-memory\";\n\tconst lines = [\n\t\tsemantic ? \"[Semantic GC packed stale Automata/Mind context page]\" : \"[Context GC packed stale tool result]\",\n\t\tsemantic ? undefined : `tool: ${record.toolName}`,\n\t\trecord.path ? `path: ${record.path}` : undefined,\n\t\trecord.command ? `command: ${cap(record.command)}` : undefined,\n\t\t`reason: ${reasonText(record)}`,\n\t\t`original: ${record.originalChars} chars (~${record.originalTokens} tokens)`,\n\t\t// The digest arrives PRE-FENCED from the curator (brain-curator.ts wraps it once, in the\n\t\t// standard untrusted-content boundary — the same treatment memory recall pages get — at the\n\t\t// moment it is stored, not here). Render it VERBATIM: re-wrapping on every GC render would\n\t\t// regenerate the fence's nonce each time, making the packed stub byte-different on every\n\t\t// provider request and busting prompt caching (BUG E).\n\t\trecord.digest ? `summary (auto-digest, machine paraphrase, not authoritative): ${record.digest}` : undefined,\n\t\trecord.storagePath\n\t\t\t? `exact old provider-visible text stored at: ${record.storagePath}`\n\t\t\t: \"exact old provider-visible text retained in the session log, not inline in provider context\",\n\t\tsemantic\n\t\t\t? \"If this memory context matters, query Automata/Mind again with the same topic/filter or fetch the drawer pointers from the stored page.\"\n\t\t\t: record.path\n\t\t\t\t? \"For current file contents, use the read tool on the path above. For the exact old output, read the stored payload path if present.\"\n\t\t\t\t: \"If this exact old output matters, retrieve/read the stored payload path if present or rerun the tool command.\",\n\t\t\"Do not rely on this summary as the original content.\",\n\t].filter((line): line is string => line !== undefined);\n\treturn lines.join(\"\\n\");\n}\n\nfunction gcDetails(message: { details?: unknown }, record: ContextGcPackedRecord): Record<string, unknown> {\n\treturn {\n\t\t...(typeof message.details === \"object\" && message.details !== null ? message.details : {}),\n\t\tcontextGc: {\n\t\t\tpacked: true,\n\t\t\toriginalChars: record.originalChars,\n\t\t\toriginalTokens: record.originalTokens,\n\t\t\tstoragePath: record.storagePath,\n\t\t\treason: record.reason,\n\t\t},\n\t};\n}\n\nfunction makePackedToolResult(message: ToolResultMessage, record: ContextGcPackedRecord): ToolResultMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...message,\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message, record),\n\t};\n}\n\nfunction makePackedSemanticMemoryMessage(message: AgentMessage, record: ContextGcPackedRecord): AgentMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...(message as unknown as Record<string, unknown>),\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message as { details?: unknown }, record),\n\t} as AgentMessage;\n}\n\nexport function applyContextGc(\n\tmessages: AgentMessage[],\n\trawSettings: ContextGcSettings & {\n\t\tcwd?: string;\n\t\tstorageDir?: string;\n\t\twritePayloads?: boolean;\n\t\tcuration?: ContextGcCurationHooks;\n\t},\n): ContextGcResult {\n\tconst settings = normalizeContextGcSettings(rawSettings);\n\tconst baseReport: ContextGcReport = {\n\t\tenabled: settings.enabled,\n\t\tpackedCount: 0,\n\t\toriginalTokens: 0,\n\t\tpackedTokens: 0,\n\t\tsavedTokens: 0,\n\t\trecords: [],\n\t};\n\tif (!settings.enabled) return { messages, report: baseReport };\n\n\tconst options: ContextGcOptions = {\n\t\t...settings,\n\t\tcwd: rawSettings.cwd ?? process.cwd(),\n\t\tstorageDir: rawSettings.storageDir,\n\t\twritePayloads: rawSettings.writePayloads ?? true,\n\t\tcuration: rawSettings.curation,\n\t};\n\tconst eligibleTools = new Set(options.tools);\n\tconst plan = collectContextGcPlan(messages, options.cwd, options.semanticMemory);\n\tconst recentStart = Math.max(0, messages.length - options.preserveRecentMessages);\n\tconst semanticIndexSet = new Set(plan.semanticIndexes);\n\tconst preservedSemanticIndexes = new Set(\n\t\toptions.semanticMemory.preserveRecentPages > 0\n\t\t\t? plan.semanticIndexes.slice(-options.semanticMemory.preserveRecentPages)\n\t\t\t: [],\n\t);\n\tconst nextMessages = messages.slice();\n\tlet changed = false;\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (semanticIndexSet.has(index) && !preservedSemanticIndexes.has(index) && index < recentStart) {\n\t\t\tconst originalText = agentMessageText(message);\n\t\t\tif (originalText && originalText.length >= options.semanticMemory.minChars) {\n\t\t\t\tconst originalTokens = estimateTokens(message);\n\t\t\t\tconst key = createHash(\"sha256\")\n\t\t\t\t\t.update(`semantic-memory\\0${index}\\0${originalText}`)\n\t\t\t\t\t.digest(\"hex\")\n\t\t\t\t\t.slice(0, 24);\n\t\t\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\t\t\tconst record: ContextGcPackedRecord = {\n\t\t\t\t\ttoolName: \"automata-mind\",\n\t\t\t\t\ttoolCallId: `semantic-${index}`,\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\treason: \"stale-semantic-memory\",\n\t\t\t\t\toriginalChars: originalText.length,\n\t\t\t\t\toriginalTokens,\n\t\t\t\t\tpackedTokens: 0,\n\t\t\t\t\tstoragePath,\n\t\t\t\t\tkey,\n\t\t\t\t};\n\t\t\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\t\t\toptions.curation?.onPacked?.(record, originalText);\n\t\t\t\tconst packed = makePackedSemanticMemoryMessage(message, record);\n\t\t\t\trecord.packedTokens = estimateTokens(packed);\n\t\t\t\tnextMessages[index] = packed;\n\t\t\t\tbaseReport.records.push(record);\n\t\t\t\tbaseReport.originalTokens += record.originalTokens;\n\t\t\t\tbaseReport.packedTokens += record.packedTokens;\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tif (!eligibleTools.has(message.toolName)) continue;\n\t\tif (index >= recentStart) continue;\n\n\t\tconst originalText = toolResultText(message);\n\t\tif (originalText.length < options.minToolResultChars) continue;\n\n\t\tconst call = plan.calls.get(message.toolCallId);\n\t\tconst path = normalizeToolPath(options.cwd, call?.args.path);\n\t\tlet reason: ContextGcPackedRecord[\"reason\"] = \"stale-tool-result\";\n\t\tif (message.toolName === \"read\" && path) {\n\t\t\tif (plan.latestReadByPath.get(path) === message.toolCallId) continue;\n\t\t\treason = \"superseded-read\";\n\t\t}\n\n\t\tconst originalTokens = estimateTokens(message);\n\t\tconst key = createHash(\"sha256\")\n\t\t\t.update(`${message.toolName}\\0${message.toolCallId}\\0${originalText}`)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\tconst record: ContextGcPackedRecord = {\n\t\t\ttoolName: message.toolName,\n\t\t\ttoolCallId: message.toolCallId,\n\t\t\tmessageIndex: index,\n\t\t\treason,\n\t\t\toriginalChars: originalText.length,\n\t\t\toriginalTokens,\n\t\t\tpackedTokens: 0,\n\t\t\tstoragePath,\n\t\t\tpath,\n\t\t\tcommand: typeof call?.args.command === \"string\" ? call.args.command : undefined,\n\t\t\tkey,\n\t\t};\n\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\toptions.curation?.onPacked?.(record, originalText);\n\t\tconst packed = makePackedToolResult(message, record);\n\t\trecord.packedTokens = estimateTokens(packed);\n\t\tnextMessages[index] = packed as AgentMessage;\n\t\tbaseReport.records.push(record);\n\t\tbaseReport.originalTokens += record.originalTokens;\n\t\tbaseReport.packedTokens += record.packedTokens;\n\t\tchanged = true;\n\t}\n\n\tbaseReport.packedCount = baseReport.records.length;\n\tbaseReport.savedTokens = Math.max(0, baseReport.originalTokens - baseReport.packedTokens);\n\treturn { messages: changed ? nextMessages : messages, report: baseReport };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-gc.d.ts","sourceRoot":"","sources":["../../src/core/context-gc.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAK9D,MAAM,WAAW,wBAAwB;IACxC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,yFAAyF;IACzF,QAA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AAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;yCAEqC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC/B,OAAO,EAAE,OAAO,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,qBAAqB,EAAE,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,MAAM,EAAE,eAAe,CAAC;CACxB;AAuBD,eAAO,MAAM,2BAA2B,EAAE,2BA8BzC,CAAC;AA6CF,wBAAgB,oBAAoB,CAAC,QAAQ,CAAC,EAAE,iBAAiB,GAAG,2BAA2B,CAE9F;AA+ND,wBAAgB,cAAc,CAC7B,QAAQ,EAAE,YAAY,EAAE,EACxB,WAAW,EAAE,iBAAiB,GAAG;IAChC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CAClC,GACC,eAAe,CAyHjB","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, resolve } from \"node:path\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { estimateTokens } from \"@caupulican/pi-agent-core/node\";\nimport type { ToolResultMessage } from \"@caupulican/pi-ai\";\nimport { normalizePath } from \"../utils/paths.ts\";\n\nexport interface SemanticMemoryGcSettings {\n\tenabled?: boolean;\n\t/** Number of newest Automata/Mind injected pages to preserve verbatim. */\n\tpreserveRecentPages?: number;\n\t/** Minimum provider-visible text chars before a stale semantic memory page is packed. */\n\tminChars?: number;\n\t/** Markers that identify deterministic Automata/Mind context pages. */\n\tmarkers?: string[];\n}\n\nexport interface ContextGcSettings {\n\tenabled?: boolean;\n\t/** Number of most recent AgentMessage rows to preserve verbatim. */\n\tpreserveRecentMessages?: number;\n\t/** Minimum provider-visible text chars before a stale tool result is packed. */\n\tminToolResultChars?: number;\n\t/** Tool names eligible for stale result packing. */\n\ttools?: string[];\n\t/** Provider-context control for deterministic Automata/Mind semantic memory pages. */\n\tsemanticMemory?: SemanticMemoryGcSettings;\n}\n\nexport interface NormalizedContextGcSettings extends Omit<Required<ContextGcSettings>, \"semanticMemory\"> {\n\tsemanticMemory: Required<SemanticMemoryGcSettings>;\n}\n\n/**\n * Brain-curation hooks (both optional; absent hooks are byte-for-byte today's behavior).\n * `resolveDigest` is a pure lookup keyed by the record's content hash — it must return the digest\n * already fenced in the untrusted-content boundary (e.g. BrainCurator.getDigest), with the fence's\n * nonce fixed once at store time, since GC re-renders the stub from raw messages on every request\n * and renders the returned string VERBATIM. `onPacked` lets the caller enqueue digest work with the\n * exact original text at the moment it is packed.\n */\nexport interface ContextGcCurationHooks {\n\tresolveDigest?: (digestKey: string) => string | undefined;\n\tonPacked?: (record: ContextGcPackedRecord, originalText: string) => void;\n}\n\nexport interface ContextGcOptions extends NormalizedContextGcSettings {\n\tcwd: string;\n\tstorageDir?: string;\n\twritePayloads?: boolean;\n\tcuration?: ContextGcCurationHooks;\n}\n\nexport interface ContextGcPackedRecord {\n\ttoolName: string;\n\ttoolCallId: string;\n\tmessageIndex: number;\n\treason: \"superseded-read\" | \"stale-tool-result\" | \"stale-semantic-memory\";\n\toriginalChars: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tstoragePath?: string;\n\tpath?: string;\n\tcommand?: string;\n\tkey?: string;\n\t/** Brain-curator semantic digest of the packed content (model-generated; advisory only). Arrives\n\t * already fenced in the untrusted-content boundary (see ContextGcCurationHooks.resolveDigest) —\n\t * render verbatim, never re-wrap. */\n\tdigest?: string;\n}\n\nexport interface ContextGcReport {\n\tenabled: boolean;\n\tpackedCount: number;\n\toriginalTokens: number;\n\tpackedTokens: number;\n\tsavedTokens: number;\n\trecords: ContextGcPackedRecord[];\n}\n\nexport interface ContextGcResult {\n\tmessages: AgentMessage[];\n\treport: ContextGcReport;\n}\n\nconst DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS: Required<SemanticMemoryGcSettings> = {\n\tenabled: true,\n\tpreserveRecentPages: 1,\n\tminChars: 900,\n\tmarkers: [\n\t\t// Generic memory-subsystem recall page marker (brand-free). Provider-specific markers are\n\t\t// merged in dynamically at runtime via MemoryManager.getContextMarkers().\n\t\t\"<memory_context\",\n\t\t// Pre-existing provider-specific markers (to be generalized to provider-declared markers).\n\t\t\"<automata_context\",\n\t\t\"<automata_response\",\n\t\t\"<automata_query\",\n\t\t\"<automata_fetch\",\n\t\t\"<memory_lifecycle_audit\",\n\t\t\"<memory_lifecycle_purge\",\n\t\t\"<automata_doctor\",\n\t\t\"<automata_optimizer\",\n\t\t\"<automata_mesh\",\n\t],\n};\n\nexport const DEFAULT_CONTEXT_GC_SETTINGS: NormalizedContextGcSettings = {\n\tenabled: true,\n\tpreserveRecentMessages: 8,\n\tminToolResultChars: 1200,\n\ttools: [\n\t\t\"read\",\n\t\t\"bash\",\n\t\t\"rg\",\n\t\t\"grep\",\n\t\t\"find\",\n\t\t\"run_toolkit_script\",\n\t\t\"ls\",\n\t\t\"skill_open\",\n\t\t\"automata_graph_status\",\n\t\t\"automata_graph_search\",\n\t\t\"automata_graph_query\",\n\t\t\"automata_graph_neighbors\",\n\t\t\"automata_graph_path\",\n\t\t\"automata_graph_pointer_pack\",\n\t\t\"learning_query_memory\",\n\t\t\"subagent\",\n\t\t\"delegate\",\n\t\t\"task_steps\",\n\t\t\"task_background\",\n\t\t\"task_goal\",\n\t\t\"run_ledger\",\n\t\t\"context_headroom_retrieve\",\n\t\t\"headroom_retrieve\",\n\t],\n\tsemanticMemory: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS,\n};\n\ntype ToolCallMeta = {\n\tid: string;\n\tname: string;\n\targs: Record<string, unknown>;\n\tmessageIndex: number;\n};\n\nfunction cap(text: string, limit = 220): string {\n\tconst compact = text.replace(/\\s+/g, \" \").trim();\n\treturn compact.length > limit ? `${compact.slice(0, Math.max(0, limit - 1))}…` : compact;\n}\n\nfunction normalizeSemanticMemoryGcSettings(settings?: SemanticMemoryGcSettings): Required<SemanticMemoryGcSettings> {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.enabled,\n\t\tpreserveRecentPages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentPages ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.preserveRecentPages),\n\t\t),\n\t\tminChars: Math.max(0, Math.floor(settings?.minChars ?? DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.minChars)),\n\t\tmarkers:\n\t\t\tsettings?.markers && settings.markers.length > 0\n\t\t\t\t? settings.markers\n\t\t\t\t: DEFAULT_SEMANTIC_MEMORY_GC_SETTINGS.markers,\n\t};\n}\n\nfunction normalizeContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn {\n\t\tenabled: settings?.enabled ?? DEFAULT_CONTEXT_GC_SETTINGS.enabled,\n\t\tpreserveRecentMessages: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.preserveRecentMessages ?? DEFAULT_CONTEXT_GC_SETTINGS.preserveRecentMessages),\n\t\t),\n\t\tminToolResultChars: Math.max(\n\t\t\t0,\n\t\t\tMath.floor(settings?.minToolResultChars ?? DEFAULT_CONTEXT_GC_SETTINGS.minToolResultChars),\n\t\t),\n\t\ttools: settings?.tools && settings.tools.length > 0 ? settings.tools : DEFAULT_CONTEXT_GC_SETTINGS.tools,\n\t\tsemanticMemory: normalizeSemanticMemoryGcSettings(settings?.semanticMemory),\n\t};\n}\n\nexport function getContextGcSettings(settings?: ContextGcSettings): NormalizedContextGcSettings {\n\treturn normalizeContextGcSettings(settings);\n}\n\nfunction textContentParts(content: unknown): string[] | undefined {\n\tif (typeof content === \"string\") return [content];\n\tif (!Array.isArray(content)) return undefined;\n\tconst parts: string[] = [];\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null) return undefined;\n\t\tconst typed = part as { type?: string; text?: string; mimeType?: string };\n\t\tif (typed.type === \"text\" && typeof typed.text === \"string\") parts.push(typed.text);\n\t\telse if (typed.type === \"image\") return undefined;\n\t\telse return undefined;\n\t}\n\treturn parts;\n}\n\nfunction joinTextParts(parts: readonly string[]): string {\n\tif (parts.length === 0) return \"\";\n\tif (parts.length === 1) return parts[0];\n\treturn parts.join(\"\\n\");\n}\n\nfunction contentText(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content;\n\tconst parts = textContentParts(content);\n\treturn parts ? joinTextParts(parts) : undefined;\n}\n\nfunction toolResultParts(message: ToolResultMessage): string[] {\n\tconst parts: string[] = [];\n\tfor (const part of message.content) {\n\t\tif (part.type === \"text\" && part.text) parts.push(part.text);\n\t\telse if (part.type === \"image\") parts.push(`[image ${part.mimeType}]`);\n\t}\n\treturn parts;\n}\n\nfunction toolResultText(message: ToolResultMessage): string {\n\treturn joinTextParts(toolResultParts(message));\n}\n\nfunction smallStringSlice(value: string, start?: number, end?: number): string {\n\tconst sliced = value.slice(start, end);\n\treturn sliced ? ` ${sliced}`.slice(1) : \"\";\n}\n\nfunction joinedPartsContainMarker(parts: string[], marker: string): boolean {\n\tif (marker.length === 0) return true;\n\tconst tailLength = marker.length - 1;\n\tlet tail = \"\";\n\tlet first = true;\n\tfor (const part of parts) {\n\t\tif (part.includes(marker)) return true;\n\t\tif (!first && `${tail}\\n${smallStringSlice(part, 0, tailLength)}`.includes(marker)) return true;\n\t\tif (tailLength === 0) tail = \"\";\n\t\telse if (part.length >= tailLength) tail = smallStringSlice(part, -tailLength);\n\t\telse tail = `${tail}${first ? \"\" : \"\\n\"}${part}`.slice(-tailLength);\n\t\tfirst = false;\n\t}\n\treturn false;\n}\n\nfunction joinedPartsContainAnyMarker(parts: string[], markers: readonly string[]): boolean {\n\treturn markers.some((marker) => joinedPartsContainMarker(parts, marker));\n}\n\nfunction isSemanticMemoryCustomMessage(message: AgentMessage): boolean {\n\tif (message.role !== \"custom\") return false;\n\tconst customType = String((message as { customType?: unknown }).customType ?? \"\").toLowerCase();\n\treturn customType.includes(\"automata\") || customType.includes(\"memory\") || customType.includes(\"mind\");\n}\n\nfunction agentMessageText(message: AgentMessage): string | undefined {\n\tif (message.role === \"toolResult\") return toolResultText(message);\n\tif (isSemanticMemoryCustomMessage(message)) return contentText((message as { content?: unknown }).content);\n\treturn undefined;\n}\n\nfunction semanticMessageHasMarker(message: AgentMessage, settings: Required<SemanticMemoryGcSettings>): boolean {\n\tif (message.role === \"toolResult\") return joinedPartsContainAnyMarker(toolResultParts(message), settings.markers);\n\tif (isSemanticMemoryCustomMessage(message)) {\n\t\tconst parts = textContentParts((message as { content?: unknown }).content);\n\t\treturn parts ? joinedPartsContainAnyMarker(parts, settings.markers) : false;\n\t}\n\treturn false;\n}\n\ninterface ContextGcPlan {\n\tcalls: Map<string, ToolCallMeta>;\n\tlatestReadByPath: Map<string, string>;\n\tsemanticIndexes: number[];\n}\n\nfunction normalizeToolPath(cwd: string, value: unknown): string | undefined {\n\tif (typeof value !== \"string\" || value.trim() === \"\") return undefined;\n\tconst path = value.trim();\n\treturn normalizePath(isAbsolute(path) ? path : resolve(cwd, path));\n}\n\nfunction collectContextGcPlan(\n\tmessages: AgentMessage[],\n\tcwd: string,\n\tsemanticSettings: Required<SemanticMemoryGcSettings>,\n): ContextGcPlan {\n\tconst calls = new Map<string, ToolCallMeta>();\n\tconst readResultCallIds: string[] = [];\n\tconst semanticIndexes: number[] = [];\n\n\tfor (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {\n\t\tconst message = messages[messageIndex];\n\t\tif (message.role === \"assistant\") {\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"toolCall\") continue;\n\t\t\t\tcalls.set(part.id, {\n\t\t\t\t\tid: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\targs: part.arguments ?? {},\n\t\t\t\t\tmessageIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (message.role === \"toolResult\" && message.toolName === \"read\") {\n\t\t\treadResultCallIds.push(message.toolCallId);\n\t\t}\n\n\t\tif (semanticSettings.enabled && semanticMessageHasMarker(message, semanticSettings)) {\n\t\t\tsemanticIndexes.push(messageIndex);\n\t\t}\n\t}\n\n\tconst latestReadByPath = new Map<string, string>();\n\tfor (const toolCallId of readResultCallIds) {\n\t\tconst call = calls.get(toolCallId);\n\t\tconst path = normalizeToolPath(cwd, call?.args.path);\n\t\tif (path) latestReadByPath.set(path, toolCallId);\n\t}\n\n\treturn { calls, latestReadByPath, semanticIndexes };\n}\n\nfunction storagePathFor(storageDir: string | undefined, key: string): string | undefined {\n\tif (!storageDir || !isAbsolute(storageDir)) return undefined;\n\treturn resolve(storageDir, `${key}.txt`);\n}\n\nfunction maybeStoreOriginal(options: ContextGcOptions, key: string, original: string): string | undefined {\n\tconst path = storagePathFor(options.storageDir, key);\n\tif (!path || !options.writePayloads) return path;\n\ttry {\n\t\tmkdirSync(options.storageDir!, { recursive: true });\n\t\tif (!existsSync(path)) writeFileSync(path, original, \"utf8\");\n\t} catch {\n\t\treturn undefined;\n\t}\n\treturn path;\n}\n\nfunction reasonText(record: ContextGcPackedRecord): string {\n\tif (record.reason === \"superseded-read\") return \"older read snapshot superseded by a later read of the same file\";\n\tif (record.reason === \"stale-semantic-memory\") {\n\t\treturn \"older Automata/Mind semantic context page outside the semantic-memory freshness window\";\n\t}\n\treturn \"stale bulky tool output outside the recent context window\";\n}\n\nfunction buildSummary(record: ContextGcPackedRecord): string {\n\tconst semantic = record.reason === \"stale-semantic-memory\";\n\tconst lines = [\n\t\tsemantic ? \"[Semantic GC packed stale Automata/Mind context page]\" : \"[Context GC packed stale tool result]\",\n\t\tsemantic ? undefined : `tool: ${record.toolName}`,\n\t\trecord.path ? `path: ${record.path}` : undefined,\n\t\trecord.command ? `command: ${cap(record.command)}` : undefined,\n\t\t`reason: ${reasonText(record)}`,\n\t\t`original: ${record.originalChars} chars (~${record.originalTokens} tokens)`,\n\t\t// The digest arrives PRE-FENCED from the curator (brain-curator.ts wraps it once, in the\n\t\t// standard untrusted-content boundary — the same treatment memory recall pages get — at the\n\t\t// moment it is stored, not here). Render it VERBATIM: re-wrapping on every GC render would\n\t\t// regenerate the fence's nonce each time, making the packed stub byte-different on every\n\t\t// provider request and busting prompt caching (BUG E).\n\t\trecord.digest ? `summary (auto-digest, machine paraphrase, not authoritative): ${record.digest}` : undefined,\n\t\trecord.storagePath\n\t\t\t? `exact old provider-visible text stored at: ${record.storagePath}`\n\t\t\t: \"exact old provider-visible text retained in the session log, not inline in provider context\",\n\t\tsemantic\n\t\t\t? \"If this memory context matters, query Automata/Mind again with the same topic/filter or fetch the drawer pointers from the stored page.\"\n\t\t\t: record.path\n\t\t\t\t? \"For current file contents, use the read tool on the path above. For the exact old output, read the stored payload path if present.\"\n\t\t\t\t: \"If this exact old output matters, retrieve/read the stored payload path if present or rerun the tool command.\",\n\t\t\"Do not rely on this summary as the original content.\",\n\t].filter((line): line is string => line !== undefined);\n\treturn lines.join(\"\\n\");\n}\n\nfunction gcDetails(message: { details?: unknown }, record: ContextGcPackedRecord): Record<string, unknown> {\n\treturn {\n\t\t...(typeof message.details === \"object\" && message.details !== null ? message.details : {}),\n\t\tcontextGc: {\n\t\t\tpacked: true,\n\t\t\toriginalChars: record.originalChars,\n\t\t\toriginalTokens: record.originalTokens,\n\t\t\tstoragePath: record.storagePath,\n\t\t\treason: record.reason,\n\t\t},\n\t};\n}\n\nfunction makePackedToolResult(message: ToolResultMessage, record: ContextGcPackedRecord): ToolResultMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...message,\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message, record),\n\t};\n}\n\nfunction makePackedSemanticMemoryMessage(message: AgentMessage, record: ContextGcPackedRecord): AgentMessage {\n\tconst summary = buildSummary(record);\n\treturn {\n\t\t...(message as unknown as Record<string, unknown>),\n\t\tcontent: [{ type: \"text\", text: summary }],\n\t\tdetails: gcDetails(message as { details?: unknown }, record),\n\t} as AgentMessage;\n}\n\nexport function applyContextGc(\n\tmessages: AgentMessage[],\n\trawSettings: ContextGcSettings & {\n\t\tcwd?: string;\n\t\tstorageDir?: string;\n\t\twritePayloads?: boolean;\n\t\tcuration?: ContextGcCurationHooks;\n\t},\n): ContextGcResult {\n\tconst settings = normalizeContextGcSettings(rawSettings);\n\tconst baseReport: ContextGcReport = {\n\t\tenabled: settings.enabled,\n\t\tpackedCount: 0,\n\t\toriginalTokens: 0,\n\t\tpackedTokens: 0,\n\t\tsavedTokens: 0,\n\t\trecords: [],\n\t};\n\tif (!settings.enabled) return { messages, report: baseReport };\n\n\tconst options: ContextGcOptions = {\n\t\t...settings,\n\t\tcwd: rawSettings.cwd ?? process.cwd(),\n\t\tstorageDir: rawSettings.storageDir,\n\t\twritePayloads: rawSettings.writePayloads ?? true,\n\t\tcuration: rawSettings.curation,\n\t};\n\tconst eligibleTools = new Set(options.tools);\n\tconst plan = collectContextGcPlan(messages, options.cwd, options.semanticMemory);\n\tconst recentStart = Math.max(0, messages.length - options.preserveRecentMessages);\n\tconst semanticIndexSet = new Set(plan.semanticIndexes);\n\tconst preservedSemanticIndexes = new Set(\n\t\toptions.semanticMemory.preserveRecentPages > 0\n\t\t\t? plan.semanticIndexes.slice(-options.semanticMemory.preserveRecentPages)\n\t\t\t: [],\n\t);\n\tconst nextMessages = messages.slice();\n\tlet changed = false;\n\n\tfor (let index = 0; index < messages.length; index++) {\n\t\tconst message = messages[index];\n\t\tif (semanticIndexSet.has(index) && !preservedSemanticIndexes.has(index) && index < recentStart) {\n\t\t\tconst originalText = agentMessageText(message);\n\t\t\tif (originalText && originalText.length >= options.semanticMemory.minChars) {\n\t\t\t\tconst originalTokens = estimateTokens(message);\n\t\t\t\tconst key = createHash(\"sha256\")\n\t\t\t\t\t.update(\"semantic-memory\\0\")\n\t\t\t\t\t.update(String(index))\n\t\t\t\t\t.update(\"\\0\")\n\t\t\t\t\t.update(originalText)\n\t\t\t\t\t.digest(\"hex\")\n\t\t\t\t\t.slice(0, 24);\n\t\t\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\t\t\tconst record: ContextGcPackedRecord = {\n\t\t\t\t\ttoolName: \"automata-mind\",\n\t\t\t\t\ttoolCallId: `semantic-${index}`,\n\t\t\t\t\tmessageIndex: index,\n\t\t\t\t\treason: \"stale-semantic-memory\",\n\t\t\t\t\toriginalChars: originalText.length,\n\t\t\t\t\toriginalTokens,\n\t\t\t\t\tpackedTokens: 0,\n\t\t\t\t\tstoragePath,\n\t\t\t\t\tkey,\n\t\t\t\t};\n\t\t\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\t\t\toptions.curation?.onPacked?.(record, originalText);\n\t\t\t\tconst packed = makePackedSemanticMemoryMessage(message, record);\n\t\t\t\trecord.packedTokens = estimateTokens(packed);\n\t\t\t\tnextMessages[index] = packed;\n\t\t\t\tbaseReport.records.push(record);\n\t\t\t\tbaseReport.originalTokens += record.originalTokens;\n\t\t\t\tbaseReport.packedTokens += record.packedTokens;\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (message.role !== \"toolResult\") continue;\n\t\tif (!eligibleTools.has(message.toolName)) continue;\n\t\tif (index >= recentStart) continue;\n\n\t\tconst originalText = toolResultText(message);\n\t\tif (originalText.length < options.minToolResultChars) continue;\n\n\t\tconst call = plan.calls.get(message.toolCallId);\n\t\tconst path = normalizeToolPath(options.cwd, call?.args.path);\n\t\tlet reason: ContextGcPackedRecord[\"reason\"] = \"stale-tool-result\";\n\t\tif (message.toolName === \"read\" && path) {\n\t\t\tif (plan.latestReadByPath.get(path) === message.toolCallId) continue;\n\t\t\treason = \"superseded-read\";\n\t\t}\n\n\t\tconst originalTokens = estimateTokens(message);\n\t\tconst key = createHash(\"sha256\")\n\t\t\t.update(message.toolName)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(message.toolCallId)\n\t\t\t.update(\"\\0\")\n\t\t\t.update(originalText)\n\t\t\t.digest(\"hex\")\n\t\t\t.slice(0, 24);\n\t\tconst storagePath = maybeStoreOriginal(options, key, originalText);\n\t\tconst record: ContextGcPackedRecord = {\n\t\t\ttoolName: message.toolName,\n\t\t\ttoolCallId: message.toolCallId,\n\t\t\tmessageIndex: index,\n\t\t\treason,\n\t\t\toriginalChars: originalText.length,\n\t\t\toriginalTokens,\n\t\t\tpackedTokens: 0,\n\t\t\tstoragePath,\n\t\t\tpath,\n\t\t\tcommand: typeof call?.args.command === \"string\" ? call.args.command : undefined,\n\t\t\tkey,\n\t\t};\n\t\trecord.digest = options.curation?.resolveDigest?.(key);\n\t\toptions.curation?.onPacked?.(record, originalText);\n\t\tconst packed = makePackedToolResult(message, record);\n\t\trecord.packedTokens = estimateTokens(packed);\n\t\tnextMessages[index] = packed as AgentMessage;\n\t\tbaseReport.records.push(record);\n\t\tbaseReport.originalTokens += record.originalTokens;\n\t\tbaseReport.packedTokens += record.packedTokens;\n\t\tchanged = true;\n\t}\n\n\tbaseReport.packedCount = baseReport.records.length;\n\tbaseReport.savedTokens = Math.max(0, baseReport.originalTokens - baseReport.packedTokens);\n\treturn { messages: changed ? nextMessages : messages, report: baseReport };\n}\n"]}
|
package/dist/core/context-gc.js
CHANGED
|
@@ -33,6 +33,7 @@ export const DEFAULT_CONTEXT_GC_SETTINGS = {
|
|
|
33
33
|
"rg",
|
|
34
34
|
"grep",
|
|
35
35
|
"find",
|
|
36
|
+
"run_toolkit_script",
|
|
36
37
|
"ls",
|
|
37
38
|
"skill_open",
|
|
38
39
|
"automata_graph_status",
|
|
@@ -98,10 +99,18 @@ function textContentParts(content) {
|
|
|
98
99
|
}
|
|
99
100
|
return parts;
|
|
100
101
|
}
|
|
102
|
+
function joinTextParts(parts) {
|
|
103
|
+
if (parts.length === 0)
|
|
104
|
+
return "";
|
|
105
|
+
if (parts.length === 1)
|
|
106
|
+
return parts[0];
|
|
107
|
+
return parts.join("\n");
|
|
108
|
+
}
|
|
101
109
|
function contentText(content) {
|
|
102
110
|
if (typeof content === "string")
|
|
103
111
|
return content;
|
|
104
|
-
|
|
112
|
+
const parts = textContentParts(content);
|
|
113
|
+
return parts ? joinTextParts(parts) : undefined;
|
|
105
114
|
}
|
|
106
115
|
function toolResultParts(message) {
|
|
107
116
|
const parts = [];
|
|
@@ -114,7 +123,7 @@ function toolResultParts(message) {
|
|
|
114
123
|
return parts;
|
|
115
124
|
}
|
|
116
125
|
function toolResultText(message) {
|
|
117
|
-
return toolResultParts(message)
|
|
126
|
+
return joinTextParts(toolResultParts(message));
|
|
118
127
|
}
|
|
119
128
|
function smallStringSlice(value, start, end) {
|
|
120
129
|
const sliced = value.slice(start, end);
|
|
@@ -323,7 +332,10 @@ export function applyContextGc(messages, rawSettings) {
|
|
|
323
332
|
if (originalText && originalText.length >= options.semanticMemory.minChars) {
|
|
324
333
|
const originalTokens = estimateTokens(message);
|
|
325
334
|
const key = createHash("sha256")
|
|
326
|
-
.update(
|
|
335
|
+
.update("semantic-memory\0")
|
|
336
|
+
.update(String(index))
|
|
337
|
+
.update("\0")
|
|
338
|
+
.update(originalText)
|
|
327
339
|
.digest("hex")
|
|
328
340
|
.slice(0, 24);
|
|
329
341
|
const storagePath = maybeStoreOriginal(options, key, originalText);
|
|
@@ -369,7 +381,11 @@ export function applyContextGc(messages, rawSettings) {
|
|
|
369
381
|
}
|
|
370
382
|
const originalTokens = estimateTokens(message);
|
|
371
383
|
const key = createHash("sha256")
|
|
372
|
-
.update(
|
|
384
|
+
.update(message.toolName)
|
|
385
|
+
.update("\0")
|
|
386
|
+
.update(message.toolCallId)
|
|
387
|
+
.update("\0")
|
|
388
|
+
.update(originalText)
|
|
373
389
|
.digest("hex")
|
|
374
390
|
.slice(0, 24);
|
|
375
391
|
const storagePath = maybeStoreOriginal(options, key, originalText);
|