@x-otto/memory 0.0.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +161 -0
- package/dist/index.d.ts +1117 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +201 -0
- package/dist/index.js.map +1 -0
- package/package.json +36 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/memory-manager.ts","../src/persistent-memory.ts","../src/http-memory-store.ts","../src/overlay-memory-store.ts","../src/agents-discovery.ts","../src/auto-memory.ts","../src/token-estimator.ts","../src/prune.ts","../src/archive.ts","../src/defaults.ts","../src/prompts.ts","../src/operational-learning.ts","../src/memory-extractor.ts","../src/auto-extract.ts","../src/file-state-snapshot.ts"],"mappings":";;;;;AASA;;;;;KAAY,WAAA;AAAA,KAEA,WAAA;AAAA,UACK,YAAA;EACf,IAAA;EACA,QAAA;AAAA;AAAA,UAGe,WAAA;EACf,IAAA,CAAK,OAAA,EAAS,YAAA,KAAiB,OAAA,CAAQ,GAAA;EALvC;;AAIF;;;;;EASE,KAAA,CAAM,IAAA,UAAc,OAAA,WAAkB,OAAA;EACtC,KAAA,EAAO,OAAA,EAAS,YAAA,IAAgB,QAAA,GAAW,IAAA;AAAA;AAAA,UAG5B,WAAA;EACf,OAAA,EAAS,WAAA;EACT,OAAA,EAAS,WAAA;EACT,OAAA;EAfK;;;;;EAqBL,gBAAA;EAbsC;EAetC,cAAA;EACA,aAAA;EACA,iBAAA;AAAA;AAAA,UAGe,WAAA;EACf,QAAA,EAAU,OAAA;EACV,WAAA;EACA,WAAA;EACA,OAAA;AAAA;AAAA,UAGe,gBAAA;EACf,OAAA;EACA,OAAA,EAAS,WAAA;EACT,UAAA,EAAY,WAAA;EAxBH;;;;;;;EAgCT,aAAA;EACA,aAAA;EAnB0B;;;;;EAyB1B,mBAAA;EAtBA;;;;AAIF;EAwBE,qBAAA;;;;;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otto/shared";import{normalizeEnvFraction as t}from"@x-otto/env";import{CONVERSATION_SUMMARY_PREFIX as n}from"@x-otto/ai";import{existsSync as r,statSync as i}from"node:fs";import{basename as a,dirname as o,extname as s,join as c,relative as l}from"node:path";import{readdir as u,stat as d}from"node:fs/promises";import{createPersistence as f,saveDocument as p}from"@x-otto/persistence";const m=`You are a conversation summarizer for an AI coding assistant. Your task is to create a structured summary of the conversation that preserves all information needed to continue the work.
|
|
2
|
+
|
|
3
|
+
Create the summary in the following format:
|
|
4
|
+
|
|
5
|
+
## Goal
|
|
6
|
+
[What is the user trying to accomplish?]
|
|
7
|
+
|
|
8
|
+
## Constraints & Preferences
|
|
9
|
+
- [Any constraints, preferences, or requirements the user mentioned]
|
|
10
|
+
|
|
11
|
+
## All User Requests
|
|
12
|
+
- [List EVERY distinct request/instruction the user made, in order, that is not a tool result. This is the authoritative record of user intent — quote the user's own wording; do not paraphrase away specifics.]
|
|
13
|
+
|
|
14
|
+
## Progress
|
|
15
|
+
### Done
|
|
16
|
+
- [x] [Completed work items]
|
|
17
|
+
### In Progress
|
|
18
|
+
- [ ] [Work in progress]
|
|
19
|
+
|
|
20
|
+
## Key Decisions
|
|
21
|
+
- **[Decision]**: [Brief rationale]
|
|
22
|
+
|
|
23
|
+
## Next Steps
|
|
24
|
+
1. [Planned next steps. For the immediate next action, include a VERBATIM quote of the most recent user message or your own last stated intent it derives from — anchors the task, prevents drift.]
|
|
25
|
+
|
|
26
|
+
## File Operations
|
|
27
|
+
### Read
|
|
28
|
+
- [Files that were read]
|
|
29
|
+
### Modified
|
|
30
|
+
- [Files that were modified]
|
|
31
|
+
|
|
32
|
+
## Critical Context
|
|
33
|
+
- [Any critical context needed to continue the work]
|
|
34
|
+
|
|
35
|
+
IMPORTANT:
|
|
36
|
+
- Preserve exact file paths, function names, error messages, and code snippets
|
|
37
|
+
- Keep technical details precise — do not generalize
|
|
38
|
+
- Include all tool call results that affect the current state
|
|
39
|
+
- Note any pending or failed operations`,h=`You are updating an existing conversation summary with new information. The existing summary and new messages are provided below.
|
|
40
|
+
|
|
41
|
+
Produce a single UPDATED summary that stays BOUNDED — a summary that grows without limit across rounds eventually gets hard-truncated by the output cap, silently losing whatever fell past the limit. Keep it tight by actively triaging, not by appending.
|
|
42
|
+
|
|
43
|
+
Keep (never drop):
|
|
44
|
+
- Every distinct user request/instruction (the "All User Requests" record is authoritative)
|
|
45
|
+
- Unfinished, in-progress, or blocked work
|
|
46
|
+
- Decisions not yet verified, and anything the user corrected you on
|
|
47
|
+
- Exact file paths, function names, error messages, code snippets still in play
|
|
48
|
+
|
|
49
|
+
Drop / compress (make room):
|
|
50
|
+
- Work that is both completed AND verified — collapse to a one-line outcome
|
|
51
|
+
- Superseded intermediate attempts and abandoned approaches
|
|
52
|
+
- Redundant restatements already captured elsewhere in the summary
|
|
53
|
+
|
|
54
|
+
Rules:
|
|
55
|
+
- Move completed "In Progress" items to "Done", then compress "Done" per the above
|
|
56
|
+
- Merge new work items, decisions, and context; do not simply append
|
|
57
|
+
- Keep the same structured format (including "All User Requests")
|
|
58
|
+
- If any information conflicts, use the newer version`,g=`You are summarizing the FIRST PART of an assistant turn that was split during conversation compaction. The remaining part of this turn is still in the conversation.
|
|
59
|
+
|
|
60
|
+
Create a brief summary in this format:
|
|
61
|
+
|
|
62
|
+
## Original Request
|
|
63
|
+
[What did the user ask for in this turn?]
|
|
64
|
+
|
|
65
|
+
## Early Progress
|
|
66
|
+
- [Key actions completed in the prefix portion]
|
|
67
|
+
|
|
68
|
+
## Context for Remaining Messages
|
|
69
|
+
- [Information needed to understand the remaining suffix messages]
|
|
70
|
+
|
|
71
|
+
Keep it concise — this will be prepended to the remaining messages of this turn.`,_=`## Goal
|
|
72
|
+
[What is the user trying to accomplish?]
|
|
73
|
+
|
|
74
|
+
## Constraints & Preferences
|
|
75
|
+
- [Any constraints, preferences, or requirements the user mentioned]
|
|
76
|
+
|
|
77
|
+
## All User Requests
|
|
78
|
+
- [List EVERY distinct request/instruction the user made, in order, that is not a tool result. This is the authoritative record of user intent — multi-round compaction must never let an earlier request silently drop. Quote the user's own wording for each; do not paraphrase away specifics.]
|
|
79
|
+
|
|
80
|
+
## Progress
|
|
81
|
+
### Done
|
|
82
|
+
- [x] [Completed work items]
|
|
83
|
+
### In Progress
|
|
84
|
+
- [ ] [Work in progress]
|
|
85
|
+
|
|
86
|
+
## Key Decisions
|
|
87
|
+
- **[Decision]**: [Brief rationale]
|
|
88
|
+
|
|
89
|
+
## Next Steps
|
|
90
|
+
1. [Planned next steps. For the immediate next action, include a VERBATIM quote of the most recent user message or your own last stated intent that it derives from — this anchors the task and prevents interpretation drift across compactions.]
|
|
91
|
+
|
|
92
|
+
## File Operations
|
|
93
|
+
### Read
|
|
94
|
+
- [Files that were read]
|
|
95
|
+
### Modified
|
|
96
|
+
- [Files that were modified]
|
|
97
|
+
|
|
98
|
+
## Critical Context
|
|
99
|
+
- [Any critical context needed to continue the work]`,v=`IMPORTANT:
|
|
100
|
+
- Preserve exact file paths, function names, error messages, and code snippets
|
|
101
|
+
- Keep technical details precise — do not generalize
|
|
102
|
+
- Include all tool call results that affect the current state
|
|
103
|
+
- Note any pending or failed operations`,y=`You are a conversation summarizer for an AI coding assistant. You are summarizing the EARLIER portion of a conversation. The most recent messages are NOT shown to you here — they are kept verbatim and will follow your summary unchanged.
|
|
104
|
+
|
|
105
|
+
Your summary and those preserved recent messages together become the assistant's full context going forward.
|
|
106
|
+
|
|
107
|
+
Create the summary in the following format:
|
|
108
|
+
|
|
109
|
+
${_}
|
|
110
|
+
|
|
111
|
+
## Context the Preserved Tail Depends On
|
|
112
|
+
- [Facts a reader MUST know to correctly understand the preserved recent messages that follow: decisions already made, file paths and their current state, conventions/constraints agreed earlier, mistakes already corrected, and any partially-done work the recent messages continue. This section is the whole point of this summary — be specific.]
|
|
113
|
+
|
|
114
|
+
${v}
|
|
115
|
+
- Do NOT re-summarize the preserved recent messages themselves — they are kept verbatim after your summary. Summarize only the EARLIER conversation and surface what the tail depends on.`,b=`You are summarizing ONE SEGMENT of a longer conversation for an AI coding assistant. This is a partial view — you are NOT seeing the whole conversation, and other segments are being summarized separately. Your segment summary will later be merged with the others.
|
|
116
|
+
|
|
117
|
+
Create a concise summary of THIS SEGMENT in the following format:
|
|
118
|
+
|
|
119
|
+
${_}
|
|
120
|
+
|
|
121
|
+
${v}
|
|
122
|
+
- Do NOT emit conclusions that require seeing the whole conversation (e.g. a single global "next step"). Report only what THIS segment establishes; the merge step will reconcile across segments.`,x=`You are merging several segment summaries of one conversation into a single coherent summary for an AI coding assistant. Each input below is a summary of a different (chronological) segment of the same conversation.
|
|
123
|
+
|
|
124
|
+
Reconcile them into one summary in the following format:
|
|
125
|
+
|
|
126
|
+
${_}
|
|
127
|
+
|
|
128
|
+
${v}
|
|
129
|
+
- Resolve conflicts in favour of the LATER segment.
|
|
130
|
+
- Merge duplicate items; do not simply concatenate.`;function S(e,t,n,r){let i=[];return r?.variant===`segment`?i.push(b):t?(i.push(h),i.push(`\n<existing_summary>\n${t}\n</existing_summary>`),r?.preservedCount&&r.preservedCount>0&&i.push(C(r.preservedCount))):r?.variant===`preserved-tail`?i.push(y):i.push(m),n&&i.push(`\n<additional_instructions>\n${n}\n</additional_instructions>`),i.push(`\n<conversation>\n${e}\n</conversation>`),i.join(`
|
|
131
|
+
`)}function C(e){return`\nNOTE: The ${e} most recent message(s) are kept verbatim and will follow your summary — do NOT re-summarize them; focus on the earlier conversation and what those recent messages depend on.`}function ee(e,t,n){let r=[x];return t&&r.push(`\n<existing_summary>\n${t}\n</existing_summary>`),n&&r.push(`\n<additional_instructions>\n${n}\n</additional_instructions>`),r.push(`\n<segment_summaries>\n${e}\n</segment_summaries>`),r.join(`
|
|
132
|
+
`)}function w(e){return`${g}\n\n<turn_prefix>\n${e}\n</turn_prefix>`}const te=8e3;function T(e){let t=0;for(let n of e)/[\u3000-\u9fff\uff00-\uffef]/.test(n)&&t++;return Math.ceil(t+(e.length-t)/4)}function ne(e,t){if(t<=0)return``;if(T(e)<=t)return e;let n=Array.from(e),r=0,i=n.length,a=``;for(;r<=i;){let e=Math.floor((r+i)/2),o=n.slice(0,e).join(``);T(o)<=t?(a=o,r=e+1):i=e-1}return a}function re(e,t=te){if(e.size===0)return``;let n=[`<agent_memory>`],r=0,i=0;for(let[a,o]of e){let e=o.trim();if(!e)continue;let s=t-r;if(s<=0){i++;continue}let c=T(e);if(c<=s)n.push(`# ${a}`),n.push(e),n.push(``),r+=c;else{let i=ne(e,s);n.push(`# ${a}`),n.push(i),n.push(`\n> ⚠ [truncated — content exceeded the memory injection budget (${t} tokens); remainder omitted]`),n.push(``),r=t}}return i>0&&(n.push(`> ⚠ [${i} additional memory source(s) omitted — total injection budget (${t} tokens) reached]`),n.push(``)),n.push(`</agent_memory>`),n.push(``),n.push(`<memory_guidelines>
|
|
133
|
+
When you learn something from this interaction that should be remembered, use the memory_record tool — never edit/write .otto state files directly (they are protected; see RFC-228). Choose scope:
|
|
134
|
+
- 'workspace' (default): durable structured facts portable across machines (preferences, gotchas, decisions).
|
|
135
|
+
- 'local': machine-specific facts that should never sync to other devices (local paths, installed plugins, environment quirks).
|
|
136
|
+
- 'project-shared': team-visible project conventions that belong in AGENTS.md (build/test commands, code style, architecture decisions all contributors should see).
|
|
137
|
+
|
|
138
|
+
**Should remember**:
|
|
139
|
+
- User-specified preferences and constraints
|
|
140
|
+
- Patterns learned from feedback (code style, architecture preferences)
|
|
141
|
+
- Key tool parameters (API endpoints, non-sensitive config)
|
|
142
|
+
- Project-specific build/test commands
|
|
143
|
+
|
|
144
|
+
**Should NOT remember**:
|
|
145
|
+
- Temporary task details
|
|
146
|
+
- One-off Q&A
|
|
147
|
+
- API keys, passwords, or sensitive information
|
|
148
|
+
- Casual conversation
|
|
149
|
+
</memory_guidelines>`),n.join(`
|
|
150
|
+
`)}const ie=`You are a learning extractor for an AI coding assistant. Read the conversation below and extract durable, cross-session "lessons" — operational knowledge that will help the assistant do better on FUTURE, unrelated sessions in this project.
|
|
151
|
+
|
|
152
|
+
A lesson captures a reusable cause→action:
|
|
153
|
+
- "trigger": the situation/context that should recall this lesson (when it applies)
|
|
154
|
+
- "insight": the actionable guidance learned (what to do)
|
|
155
|
+
- "tags": 1-5 lowercase keywords for retrieval
|
|
156
|
+
|
|
157
|
+
SAVE these (durable, reusable):
|
|
158
|
+
- A user correction that reveals a lasting preference ("user prefers X over Y")
|
|
159
|
+
- A non-obvious gotcha discovered the hard way ("running Z without flag W silently fails")
|
|
160
|
+
- A project-specific workflow or command that isn't written down elsewhere
|
|
161
|
+
- A constraint or convention the user insisted on
|
|
162
|
+
|
|
163
|
+
DO NOT save these (they pollute recall):
|
|
164
|
+
- Anything derivable from the repo, git history, or AGENTS.md/README — do not restate the obvious
|
|
165
|
+
- Ephemeral task state ("currently editing foo.ts") — lessons must outlive this session
|
|
166
|
+
- One-off Q&A, casual conversation, or a summary of what happened
|
|
167
|
+
- Secrets, API keys, passwords, tokens, or any sensitive value
|
|
168
|
+
|
|
169
|
+
Output ONLY a JSON array, nothing else. Each element: {"trigger": string, "insight": string, "tags": string[]}.
|
|
170
|
+
If there is nothing durable worth saving, output exactly: []`;function ae(e){return`${ie}\n\n<conversation>\n${e}\n</conversation>`}function oe(e,t){return`Earlier conversation history has been compacted into the summary below. If you need details the summary does not cover, call the memory_archive_read tool with archive id "${e}" to pull back the original messages.
|
|
171
|
+
|
|
172
|
+
<summary>
|
|
173
|
+
${t}
|
|
174
|
+
</summary>`}function se(e){return`[Low-fidelity summary — only about ${Math.max(0,Math.round(e*100))}% of the original history could be fed into summarization. Significant details are missing. Treat this summary as incomplete: if you need details it does not cover, call memory_archive_read with the archive id below to pull back the original messages, rather than guessing or asking the user to repeat themselves.]`}const E=e(`@x-otto/memory:persistent`),ce=[{path:`~/.otto/AGENTS.md`,writable:!0},{path:`./.otto/AGENTS.md`,writable:!0},{path:`./AGENTS.md`,writable:!1}];var le=class{memories=new Map;unwatch;constructor(e,t=ce){this.store=e,this.sources=t}async load(){this.memories=await this.store.load(this.sources),E.info(`Loaded ${this.memories.size} memory source(s)`)}async reload(){await this.load()}getInjection(){return re(this.memories)}getMemories(){return this.memories}async write(e,t){let n=this.sources.find(t=>t.path===e);if(!n)throw Error(`Unknown memory source: ${e}`);if(!n.writable)throw Error(`Memory source is read-only: ${e}`);await this.store.write(e,t),this.memories.set(e,t),E.info(`Memory source written: ${e}`)}watching(){this.unwatch||!this.store.watch||(this.unwatch=this.store.watch(this.sources,e=>{E.info(`Memory source changed: ${e}, reloading...`),this.reload()}))}stop(){this.unwatch?.(),this.unwatch=void 0}dispose(){this.stop(),this.memories.clear()}},ue=class{data=new Map;set(e,t){this.data.set(e,t)}async load(e){let t=new Map;for(let n of e){let e=this.data.get(n.path);e!==void 0&&t.set(n.path,e)}return t}async write(e,t){this.data.set(e,t)}},D=class{cwd;homeDirOverride;constructor(e=process.cwd(),t){this.cwd=e,this.homeDirOverride=t}async load(e){let{readFile:t}=await import(`node:fs/promises`),{resolve:n,isAbsolute:r}=await import(`node:path`),{homedir:i}=await import(`node:os`),a=new Map;for(let o of e){let e=this.resolvePath(o.path,n,r,i);try{let n=await t(e,`utf-8`);a.set(o.path,n)}catch{}}return a}async write(e,t){let{mkdir:n}=await import(`node:fs/promises`),{resolve:r,dirname:i,isAbsolute:a}=await import(`node:path`),{homedir:o}=await import(`node:os`),{atomicWriteFile:s}=await import(`@x-otto/persistence`),c=this.resolvePath(e,r,a,o);await n(i(c),{recursive:!0}),await s(c,t)}resolvePath(e,t,n,r){let i=this.homeDirOverride??r(),a=e.startsWith(`~/`)?e.replace(`~/`,`${i}/`):e;return n(a)?a:t(this.cwd,a)}};const de=e(`@x-otto/memory:token-estimator`);let O=null,k=null;async function fe(){if(!O){if(k){await k;return}k=(async()=>{try{let{getEncoding:e}=await import(`js-tiktoken`),t=e(`cl100k_base`);O={encode:e=>typeof e!=`string`||e.length===0?[]:t.encode(e)},de.info(`Tokenizer loaded: cl100k_base`)}catch(e){de.warn(`Failed to load js-tiktoken, falling back to heuristic: %s`,e.message),O=null}finally{k=null}})(),await k}}const pe=2e3;function me(e){return e>=33&&e<=47||e>=58&&e<=64||e>=91&&e<=96||e>=123&&e<=126}function he(e){return e>=12352&&e<=12543||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=63744&&e<=64255||e>=44032&&e<=55203||e>=65280&&e<=65519||e>=131072&&e<=191471}function A(e){let t=0,n=0,r=0;for(let i of e){let e=i.codePointAt(0)??0;he(e)?t+=1:me(e)?n+=1:r+=1}return Math.ceil(t*1+n*.5+r*.25)}function ge(e,t){let n=1;for(let r=1;r<e.length;r++)if(e.charCodeAt(r)===e.charCodeAt(r-1)){if(n++,n>=t)return!0}else n=1;return!1}function j(e){if(O){if(e.length>1e5||ge(e,64))return A(e);try{return O.encode(e).length}catch{return A(e)}}return k||fe().catch(()=>{}),A(e)}function _e(e){return e?e.length<=6?e:e.slice(-6):`?`}function M(e){return typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.map(e=>{switch(e.type){case`text`:return e.text;case`thinking`:return e.text;case`tool_call`:return`[call#${_e(e.id)} ${e.name}](${JSON.stringify(e.arguments)})`;case`image`:return`[image]`;default:return``}}).filter(Boolean).join(`
|
|
175
|
+
`):JSON.stringify(e)}const ve=new WeakMap;function N(e,t=j){let n=t===j&&O!==null&&typeof e==`object`&&!!e;if(n){let t=ve.get(e);if(t!==void 0)return t}let r;if(Array.isArray(e.content)){r=4;for(let n of e.content)switch(n.type){case`text`:case`thinking`:r+=t(n.text);break;case`tool_call`:r+=t(`${n.name}(${JSON.stringify(n.arguments)})`);break;case`image`:r+=pe;break;default:break}}else r=4+t(M(e));return n&&ve.set(e,r),r}function P(e,t=j){let n=0;for(let r of e)n+=N(r,t);return n}function ye(e){return e.role===`assistant`}function F(e,t=j){let n=-1,r=0;for(let t=e.length-1;t>=0;t--){let i=e[t];if(ye(i)&&i.usage){n=t,r=(i.usage.cacheReadTokens??0)+(i.usage.cacheWriteTokens??0)+i.usage.inputTokens+i.usage.outputTokens;break}}let i=0,a=0;if(n>=0){for(let r=0;r<=n;r++)a+=N(e[r],t);for(let r=n+1;r<e.length;r++)i+=N(e[r],t)}else i=P(e,t);let o=r+i,s=n>=0?Math.max(0,r-a):0,c=Math.max(0,o-s);return{total:o,fromUsage:r,fromEstimate:i,lastUsageIndex:n,derivedPrefix:s,bodyAfterPrefix:c}}const be=.1,I=16384,xe=t(process.env.OTTO_MEMORY_COMPACTION_HARD_CEILING_FRACTION,.9),Se=24e3,Ce=.6,we=.15,Te=2e4,Ee=2e3,De=`write`,Oe=`edit`,ke=`read`,Ae=`grep`,je=`find`,Me=`read_file`,Ne=`grep_search`,Pe=`file_search`,Fe=t(process.env.OTTO_MEMORY_COVERAGE_WARN_THRESHOLD,.7),Ie=t(process.env.OTTO_MEMORY_COVERAGE_ERROR_THRESHOLD,.5),Le=t(process.env.OTTO_MEMORY_COVERAGE_FLOOR_THRESHOLD,.3),Re=[De,Oe],L=[ke,Ae,je,Me,Ne,Pe,`bash`,`bash_output`,`web_search`,`web_fetch`];function R(e){return{compaction:{enabled:!0,trigger:[`headroom`,Math.min(I,e.maxOutput)+Se],keepRecent:[`fraction`,be],reserveTokens:Math.min(I,e.maxOutput)},prune:{trigger:[`fraction`,Ce],protect:[`fraction`,we],minimum:Te,regenerableTools:[...L],protectedTools:[],truncateTools:[...Re],truncateMaxLength:Ee}}}const z={enabled:!0,trigger:[`headroom`,I+Se],keepRecent:[`fraction`,be],reserveTokens:I},B={trigger:[`fraction`,Ce],protect:[`fraction`,we],minimum:Te,regenerableTools:[...L],protectedTools:[],truncateTools:[...Re],truncateMaxLength:Ee};function V(e,t){let[n,r]=e;switch(n){case`tokens`:return r;case`fraction`:return Math.floor(t*r);case`headroom`:{let e=Math.floor(t*.5);return Math.max(e,t-r)}}}const ze=e(`@x-otto/memory:prune`);function Be(e,t,n={},r=j,i={}){let a={...B,...n},o=V(a.trigger,t),s=P(e,r),c=i.currentTokens??s;if(!i.force&&c<o)return{messages:[...e],prunedCount:0,tokensSaved:0,changed:!1};let l=V(a.protect,t),u=new Set(a.truncateTools),d=new Set(a.regenerableTools),f=new Set(a.protectedTools),p=0,m=e.length;for(let t=e.length-1;t>=0;t--){let n=e[t],i=N(n,r);if(p+=i,p>=l){m=t+1;break}}let h=e.map((e,t)=>{if(t>=m)return e;if(e.role===`tool_result`){let t=e;return!d.has(t.toolName)||f.has(t.toolName)?e:Ve(t,r)}return e.role===`assistant`&&t<m?Ue(e,u,a.truncateMaxLength):e}),g=s-P(h,r);if(g<a.minimum)return ze.debug(`Prune skipped: savings ${g} < minimum ${a.minimum}`),{messages:[...e],prunedCount:0,tokensSaved:0,changed:!1};let _=h.filter((t,n)=>t!==e[n]).length;return ze.info(`Pruned ${_} messages, saved ~${g} tokens`),{messages:h,prunedCount:_,tokensSaved:g,changed:!0}}function Ve(e,t){let n=e.content.map(e=>e.type===`text`?e.text:``).join(``),r=t(n);if(r<100)return e;let i=n.split(`
|
|
176
|
+
`).find(e=>e.startsWith(`[tool result stored to `)),a=i?` ${i}`:``;return{...e,content:[{type:`text`,text:`[output pruned — ${r} tokens]${a}`}]}}function He(e,t){let n=typeof t.path==`string`?t.path:void 0;if(n===void 0)return null;if(e===`write`)return{path:n,content:`[content omitted by context pruning — ${(typeof t.content==`string`?t.content:``).length} chars. The file was already written to disk; read it if needed.]`};if(e===`edit`){let e=typeof t.oldContent==`string`?t.oldContent:``,r=typeof t.newContent==`string`?t.newContent:``;return{path:n,oldContent:`[omitted by context pruning — ${e.length} chars]`,newContent:`[omitted by context pruning — ${r.length} chars. The edit was already applied to the file on disk; read it if needed.]`}}return null}function Ue(e,t,n){if(!Array.isArray(e.content))return e;let r=!1,i=e.content.map(e=>{if(e.type!==`tool_call`||!t.has(e.name)||JSON.stringify(e.arguments).length<=n)return e;let i=He(e.name,e.arguments);return i===null?e:(r=!0,{...e,arguments:i})});return r?{...e,content:i}:e}const H=new Map;function We(e){return H.get(e)??0}function Ge(e,t){H.set(e,t)}function Ke(e){let t=H.get(e)??0;return t>0&&H.set(e,0),t}const U=e(`@x-otto/memory:compaction`);function qe(e){return e.role===`user`&&M(e).startsWith(n)}function Je(e){return e.startsWith(n)?e.slice(n.length).trimStart():e}const Ye=new Set([ke,Ae,je,Me,Ne,Pe]),Xe=new Set([De,Oe,`write_file`,`edit_file`,`replace_string_in_file`]);function Ze(e,t,n=j){let r=0,i=0;for(let a=e.length-1;a>=0;a--){let o=N(e[a],n);if(r+=o,r>=t){i=a+1;break}}i=Math.max(0,Math.min(i,e.length-1));let a=i;for(;a<e.length;){let t=e[a];if(t.role===`user`||t.role===`assistant`)break;a++}let o=!1,s=a;if(a>0&&a<e.length&&e[a].role===`assistant`){let t=a-1;for(;t>=0&&e[t].role===`tool_result`;)t--;t>=0&&e[t].role===`assistant`&&(o=!0,s=t)}return{firstKeptIndex:a,turnStartIndex:s,isSplitTurn:o}}function Qe(e,t,n={},r=j){let i=V({...z,...n}.trigger,t);return P(e,r)>=i*.5}function $e(e,t,n={},r,i=j,a){let o=V({...z,...n}.keepRecent,t),s=P(e,i);if(e.length<=2)return U.debug(`Too few messages to compact`),null;let c=Ze(e,a?.force===!0?Math.max(1,Math.min(o,Math.floor(s/2))):o,i);if(c.firstKeptIndex<=0)return U.debug(`Cut point at beginning, nothing to compact`),null;let l=e.slice(0,c.firstKeptIndex),u=e.slice(c.firstKeptIndex),d=l.filter(e=>!qe(e));if(d.length===0)return U.debug(`Compaction window only contains prior summaries, nothing new to summarize`),null;let f=r;if(!f){for(let e=l.length-1;e>=0;e--)if(qe(l[e])){f=Je(M(l[e]));break}}let p=[];c.isSplitTurn&&(p=e.slice(c.turnStartIndex,c.firstKeptIndex));let m=st(d);return{messagesToSummarize:[...d],turnPrefixMessages:p,preservedMessages:[...u],isSplitTurn:c.isSplitTurn,tokensBefore:s,previousSummary:f,fileOps:m}}function et(e,t,n){let r=[],i=[],a=0;for(let o of e){let e=N(o,n);i.length>0&&a+e>t&&(r.push(i),i=[],a=0),i.push(o),a+=e}return i.length>0&&r.push(i),r}function W(e,t){if(e.length<=t)return e;let n=e=>`\n\n…[${e} chars omitted to fit the summarization window]…\n\n`,r=Math.max(0,t-n(e.length).length),i=Math.floor(r/2);if(i<=0)return n(e.length).slice(0,t);let a=e.length-i*2;return`${e.slice(0,i)}${n(a)}${e.slice(-i)}`}function tt(e,t,n){if(n(e)<=t)return e;let r=0,i=e.length,a=``;for(;r<=i;){let o=Math.floor((r+i)/2),s=W(e,o);n(s)<=t?(a=s,r=o+1):i=o-1}return a}function nt(e){return e.role===`user`?0:e.role===`assistant`?1:e.role===`tool_result`?rt.has(e.toolName)?3:2:1}const rt=new Set(L);function it(e,t){let n=e.map(e=>({msg:e,prio:nt(e),text:G(e)})),r=n.reduce((e,t)=>e+t.text.length,0);if(r<=t)return{texts:n.map(e=>e.text),sourceChars:r,fedChars:r,truncated:!1};let i=!1,a=e=>n.filter(t=>t.prio===e),o=a(0),s=a(1),c=a(2),l=a(3),u=e=>e.reduce((e,t)=>e+t.text.length,0),d=[{msgs:l,share:.1},{msgs:c,share:.2},{msgs:s,share:.35}],f=t;for(let{msgs:e,share:n}of d){if(e.length===0)continue;let r=u(e),a=Math.floor(t*n),o=Math.min(r,a);at(e,o),o<r&&(i=!0),f-=u(e)}o.length>0&&u(o)>f&&(at(o,Math.max(0,f)),i=!0);let p=n.reduce((e,t)=>e+t.text.length,0);return{texts:n.map(e=>e.text),sourceChars:r,fedChars:p,truncated:i}}function at(e,t){if(e.length===0)return;let n=Math.max(0,Math.floor(t/e.length));for(let t of e)t.text.length>n&&(t.text=n<=0?``:W(t.text,n))}async function ot(e,t,n={},r,i=j,a){let o={...z,...n};U.info(`Compacting ${e.messagesToSummarize.length} messages`);let s=o.contextWindow==null?0:i(S(``,void 0,o.customInstructions,{variant:`segment`})),c=o.contextWindow==null?void 0:Math.max(1,Math.floor(o.contextWindow*.6)-s),l,u=1,d=c==null?[e.messagesToSummarize]:et(e.messagesToSummarize,c,i);if(d.length<=1){let n=e.messagesToSummarize.map(G).join(`
|
|
177
|
+
|
|
178
|
+
`),i=e.preservedMessages?.length??0;l=await t(S(n,e.previousSummary,o.customInstructions,{variant:i>0?`preserved-tail`:`full`,preservedCount:i}),{maxTokens:o.reserveTokens,signal:r}),U.info({batches:1,sourceChars:n.length,fedChars:n.length,coverage:1,truncated:!1},`[compaction] summarization coverage`)}else{let n=a??`__default__`,s=We(n),f=s>0?s:8;s>0&&Ke(n);let p=d.length<=f?d:[...d.slice(0,f-1),d.slice(f-1).flat()];U.info(`RFC-321 M6: summarization input exceeds window budget; map-reduce over ${p.length} batches`);let m=c*4,h=[],g=0,_=0,v=!1,y=[0,0,0,0],b=[0,0,0,0];for(let e of p){if(r?.aborted)break;let n=it(e,m),a=n.texts.join(`
|
|
179
|
+
|
|
180
|
+
`),s=a;s.length>m&&(s=W(s,m)),s=tt(s,c,i),g+=n.sourceChars,_+=Math.min(n.fedChars,s.length),(n.truncated||s.length<a.length)&&(v=!0),e.forEach((e,t)=>{let r=nt(e);y[r]=(y[r]??0)+G(e).length,b[r]=(b[r]??0)+(n.texts[t]?.length??0)});let l=S(s,void 0,o.customInstructions,{variant:`segment`});h.push(await t(l,{maxTokens:o.reserveTokens,signal:r}))}l=await t(ee(W(h.map((e,t)=>`### Segment ${t+1}\n\n${e}`).join(`
|
|
181
|
+
|
|
182
|
+
`),m),e.previousSummary,o.customInstructions),{maxTokens:o.reserveTokens,signal:r});let x=g>0?_/g:1;u=x,U.info({batches:p.length,sourceChars:g,fedChars:_,coverage:Number(x.toFixed(4)),truncated:v,byPriority:{p0:{src:y[0],fed:b[0]},p1:{src:y[1],fed:b[1]},p2:{src:y[2],fed:b[2]},p3:{src:y[3],fed:b[3]}}},`[compaction] summarization coverage`);let C=o.coverageWarnThreshold??Fe,w=Math.min(o.coverageErrorThreshold??Ie,C);x<w&&U.warn({coverage:Number(x.toFixed(4)),sourceChars:g,fedChars:_,batches:p.length,errorThreshold:w},`[compaction] low summarization coverage — large portion of history not represented in summary (RFC-321 C1)`),lt(x,p.length,a??`__default__`,w,C)}if(e.fileOps.read.length>0||e.fileOps.modified.length>0){let t=ct(e.fileOps);l.includes(`## File Operations`)||(l+=`\n\n${t}`)}if(e.isSplitTurn&&e.turnPrefixMessages.length>0){let n=await t(w(e.turnPrefixMessages.map(G).join(`
|
|
183
|
+
|
|
184
|
+
`)),{signal:r});l=`${l}\n\n---\n\n${n}`}return U.info(`Compaction complete: summary ${l.length} chars`),{summary:l,firstKeptIndex:e.messagesToSummarize.length,tokensBefore:e.tokensBefore,coverage:u}}function G(e){return`${e.role===`user`?`Human`:e.role===`assistant`?`Assistant`:e.role===`tool_result`?`Tool[result#${_e(e.toolCallId)} ${e.toolName}]${e.isError?`{error}`:``}`:`System`}: ${M(e)}`}function st(e){let t=new Set,n=new Set;for(let r of e){if(r.role!==`tool_result`)continue;let e=r.toolName,i=M(r).match(/(?:^|\s)(\/[^\s]+\.[a-z]+)/i);i?.[1]&&(Ye.has(e)?t.add(i[1]):Xe.has(e)&&n.add(i[1]))}return{read:[...t],modified:[...n]}}function ct(e){let t=[`## File Operations`];if(e.read.length>0){t.push(`### Read`);for(let n of e.read)t.push(`- ${n}`)}if(e.modified.length>0){t.push(`### Modified`);for(let n of e.modified)t.push(`- ${n}`)}return t.join(`
|
|
185
|
+
`)}function lt(e,t,n,r,i){e<r?Ge(n,Math.max(t*2,16)):e<i&&Ge(n,t+2)}const ut=e(`@x-otto/memory:archive`);var dt=class{type=`memory`;archives=new Map;sessionIndex=new Map;async archive(e,t,n){let r=Date.now(),i=`memory://archives/${e}/compaction-${r}.md`,a=K(t,n,r);this.archives.set(i,{content:a,entry:{path:i,timestamp:r,summary:n.slice(0,200),messageCount:t.length}});let o=this.sessionIndex.get(e)??[];return o.push(i),this.sessionIndex.set(e,o),ut.info(`Archived ${t.length} messages for session ${e}`),i}async read(e){let t=this.archives.get(e);if(!t)throw Error(`Archive not found: ${e}`);return t.content}async list(e){return(this.sessionIndex.get(e)??[]).map(e=>this.archives.get(e)?.entry).filter(e=>e!==void 0)}forgetSession(e){let t=this.sessionIndex.get(e);if(t){for(let e of t)this.archives.delete(e);this.sessionIndex.delete(e)}}};function K(e,t,n){let r=[`## Compacted at ${new Date(n).toISOString()}`,``,`### Summary`,t,``,`### Original Messages (${e.length} messages)`];for(let t of e){let e=t.role===`user`?`Human`:t.role===`assistant`?`Assistant`:t.role===`tool_result`?`Tool[${t.toolName}]`:`System`,n=M(t),i=n.length>2e3?`${n.slice(0,2e3)}\n...(truncated, ${n.length} chars total)`:n;r.push(`\n**${e}**: ${i}`)}return r.join(`
|
|
186
|
+
`)}function ft(e){if(e.role===`assistant`&&e.usage){let{usage:t,...n}=e;return n}return e}const q=e(`@x-otto/memory`);function J(e){return e?.trim()||`__default__`}var pt=class{persistent;archiveStorage;loadSessionEntries;messageFromEntry;summarize;estimateTokens;rawConfig;contextWindow;getContextWindow;compactionConfig;pruneConfig;maxContentBytes;getMaxContentBytes;getEstimatedBytes;previousSummaries=new Map;archiveIdCounter=new Map;compactionInFlight=new Set;constructor(e){let t=e.model?R(e.model):{compaction:z,prune:B};this.compactionConfig={...t.compaction,...e.compaction},this.pruneConfig={...t.prune,...e.prune},this.contextWindow=e.model?.contextWindow??2e5,this.getContextWindow=e.getContextWindow,this.maxContentBytes=e.maxContentBytes,this.getMaxContentBytes=e.getMaxContentBytes,this.getEstimatedBytes=e.getEstimatedBytes,this.rawConfig=e,this.archiveStorage=e.archiveStorage??new dt,this.loadSessionEntries=e.loadSessionEntries,this.messageFromEntry=e.messageFromEntry,this.summarize=e.summarize,this.estimateTokens=e.estimateTokens??j,this.persistent=new le(e.memoryStore??new D,e.sources)}clearSession(e){this.previousSummaries.delete(J(e))}forgetSession(e){this.previousSummaries.delete(J(e)),this.archiveIdCounter.delete(e),this.archiveStorage.forgetSession?.(e)}reconfigure(e){let t=R(e);this.contextWindow=e.contextWindow,this.compactionConfig={...t.compaction,...this.rawConfig.compaction},this.pruneConfig={...t.prune,...this.rawConfig.prune}}effectiveContextWindow(){return this.getContextWindow?.()??this.contextWindow}async ensureFitsWindow(e,t,n){if(!this.needsCompaction(e))return{messages:[...e],compacted:!1};let r=await this.process(e,t,n,{force:!0});return{messages:r.messages,compacted:r.compacted,summary:r.summary,replacement:r.replacement}}async loadMemory(){await this.persistent.load()}getMemoryPrompt(){return this.persistent.getInjection()}async reloadMemory(){await this.persistent.reload()}getMemories(){return this.persistent.getMemories()}needsPrune(e){return this.needsPruneWith(F(e,this.estimateTokens))}needsPruneWith(e){let t=V(this.pruneConfig.trigger,this.effectiveContextWindow());return e.bodyAfterPrefix>=t}prune(e,t=!1){return this.pruneWith(e,F(e,this.estimateTokens),t)}pruneWith(e,t,n){return Be(e,this.effectiveContextWindow(),this.pruneConfig,this.estimateTokens,{currentTokens:t.total,force:n})}needsCompaction(e){if(this.compactionConfig.enabled===!1)return!1;let t=this.effectiveContextWindow(),n=F(e,this.estimateTokens),r=V(this.compactionConfig.trigger,t),i=this.compactionConfig.hardCeilingFraction??xe,a=Math.max(r,Math.floor(t*i));return!!(n.bodyAfterPrefix>=r||n.total>=a||this.residencyPressure())}residencyPressure(){if(this.getEstimatedBytes==null)return!1;let e=this.getMaxContentBytes?.()??this.maxContentBytes;if(e==null)return!1;let t=this.getEstimatedBytes();return t!=null&&t>=e*.9}isEligibleForManualCompact(e){return Qe(e,this.effectiveContextWindow(),this.compactionConfig,this.estimateTokens)}prepareCompaction(e,t,n){return $e(e,this.effectiveContextWindow(),this.compactionConfig,this.previousSummaries.get(J(t)),this.estimateTokens,n)}async compact(e,t,n){let r=await ot(e,this.summarize,{...this.compactionConfig,contextWindow:this.effectiveContextWindow(),...(()=>{let e=this.rawConfig.getCoverageThresholds?.();return{...e?.warn===void 0?{}:{coverageWarnThreshold:e.warn},...e?.error===void 0?{}:{coverageErrorThreshold:e.error},...e?.floor===void 0?{}:{coverageFloorThreshold:e.floor}}})()},n,this.estimateTokens,t),i=Math.min(this.compactionConfig.coverageFloorThreshold??this.rawConfig.getCoverageThresholds?.()?.floor??Le,this.compactionConfig.coverageErrorThreshold??Ie);if(r.coverage<i&&(q.warn({sessionId:t,coverage:Number(r.coverage.toFixed(4)),floorThreshold:i},`[compaction] coverage below floor — boundary established WITH an explicit low-fidelity notice; a large portion of history is not represented in this summary (RFC-340 D1)`),r.summary=`${se(r.coverage)}\n\n${r.summary}`),t)try{await this.recordCompactionArchive(t,r,e.messagesToSummarize),q.info(`Compaction recorded at ${r.archivePath}`)}catch(e){q.warn({error:e},`Failed to record compaction archive`)}return this.previousSummaries.set(J(t),r.summary),r}async recordCompactionArchive(e,t,n){let r=(this.archiveIdCounter.get(e)??0)+1;this.archiveIdCounter.set(e,r),t.archivePath=`archive:${e}:${r}`,this.loadSessionEntries||await this.archiveStorage.archive(e,n,t.summary)}async process(e,t,r,i){let a=[...e],o=!1,s=!1,c,l,u,d,f=i?.force===!0,p=i?.skipPrune===!0,m=F(a,this.estimateTokens);if(!p&&(f||this.needsPruneWith(m))){let e=a.length,t=this.pruneWith(a,m,f);t.changed&&(a=t.messages,o=!0,d={prunedCount:t.prunedCount,tokensSaved:t.tokensSaved,messagesBefore:e,messagesAfter:a.length},q.info(`Prune: removed ${t.prunedCount} tool outputs, saved ~${t.tokensSaved} tokens`))}let h=this.compactionConfig.enabled!==!1;if(f?h:this.needsCompaction(a)){let e=J(t);if(this.compactionInFlight.has(e))q.info({sessionId:t},`Compaction already in flight for this session, skipping this round (will retry next round)`);else{this.compactionInFlight.add(e);try{let e=this.prepareCompaction(a,t,{force:f||this.residencyPressure()});if(e)try{let i=await this.compact(e,t,r);s=!0,c=i.summary,u=i.archivePath;let o={role:`user`,content:[{type:`text`,text:`${n}\n\n${u?oe(u,i.summary):i.summary}`}],timestamp:Date.now()};l=e.preservedMessages.map(ft),a=[o,...l],q.info(`Compaction: ${e.messagesToSummarize.length} messages → summary, kept ${e.preservedMessages.length}`)}catch(e){q.warn({error:e},`Compaction failed (LLM/summarizer error?), skipping compaction for this turn`)}}finally{this.compactionInFlight.delete(e)}}}return{messages:a,summary:c,replacement:l,archivePath:u,pruned:o,compacted:s,pruneMetrics:d}}async listArchives(e){if(this.loadSessionEntries&&this.messageFromEntry)try{return await this.listArchivesFromEntries(e)}catch(e){q.warn({error:e},`listArchives from session entries failed, falling back`)}return this.archiveStorage.list(e)}async listArchivesFromEntries(e){let t=await this.loadSessionEntries(e),n=this.messageFromEntry,r=[],i=0;for(let a=0;a<t.length;a++){let o=t[a];if(o.type!==`compaction`)continue;let s=o.data;i++;let c=0,l=0;for(let e=a-1;e>=0;e--){let r=t[e];if(r.type===`compaction`)break;let i=n(r);i&&(c++,l=i.timestamp??l)}r.push({path:`archive:${e}:${i}`,timestamp:l||o.seq||0,messageCount:s.compactedCount,summary:s.summary.slice(0,200)})}return r}async readArchive(e){if(this.loadSessionEntries&&this.messageFromEntry)try{let t=await this.readArchiveFromEntries(e);if(t)return t}catch(e){q.warn({error:e},`readArchive from session entries failed, falling back`)}return this.archiveStorage.read(e)}async readArchiveFromEntries(e){let t=e.match(/^archive:(.+):(\d+)$/);if(!t)return null;let n=t[1],r=parseInt(t[2],10),i=await this.loadSessionEntries(n),a=this.messageFromEntry,o=0,s=-1;for(let e=0;e<i.length;e++)if(i[e].type===`compaction`&&(o++,o===r)){s=e;break}if(s<0)return null;let c=i[s].data,l=-1;for(let e=s-1;e>=0;e--)if(i[e].type===`compaction`){l=e;break}let u=l+1,d=[];for(let e=u;e<s;e++){let t=a(i[e]);t&&d.push(t)}let f=Date.now();return K(d.filter(e=>e!==null),c.summary,f)}dispose(){this.persistent.dispose()}};function mt(e){return new pt(e)}var ht=class{baseUrl;userId;workspaceKeyGetter;isWorkspaceSyncEnabled;getAuth;fetchImpl;timeoutMs;local;onConflict;conflictCounters=new Map;knownVersions=new Map;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,``),this.userId=e.userId,this.workspaceKeyGetter=e.workspaceKey,this.isWorkspaceSyncEnabled=e.isWorkspaceSyncEnabled??(()=>!1),this.getAuth=e.getAuth,this.fetchImpl=e.fetch,this.timeoutMs=e.timeoutMs,this.local=new D(e.localDir,e.homeDirOverride),this.onConflict=e.onConflict}async load(e){let t=new Map,n=[];for(let r of e)if(this.userId&>(r.path)){let e=await this.loadRemoteUser(r.path);e===null?n.push(r):(t.set(r.path,e),this.local.write(r.path,e).catch(()=>{}))}else if(this.isWorkspaceSourceEnabled(r.path)){let e=await this.loadRemoteWorkspace(r.path);e===null?n.push(r):(t.set(r.path,e),this.local.write(r.path,e).catch(()=>{}))}else n.push(r);if(n.length>0){let e=await this.local.load(n);for(let[n,r]of e)t.set(n,r)}return t}async write(e,t){await this.local.write(e,t),this.userId&>(e)?this.writeRemoteUser(e,t).catch(()=>{}):this.isWorkspaceSourceEnabled(e)&&await this.writeRemoteWorkspace(e,t)}watch(e,t){return()=>{}}isWorkspaceSourceEnabled(e){return _t(e)&&this.isWorkspaceSyncEnabled()&&!!this.workspaceKeyGetter?.()}remoteKey(e){let t=e.startsWith(`~/.otto/`)?e.slice(8):e;return`user:${this.userId}:${t}`}remoteResourceId(e){let t=e.startsWith(`~/.otto/`)?e.slice(8):e;return encodeURIComponent(t)}workspaceResourceId(e){let t=e.startsWith(`./.otto/`)?e.slice(8):e;return encodeURIComponent(t)}async loadRemoteUser(e){try{let t={Authorization:`Bearer ${(await this.getAuth()).token}`,Accept:`application/json`,"X-Otto-User-Id":this.userId},n=new AbortController,r=setTimeout(()=>n.abort(),this.timeoutMs);try{let r=await this.fetchImpl(`${this.baseUrl}/memory/user/${this.remoteResourceId(e)}`,{method:`GET`,headers:t,signal:n.signal});if(r.ok){let e=await r.json();if(typeof e.content==`string`)return e.content}if(r.status===404){let r=await this.fetchImpl(`${this.baseUrl}/sessions/${encodeURIComponent(this.remoteKey(e))}`,{method:`GET`,headers:t,signal:n.signal});if(r.ok){let e=await r.json();if(typeof e.content==`string`)return e.content}}}finally{clearTimeout(r)}}catch{}return null}async writeRemoteUser(e,t){try{let n={Authorization:`Bearer ${(await this.getAuth()).token}`,"Content-Type":`application/json`,"X-Otto-User-Id":this.userId},r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);try{await this.fetchImpl(`${this.baseUrl}/memory/user/${this.remoteResourceId(e)}`,{method:`PUT`,headers:n,body:JSON.stringify({content:t}),signal:r.signal})}finally{clearTimeout(i)}}catch{}}async loadRemoteWorkspace(e){let t=this.workspaceKeyGetter?.();if(!t)return null;try{let n={Authorization:`Bearer ${(await this.getAuth()).token}`,Accept:`application/json`},r=new AbortController,i=setTimeout(()=>r.abort(),this.timeoutMs);try{let i=await this.fetchImpl(`${this.baseUrl}/memory/workspace/${encodeURIComponent(t)}/${this.workspaceResourceId(e)}`,{method:`GET`,headers:n,signal:r.signal});if(i.ok){let t=await i.json();if(typeof t.content==`string`)return typeof t.version==`number`&&this.knownVersions.set(e,t.version),t.content}}finally{clearTimeout(i)}}catch{}return null}async writeRemoteWorkspace(e,t){let n=this.workspaceKeyGetter?.();if(n)try{let r={Authorization:`Bearer ${(await this.getAuth()).token}`,"Content-Type":`application/json`},i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs),o=this.knownVersions.get(e)??0,s=o+1;try{let a=await this.fetchImpl(`${this.baseUrl}/memory/workspace/${encodeURIComponent(n)}/${this.workspaceResourceId(e)}`,{method:`PUT`,headers:r,body:JSON.stringify({content:t,version:s,expectedVersion:o}),signal:i.signal});if(a.status===409){await this.writeConflictSidecar(e,t);return}a.ok&&this.knownVersions.set(e,s)}finally{clearTimeout(a)}}catch{}}async writeConflictSidecar(e,t){let n=this.conflictCounters.get(e)??0,r=n%5;this.conflictCounters.set(e,n+1);let i=`${e}.conflict-${r}`;try{await this.local.write(i,t),this.onConflict?.(e,i)}catch{}}};function gt(e){return e===`~/.otto/AGENTS.md`||e===`~/.otto/MEMORY.md`||e.startsWith(`~/.otto/memory/`)}function _t(e){return e===`./.otto/MEMORY.md`||e.startsWith(`./.otto/memory/`)&&!e.startsWith(`./.otto/local/`)||e===`./.otto/lessons.json`}function vt(e){let t=new Map;return{async load(n){let r=n.filter(e=>!t.has(e.path)),i=r.length>0?await e.load(r):new Map;for(let e of n){let n=t.get(e.path);n!==void 0&&i.set(e.path,n)}return i},async write(e,n){t.set(e,n)}}}function yt(e,t={}){let n=t.fileName??`AGENTS.md`,a=t.rootMarkers??[`.git`],s=t.maxDepth??25,l=t.maxFiles??10,u=t.maxFileBytes??64*1024,d=[],f=e;for(let e=0;e<s;e++){let e=c(f,n);try{r(e)&&i(e).size<=u&&d.push(e)}catch{}let t=a.some(e=>r(c(f,e))),s=o(f);if(t||s===f)break;f=s}return d.reverse().slice(-l).map(e=>({path:e,writable:!1}))}const Y=e(`@x-otto/memory:auto`),X=`# MEMORY`,bt=/^- \[(.+?)\]\(memory\/(.+?)\.md\)/,Z=`./.otto/AGENTS.md`;function xt(e,t,n){return`<!-- otto-memory:start slug="${e}" -->\n## ${t.replace(/[\r\n]+/g,` `).trim()}\n\n${n.trim()}\n<!-- otto-memory:end slug="${e}" -->`}function St(e){return RegExp(`<!-- otto-memory:start slug="${e}" -->[\\s\\S]*?<!-- otto-memory:end slug="${e}" -->`)}var Ct=class{store;baseDir;localBaseDir;index=``;localIndex=``;loaded=!1;localLoaded=!1;constructor(e){this.store=e.store,this.baseDir=(e.baseDir??`./.otto`).replace(/\/+$/,``),this.localBaseDir=(e.localBaseDir??`${this.baseDir}/local`).replace(/\/+$/,``)}get indexPath(){return`${this.baseDir}/MEMORY.md`}entryPathOf(e){return`${this.baseDir}/memory/${e}.md`}get localIndexPath(){return`${this.localBaseDir}/MEMORY.md`}localEntryPathOf(e){return`${this.localBaseDir}/memory/${e}.md`}asSource(){return{path:this.indexPath,writable:!0}}asLocalSource(){return{path:this.localIndexPath,writable:!0}}async load(){this.index=(await this.store.load([this.asSource()])).get(this.indexPath)??``,this.loaded=!0}async loadLocal(){this.localIndex=(await this.store.load([this.asLocalSource()])).get(this.localIndexPath)??``,this.localLoaded=!0}getInjection(){let e=this.index.trim();return e?`${e}\n\n> Auto-memory entries live in the memory store (\`${this.baseDir}/memory/\`), not workspace files — read them with the memory_read tool; record new durable facts with memory_record.`:``}getLocalInjection(){let e=this.localIndex.trim();return e?`${e}\n\n> Machine-specific memory entries live in \`${this.localBaseDir}/memory/\` — never synced to other devices. Read with memory_read; record with memory_record (scope: 'local').`:``}async record(e,t=`workspace`){if(t===`local`){await this.recordLocal(e);return}if(t===`project-shared`){await this.recordProjectShared(e);return}await this.ensureLoaded();let n=this.resolveSlug(e.name,this.indexLines());await this.store.write(this.entryPathOf(n),`# ${e.name}\n\n${e.content}\n`);let r=`- [${e.name}](memory/${n}.md) — ${e.description}`,i=this.indexLines().filter(e=>!e.includes(`(memory/${n}.md)`));i.some(e=>e.startsWith(X))||i.unshift(X),i.push(r),this.index=`${i.join(`
|
|
187
|
+
`)}\n`,await this.store.write(this.indexPath,this.index),Y.info(`Auto-memory recorded: ${n}`)}async recordLocal(e){await this.ensureLocalLoaded();let t=this.resolveSlug(e.name,this.localIndexLines());await this.store.write(this.localEntryPathOf(t),`# ${e.name}\n\n${e.content}\n`);let n=`- [${e.name}](memory/${t}.md) — ${e.description}`,r=this.localIndexLines().filter(e=>!e.includes(`(memory/${t}.md)`));r.some(e=>e.startsWith(X))||r.unshift(X),r.push(n),this.localIndex=`${r.join(`
|
|
188
|
+
`)}\n`,await this.store.write(this.localIndexPath,this.localIndex),Y.info(`Auto-memory recorded (local scope): ${t}`)}async recordProjectShared(e){let t=(await this.store.load([{path:Z,writable:!0}])).get(Z)??``,n=e.name.replace(/[\r\n]+/g,` `).trim(),r=RegExp(`<!-- otto-memory:start slug="([^"]+)" -->\\n## ${wt(n)}\\n`).exec(t)?.[1]??Q(e.name),i=xt(r,e.name,e.content),a=St(r),o;o=a.test(t)?t.replace(a,i):t.trim()===``?`# 项目记忆(模型经 memory_record(scope: "project-shared") 写入,人工可编辑本文件任意内容)
|
|
189
|
+
\n${i}\n`:`${t.trimEnd()}\n\n${i}\n`,await this.store.write(Z,o),Y.info(`Auto-memory recorded (project-shared scope): ${r}`)}async read(e){await this.ensureLoaded();let t=this.slugByName(e,this.indexLines())??Q(e),n=this.entryPathOf(t),r=await this.readEntry(n);if(r!==null)return await this.withConflictLabel(n,r);await this.ensureLocalLoaded();let i=this.slugByName(e,this.localIndexLines())??Q(e),a=this.localEntryPathOf(i),o=await this.readEntry(a);return o===null?null:await this.withConflictLabel(a,o)}async withConflictLabel(e,t){for(let n=0;n<5;n++){let r=`${e}.conflict-${n}`;if(await this.readEntry(r)!==null)return`[CONFLICT] Concurrent edit detected for "${e}" — review "${r}" and reconcile manually.\n\n${t}`}return t}async readEntry(e){let t=(await this.store.load([{path:e,writable:!1}])).get(e);return t&&t.trim()!==``?t:null}async forget(e){await this.ensureLoaded(),await this.ensureLocalLoaded();let t=this.slugByName(e,this.indexLines())??Q(e);this.index=`${this.indexLines().filter(e=>!e.includes(`(memory/${t}.md)`)).join(`
|
|
190
|
+
`)}\n`,await this.store.write(this.indexPath,this.index),await this.store.write(this.entryPathOf(t),``);let n=this.slugByName(e,this.localIndexLines());n&&(this.localIndex=`${this.localIndexLines().filter(e=>!e.includes(`(memory/${n}.md)`)).join(`
|
|
191
|
+
`)}\n`,await this.store.write(this.localIndexPath,this.localIndex),await this.store.write(this.localEntryPathOf(n),``))}async ensureLoaded(){this.loaded||await this.load()}async ensureLocalLoaded(){this.localLoaded||await this.loadLocal()}indexLines(){return this.index.split(`
|
|
192
|
+
`).filter(e=>e.trim()!==``)}localIndexLines(){return this.localIndex.split(`
|
|
193
|
+
`).filter(e=>e.trim()!==``)}slugByName(e,t){for(let n of t){let t=bt.exec(n);if(t&&t[1]===e)return t[2]??null}return null}resolveSlug(e,t){let n=this.slugByName(e,t);if(n)return n;let r=new Map;for(let e of t){let t=bt.exec(e);t&&t[1]!==void 0&&t[2]!==void 0&&r.set(t[2],t[1])}let i=Q(e),a=i,o=2;for(;r.has(a)&&r.get(a)!==e;)a=`${i}-${o}`,o+=1;return a}};function Q(e){return e.toLowerCase().replace(/[^a-z0-9一-鿿]+/g,`-`).replace(/^-+|-+$/g,``)}function wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Tt=e(`@x-otto/memory:extractor`);async function Et(e,t,n,r={}){let i=Ot(e);if(!i.trim())return[];let a;try{a=await n(ae(i),{maxTokens:r.maxTokens??2048,signal:r.signal})}catch(e){return Tt.debug(`extraction LLM call failed (fail-closed → []): ${String(e)}`),[]}let o=kt(a);if(!o)return[];let s=r.maxLessons??5,c=[];for(let e of o){let n=At(e,t);if(n&&c.push(n),c.length>=s)break}return c}async function Dt(e,t,n={}){let r=[],i=0;for(let a of t){let{lesson:t,deduped:o}=await e.saveDeduped(a,n.similarityThreshold);o?i++:r.push(t)}return{saved:r,skippedSimilar:i}}function Ot(e){return e.map(e=>`${e.role===`user`?`Human`:e.role===`assistant`?`Assistant`:e.role===`tool_result`?`Tool[${e.toolName??`unknown`}]`:`System`}: ${M(e)}`).join(`
|
|
194
|
+
|
|
195
|
+
`)}function kt(e){let t=e.indexOf(`[`),n=e.lastIndexOf(`]`);if(t===-1||n===-1||n<t)return null;try{let r=JSON.parse(e.slice(t,n+1));return Array.isArray(r)?r:null}catch{return null}}function At(e,t){if(!e||typeof e!=`object`)return null;let n=typeof e.trigger==`string`?e.trigger.trim():``,r=typeof e.insight==`string`?e.insight.trim():``;if(!n||!r)return null;let i=Array.isArray(e.tags)?e.tags.filter(e=>typeof e==`string`&&e.trim().length>0).map(e=>e.trim().toLowerCase()).slice(0,5):[];return{trigger:n.slice(0,500),insight:r.slice(0,2e3),tags:i,sourceSessionId:t}}const jt=e(`@x-otto/memory:auto-extract`);function Mt(e){return e===`learn`||e===`memory_record`}function Nt(e,t){for(let n of e)if(n.role===`assistant`){for(let e of n.content)if(e.type===`tool_call`&&t(e.name))return!0}return!1}function Pt(e){let t=new Map,n=e.isMemoryWriteTool??Mt,r=()=>Math.max(1,e.config.everyNTurns??1);function i(e){let n=t.get(e);return n||(n={lastExtractedIndex:0,idleCount:0},t.set(e,n)),n}let a=(e=0,t=0,n)=>({ran:n===void 0,reason:n,saved:e,skippedSimilar:t});return{async onIdle(t,o,s){if(!e.config.enabled)return a(0,0,`disabled`);let c=i(t),l=o.slice(c.lastExtractedIndex);if(l.length===0)return a(0,0,`no-new-messages`);if(c.idleCount+=1,c.idleCount<r())return a(0,0,`throttled`);let u=()=>{c.lastExtractedIndex=o.length,c.idleCount=0};if(Nt(l,n))return u(),a(0,0,`main-agent-wrote`);try{let n=await Et(l,t,e.llm,{maxTokens:e.config.maxTokens,maxLessons:e.config.maxLessons,signal:s?.signal}),r=await Dt(e.store,n,{similarityThreshold:e.config.similarityThreshold});return u(),n.length>0&&jt.info({sessionId:t,extracted:n.length,saved:r.saved.length,deduped:r.skippedSimilar},`memory-auto-extract`),a(r.saved.length,r.skippedSimilar)}catch(e){return jt.warn(`auto-extract failed (fail-closed): ${String(e)}`),a(0,0,`error`)}},reset(e){t.delete(e)}}}const Ft=new Set([`node_modules`,`.git`,`dist`,`.next`,`.turbo`,`coverage`,`.cache`,`__pycache__`,`.vscode`]);var It=class{lastSnapshot=null;async capture(e){let[t,n]=await Promise.all([this.buildDirectoryTree(e.workspaceDir,0),this.checkRecentFiles(e.workspaceDir,e.recentFiles??[])]),r=[];n.length>0&&r.push(`${n.length} recently modified file(s) detected`);let i={timestamp:Date.now(),directoryTree:t,modifiedFiles:n,planStatus:e.planStatus,findings:r};return this.lastSnapshot=i,i}getLastSnapshot(){return this.lastSnapshot}formatSnapshot(e){let t=[`[File State Snapshot @ ${new Date(e.timestamp).toISOString()}]`];if(e.directoryTree&&t.push(`Directory:\n${e.directoryTree}`),e.modifiedFiles.length>0){let n=e.modifiedFiles.map(e=>` ${e.action}: ${e.path} — ${e.summary}`).join(`
|
|
196
|
+
`);t.push(`Modified Files:\n${n}`)}return e.planStatus&&t.push(`Plan Status: ${e.planStatus}`),e.findings.length>0&&t.push(`Findings:\n${e.findings.map(e=>` - ${e}`).join(`
|
|
197
|
+
`)}`),t.join(`
|
|
198
|
+
|
|
199
|
+
`)}async buildDirectoryTree(e,t,n=``){if(t>=4)return n?`${n}...\n`:``;let r;try{r=(await u(e,{withFileTypes:!0})).filter(e=>!Ft.has(e.name)&&!e.name.startsWith(`.`)).sort((e,t)=>e.isDirectory()===t.isDirectory()?e.name.localeCompare(t.name):e.isDirectory()?-1:1).slice(0,50).map(e=>e.name+(e.isDirectory()?`/`:``))}catch{return``}let i=[];for(let a of r){let r=a.endsWith(`/`);if(i.push(`${n}${a}`),r){let r=await this.buildDirectoryTree(c(e,a.slice(0,-1)),t+1,n+` `);r&&i.push(r.trimEnd())}}return i.join(`
|
|
200
|
+
`)}async checkRecentFiles(e,t){let n=[],r=Date.now();for(let i of t){let t=i.startsWith(`/`)?i:c(e,i),a=l(e,t);try{let e=await d(t),i=r-e.mtimeMs,o=e.birthtimeMs>0&&e.mtimeMs-e.birthtimeMs<1e3?`created`:`modified`,s=`${(e.size/1024).toFixed(1)}KB, modified ${Lt(i)} ago`;n.push({path:a,action:o,summary:s})}catch{n.push({path:a,action:`deleted`,summary:`file not found`})}}return n}};function Lt(e){let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m`:`${Math.floor(n/60)}h`}const Rt=.6;function zt(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>2))}function Bt(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&n++;return n/(e.size+t.size-n)}const Vt=new Set([1,2]);function Ht(e){let t=`[${e.tags.join(`, `)}] ${e.trigger} → ${e.insight}`,n=0;for(let e of t)/[\u3000-\u9fff\uff00-\uffef]/.test(e)&&n++;return Math.ceil(n+(t.length-n)/4)}function Ut(e){let t=JSON.stringify({tags:[...e.tags].sort(),trigger:e.trigger,insight:e.insight}),n=2166136261;for(let e=0;e<t.length;e++)n^=t.charCodeAt(e),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,`0`)}function $(e,t){let n=e.relevantHitCount??e.appliedCount??0;return{...e,scope:e.scope??t,state:e.state??`active`,contentHash:e.contentHash??Ut(e),estimatedTokens:e.estimatedTokens??Ht(e),relevantHitCount:n,coreInjectedCount:e.coreInjectedCount??0,hitCountTotal:e.hitCountTotal??n,appliedCount:n}}function Wt(e){if(!e||typeof e!=`object`)return;let t=e;if(t.version!==void 0&&Vt.has(t.version)&&t.data)return t.data;let n=e;if(n.version===void 0&&Array.isArray(n.lessons))return e}var Gt=class{lessons=new Map;nextId=1;loaded=!1;snapshotId;persistence;store;storePath;logger;scope;ephemeral;constructor(e){if(this.logger=e?.logger,this.scope=e?.scope,this.ephemeral=e?.ephemeral??!1,e?.store)this.store=e.store,this.storePath=e.storePath??e.path;else if(e?.path){let t=s(e.path)||`.json`;this.snapshotId=a(e.path,t),this.persistence=f({type:`file`,baseDir:o(e.path),extension:t})}}async save(e){await this.ensureLoaded();let t=`lesson_${this.nextId++}`,n=$({...e,id:t,createdAt:Date.now(),appliedCount:0},this.scope);return this.lessons.set(t,n),await this.persist(),n}async search(e,t=5){await this.ensureLoaded();let n=e.toLowerCase(),r=[];for(let e of this.lessons.values()){let t=0;e.trigger.toLowerCase().includes(n)&&(t+=3),e.insight.toLowerCase().includes(n)&&(t+=2);for(let r of e.tags)r.toLowerCase().includes(n)&&(t+=1);t>0&&r.push({lesson:e,score:t})}let i=r.sort((e,t)=>t.score-e.score).slice(0,t).map(e=>(e.lesson.relevantHitCount=(e.lesson.relevantHitCount??0)+1,e.lesson.hitCountTotal=(e.lesson.hitCountTotal??0)+1,e.lesson.lastAccessedAt=Date.now(),e.lesson.appliedCount=e.lesson.relevantHitCount,e.lesson));return await this.persist(),i}async findSimilar(e,t,n=Rt){await this.ensureLoaded();let r=zt(`${e} ${t}`);if(r.size===0)return;let i;for(let e of this.lessons.values()){let t=Bt(r,zt(`${e.trigger} ${e.insight}`));t>=n&&(!i||t>i.similarity)&&(i={lesson:e,similarity:t})}return i}async saveDeduped(e,t=Rt){let n=await this.findSimilar(e.trigger,e.insight,t);return n?{lesson:n.lesson,deduped:!0}:{lesson:await this.save(e),deduped:!1}}async list(e){await this.ensureLoaded();let t=[...this.lessons.values()];if(e?.tags&&e.tags.length>0){let n=new Set(e.tags);t=t.filter(e=>e.tags.some(e=>n.has(e)))}if(e?.query){let n=e.query.toLowerCase();t=t.filter(e=>e.trigger.toLowerCase().includes(n)||e.insight.toLowerCase().includes(n))}return t}async get(e){return await this.ensureLoaded(),this.lessons.get(e)}async recordRelevantHits(e,t=Date.now()){await this.ensureLoaded();let n=!1;for(let r of e){let e=this.lessons.get(r);e&&(e.relevantHitCount=(e.relevantHitCount??0)+1,e.hitCountTotal=(e.hitCountTotal??0)+1,e.lastAccessedAt=t,e.appliedCount=e.relevantHitCount,n=!0)}n&&await this.persist()}async delete(e){await this.ensureLoaded();let t=this.lessons.delete(e);return t&&await this.persist(),t}get size(){return this.lessons.size}async ensureLoaded(){if(!this.loaded){if(this.store&&this.storePath){await this.loadFromStore(),this.loaded=!0;return}if(!this.persistence||!this.snapshotId){this.loaded=!0;return}try{let e=Wt(await this.persistence.load(this.snapshotId));if(e){for(let t of e.lessons)this.lessons.set(t.id,$(t,this.scope));this.nextId=e.nextId??this.lessons.size+1}}catch(e){this.logger?.warn(`Failed to load lessons from file persistence (snapshotId=${this.snapshotId}): ${String(e)}. Falling back to empty lessons — all previously learned lessons will be lost for this session.`)}this.loaded=!0}}async refresh(){!this.store||!this.storePath||(await this.loadFromStore(),this.loaded=!0)}async loadFromStore(){try{let e=(await this.store.load([{path:this.storePath,writable:!0}])).get(this.storePath);if(!e)return;let t=Wt(JSON.parse(e));if(t){for(let e of t.lessons)this.lessons.set(e.id,$(e,this.scope));this.nextId=t.nextId??this.lessons.size+1}}catch(e){this.logger?.warn(`Failed to load lessons from MemoryStore (storePath=${this.storePath}): ${String(e)}. Falling back to empty lessons — all previously learned lessons will be lost for this session.`)}}async persist(){if(this.ephemeral)return;if(this.store&&this.storePath){let e={lessons:[...this.lessons.values()],nextId:this.nextId};await this.store.write(this.storePath,JSON.stringify({version:2,data:e}));return}if(!this.persistence||!this.snapshotId)return;let e=Date.now();await p(this.persistence,this.snapshotId,{lessons:[...this.lessons.values()],nextId:this.nextId},{version:2,tags:[`operational-learning`],now:e,preserveCreatedAt:!1})}};export{Ct as AutoMemory,z as DEFAULT_COMPACTION_CONFIG,te as DEFAULT_MEMORY_INJECTION_BUDGET_TOKENS,ce as DEFAULT_MEMORY_SOURCES,B as DEFAULT_PRUNE_CONFIG,Rt as DEFAULT_SIMILARITY_THRESHOLD,It as FileStateManager,D as FileSystemMemoryStore,ht as HttpMemoryStore,pe as IMAGE_BLOCK_TOKEN_ESTIMATE,dt as InMemoryArchiveStorage,ue as InMemoryMemoryStore,ie as LESSON_EXTRACTION_PROMPT,pt as MemoryManager,Gt as OperationalLearningStore,le as PersistentMemory,x as SEGMENT_MERGE_PROMPT,b as SEGMENT_SUMMARIZATION_PROMPT,m as SUMMARIZATION_PROMPT,g as TURN_PREFIX_SUMMARIZATION_PROMPT,h as UPDATE_SUMMARIZATION_PROMPT,y as WITH_PRESERVED_TAIL_PROMPT,oe as buildArchiveReference,ae as buildExtractionPrompt,se as buildLowCoverageNotice,re as buildMemoryInjection,ee as buildSegmentMergePrompt,S as buildSummarizationPrompt,w as buildTurnPrefixPrompt,Ut as computeLessonContentHash,R as computeMemoryDefaults,Pt as createMemoryAutoExtractor,mt as createMemoryManager,vt as createOverlayMemoryStore,yt as discoverAgentsSources,fe as ensureTokenizer,Ht as estimateLessonTokens,N as estimateMessageTokens,P as estimateMessagesTokens,j as estimateTokens,A as estimateTokensHeuristic,Et as extractLessons,K as formatArchive,M as messageToText,Be as prune,V as resolveContextSize,Dt as saveExtractedLessons};
|
|
201
|
+
//# sourceMappingURL=index.js.map
|