@duetso/agent 0.1.20

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.
Files changed (148) hide show
  1. package/LICENSE +189 -0
  2. package/README.md +315 -0
  3. package/dist/package.json +84 -0
  4. package/dist/src/cli.d.ts +23 -0
  5. package/dist/src/cli.d.ts.map +1 -0
  6. package/dist/src/cli.js +754 -0
  7. package/dist/src/cli.js.map +1 -0
  8. package/dist/src/core/serializer.d.ts +3 -0
  9. package/dist/src/core/serializer.d.ts.map +1 -0
  10. package/dist/src/core/serializer.js +22 -0
  11. package/dist/src/core/serializer.js.map +1 -0
  12. package/dist/src/core/structured-output.d.ts +13 -0
  13. package/dist/src/core/structured-output.d.ts.map +1 -0
  14. package/dist/src/core/structured-output.js +41 -0
  15. package/dist/src/core/structured-output.js.map +1 -0
  16. package/dist/src/guardrails/firewall.d.ts +7 -0
  17. package/dist/src/guardrails/firewall.d.ts.map +1 -0
  18. package/dist/src/guardrails/firewall.js +31 -0
  19. package/dist/src/guardrails/firewall.js.map +1 -0
  20. package/dist/src/guardrails/pattern.d.ts +13 -0
  21. package/dist/src/guardrails/pattern.d.ts.map +1 -0
  22. package/dist/src/guardrails/pattern.js +70 -0
  23. package/dist/src/guardrails/pattern.js.map +1 -0
  24. package/dist/src/guardrails/semantic.d.ts +14 -0
  25. package/dist/src/guardrails/semantic.d.ts.map +1 -0
  26. package/dist/src/guardrails/semantic.js +47 -0
  27. package/dist/src/guardrails/semantic.js.map +1 -0
  28. package/dist/src/index.d.ts +20 -0
  29. package/dist/src/index.d.ts.map +1 -0
  30. package/dist/src/index.js +20 -0
  31. package/dist/src/index.js.map +1 -0
  32. package/dist/src/lib/compact-json.d.ts +11 -0
  33. package/dist/src/lib/compact-json.d.ts.map +1 -0
  34. package/dist/src/lib/compact-json.js +36 -0
  35. package/dist/src/lib/compact-json.js.map +1 -0
  36. package/dist/src/lib/xml.d.ts +3 -0
  37. package/dist/src/lib/xml.d.ts.map +1 -0
  38. package/dist/src/lib/xml.js +9 -0
  39. package/dist/src/lib/xml.js.map +1 -0
  40. package/dist/src/memory/observation-groups.d.ts +15 -0
  41. package/dist/src/memory/observation-groups.d.ts.map +1 -0
  42. package/dist/src/memory/observation-groups.js +159 -0
  43. package/dist/src/memory/observation-groups.js.map +1 -0
  44. package/dist/src/memory/observational-prompts.d.ts +27 -0
  45. package/dist/src/memory/observational-prompts.d.ts.map +1 -0
  46. package/dist/src/memory/observational-prompts.js +237 -0
  47. package/dist/src/memory/observational-prompts.js.map +1 -0
  48. package/dist/src/memory/observational.d.ts +63 -0
  49. package/dist/src/memory/observational.d.ts.map +1 -0
  50. package/dist/src/memory/observational.js +605 -0
  51. package/dist/src/memory/observational.js.map +1 -0
  52. package/dist/src/memory/storage.d.ts +3 -0
  53. package/dist/src/memory/storage.d.ts.map +1 -0
  54. package/dist/src/memory/storage.js +127 -0
  55. package/dist/src/memory/storage.js.map +1 -0
  56. package/dist/src/memory/store.d.ts +13 -0
  57. package/dist/src/memory/store.d.ts.map +1 -0
  58. package/dist/src/memory/store.js +106 -0
  59. package/dist/src/memory/store.js.map +1 -0
  60. package/dist/src/model-resolution/duet-gateway.d.ts +35 -0
  61. package/dist/src/model-resolution/duet-gateway.d.ts.map +1 -0
  62. package/dist/src/model-resolution/duet-gateway.js +56 -0
  63. package/dist/src/model-resolution/duet-gateway.js.map +1 -0
  64. package/dist/src/model-resolution/index.d.ts +31 -0
  65. package/dist/src/model-resolution/index.d.ts.map +1 -0
  66. package/dist/src/model-resolution/index.js +129 -0
  67. package/dist/src/model-resolution/index.js.map +1 -0
  68. package/dist/src/session/session-manager.d.ts +45 -0
  69. package/dist/src/session/session-manager.d.ts.map +1 -0
  70. package/dist/src/session/session-manager.js +94 -0
  71. package/dist/src/session/session-manager.js.map +1 -0
  72. package/dist/src/session/session.d.ts +113 -0
  73. package/dist/src/session/session.d.ts.map +1 -0
  74. package/dist/src/session/session.js +308 -0
  75. package/dist/src/session/session.js.map +1 -0
  76. package/dist/src/tui/app.d.ts +60 -0
  77. package/dist/src/tui/app.d.ts.map +1 -0
  78. package/dist/src/tui/app.js +742 -0
  79. package/dist/src/tui/app.js.map +1 -0
  80. package/dist/src/turn-runner/agent-events.d.ts +5 -0
  81. package/dist/src/turn-runner/agent-events.d.ts.map +1 -0
  82. package/dist/src/turn-runner/agent-events.js +59 -0
  83. package/dist/src/turn-runner/agent-events.js.map +1 -0
  84. package/dist/src/turn-runner/prompts.d.ts +13 -0
  85. package/dist/src/turn-runner/prompts.d.ts.map +1 -0
  86. package/dist/src/turn-runner/prompts.js +79 -0
  87. package/dist/src/turn-runner/prompts.js.map +1 -0
  88. package/dist/src/turn-runner/shell-state-handle.d.ts +32 -0
  89. package/dist/src/turn-runner/shell-state-handle.d.ts.map +1 -0
  90. package/dist/src/turn-runner/shell-state-handle.js +168 -0
  91. package/dist/src/turn-runner/shell-state-handle.js.map +1 -0
  92. package/dist/src/turn-runner/skill-context.d.ts +26 -0
  93. package/dist/src/turn-runner/skill-context.d.ts.map +1 -0
  94. package/dist/src/turn-runner/skill-context.js +110 -0
  95. package/dist/src/turn-runner/skill-context.js.map +1 -0
  96. package/dist/src/turn-runner/skills.d.ts +35 -0
  97. package/dist/src/turn-runner/skills.d.ts.map +1 -0
  98. package/dist/src/turn-runner/skills.js +130 -0
  99. package/dist/src/turn-runner/skills.js.map +1 -0
  100. package/dist/src/turn-runner/state-machine-controller.d.ts +90 -0
  101. package/dist/src/turn-runner/state-machine-controller.d.ts.map +1 -0
  102. package/dist/src/turn-runner/state-machine-controller.js +289 -0
  103. package/dist/src/turn-runner/state-machine-controller.js.map +1 -0
  104. package/dist/src/turn-runner/state-machine-session.d.ts +27 -0
  105. package/dist/src/turn-runner/state-machine-session.d.ts.map +1 -0
  106. package/dist/src/turn-runner/state-machine-session.js +189 -0
  107. package/dist/src/turn-runner/state-machine-session.js.map +1 -0
  108. package/dist/src/turn-runner/tools.d.ts +193 -0
  109. package/dist/src/turn-runner/tools.d.ts.map +1 -0
  110. package/dist/src/turn-runner/tools.js +509 -0
  111. package/dist/src/turn-runner/tools.js.map +1 -0
  112. package/dist/src/turn-runner/turn-runner.d.ts +160 -0
  113. package/dist/src/turn-runner/turn-runner.d.ts.map +1 -0
  114. package/dist/src/turn-runner/turn-runner.js +907 -0
  115. package/dist/src/turn-runner/turn-runner.js.map +1 -0
  116. package/dist/src/turn-runner/turn-state.d.ts +6 -0
  117. package/dist/src/turn-runner/turn-state.d.ts.map +1 -0
  118. package/dist/src/turn-runner/turn-state.js +32 -0
  119. package/dist/src/turn-runner/turn-state.js.map +1 -0
  120. package/dist/src/turn-runner/usage-accounting.d.ts +7 -0
  121. package/dist/src/turn-runner/usage-accounting.d.ts.map +1 -0
  122. package/dist/src/turn-runner/usage-accounting.js +49 -0
  123. package/dist/src/turn-runner/usage-accounting.js.map +1 -0
  124. package/dist/src/types/agent.d.ts +15 -0
  125. package/dist/src/types/agent.d.ts.map +1 -0
  126. package/dist/src/types/agent.js +2 -0
  127. package/dist/src/types/agent.js.map +1 -0
  128. package/dist/src/types/config.d.ts +37 -0
  129. package/dist/src/types/config.d.ts.map +1 -0
  130. package/dist/src/types/config.js +2 -0
  131. package/dist/src/types/config.js.map +1 -0
  132. package/dist/src/types/guardrails.d.ts +34 -0
  133. package/dist/src/types/guardrails.d.ts.map +1 -0
  134. package/dist/src/types/guardrails.js +2 -0
  135. package/dist/src/types/guardrails.js.map +1 -0
  136. package/dist/src/types/memory.d.ts +151 -0
  137. package/dist/src/types/memory.d.ts.map +1 -0
  138. package/dist/src/types/memory.js +2 -0
  139. package/dist/src/types/memory.js.map +1 -0
  140. package/dist/src/types/protocol.d.ts +426 -0
  141. package/dist/src/types/protocol.d.ts.map +1 -0
  142. package/dist/src/types/protocol.js +2 -0
  143. package/dist/src/types/protocol.js.map +1 -0
  144. package/dist/src/types/state-machine.d.ts +344 -0
  145. package/dist/src/types/state-machine.d.ts.map +1 -0
  146. package/dist/src/types/state-machine.js +2 -0
  147. package/dist/src/types/state-machine.js.map +1 -0
  148. package/package.json +84 -0
@@ -0,0 +1,159 @@
1
+ import { randomBytes } from "node:crypto";
2
+ const OBSERVATION_GROUP_PATTERN = /<observation-group([^>]*)>([\s\S]*?)<\/observation-group>/g;
3
+ const ATTRIBUTE_PATTERN = /([\w][\w-]*)="([^"]*)"/g;
4
+ const REFLECTION_GROUP_SPLIT_PATTERN = /^##\s+Group\s+/m;
5
+ function parseObservationGroupAttributes(attributeString) {
6
+ const attributes = {};
7
+ for (const match of attributeString.matchAll(ATTRIBUTE_PATTERN)) {
8
+ const [, key, value] = match;
9
+ if (key && value !== undefined) {
10
+ attributes[key] = value;
11
+ }
12
+ }
13
+ return attributes;
14
+ }
15
+ function parseReflectionObservationGroupSections(content) {
16
+ const normalizedContent = content.trim();
17
+ if (!normalizedContent || !REFLECTION_GROUP_SPLIT_PATTERN.test(normalizedContent)) {
18
+ return [];
19
+ }
20
+ return normalizedContent
21
+ .split(REFLECTION_GROUP_SPLIT_PATTERN)
22
+ .map((section) => section.trim())
23
+ .filter(Boolean)
24
+ .map((section) => {
25
+ const newlineIndex = section.indexOf("\n");
26
+ const heading = (newlineIndex >= 0 ? section.slice(0, newlineIndex) : section).trim();
27
+ const body = (newlineIndex >= 0 ? section.slice(newlineIndex + 1) : "").trim();
28
+ return {
29
+ heading,
30
+ body: stripReflectionGroupMetadata(body),
31
+ };
32
+ });
33
+ }
34
+ function stripReflectionGroupMetadata(body) {
35
+ return body.replace(/^_range:\s*`[^`]*`_\s*\n?/m, "").trim();
36
+ }
37
+ export function generateAnchorId() {
38
+ return randomBytes(8).toString("hex");
39
+ }
40
+ export function wrapInObservationGroup(observations, range, id = generateAnchorId(), _sourceGroupIds, kind) {
41
+ const content = observations.trim();
42
+ const kindAttr = kind ? ` kind="${kind}"` : "";
43
+ return `<observation-group id="${id}" range="${range}"${kindAttr}>\n${content}\n</observation-group>`;
44
+ }
45
+ export function parseObservationGroups(observations) {
46
+ if (!observations) {
47
+ return [];
48
+ }
49
+ const groups = [];
50
+ let match;
51
+ while ((match = OBSERVATION_GROUP_PATTERN.exec(observations)) !== null) {
52
+ const attributes = parseObservationGroupAttributes(match[1] ?? "");
53
+ const id = attributes["id"];
54
+ const range = attributes["range"];
55
+ if (!id || !range) {
56
+ continue;
57
+ }
58
+ groups.push({
59
+ id,
60
+ range,
61
+ kind: attributes["kind"],
62
+ content: match[2].trim(),
63
+ });
64
+ }
65
+ return groups;
66
+ }
67
+ export function stripObservationGroups(observations) {
68
+ if (!observations) {
69
+ return observations;
70
+ }
71
+ return observations
72
+ .replace(OBSERVATION_GROUP_PATTERN, (_match, _attributes, content) => content.trim())
73
+ .replace(/\n{3,}/g, "\n\n")
74
+ .trim();
75
+ }
76
+ function getRangeSegments(range) {
77
+ return range
78
+ .split(",")
79
+ .map((segment) => segment.trim())
80
+ .filter(Boolean);
81
+ }
82
+ export function combineObservationGroupRanges(groups) {
83
+ const segments = groups.flatMap((group) => getRangeSegments(group.range));
84
+ if (segments.length === 0) {
85
+ return "";
86
+ }
87
+ const firstSegment = segments[0];
88
+ const lastSegment = segments[segments.length - 1];
89
+ const firstStart = firstSegment?.split(":")[0]?.trim();
90
+ const lastEnd = lastSegment?.split(":").at(-1)?.trim();
91
+ if (firstStart && lastEnd) {
92
+ return `${firstStart}:${lastEnd}`;
93
+ }
94
+ return Array.from(new Set(segments)).join(",");
95
+ }
96
+ export function renderObservationGroupsForReflection(observations) {
97
+ const groups = parseObservationGroups(observations);
98
+ if (groups.length === 0) {
99
+ return null;
100
+ }
101
+ const groupsByContent = new Map(groups.map((group) => [group.content.trim(), group]));
102
+ const result = observations.replace(OBSERVATION_GROUP_PATTERN, (_match, _attrs, content) => {
103
+ const group = groupsByContent.get(content.trim());
104
+ if (!group)
105
+ return content.trim();
106
+ return `## Group \`${group.id}\`\n_range: \`${group.range}\`_\n\n${group.content}`;
107
+ });
108
+ return result.replace(/\n{3,}/g, "\n\n").trim();
109
+ }
110
+ function getCanonicalGroupId(sectionHeading, fallbackIndex) {
111
+ const match = sectionHeading.match(/`([^`]+)`/);
112
+ return match?.[1]?.trim() || `derived-group-${fallbackIndex + 1}`;
113
+ }
114
+ export function deriveObservationGroupProvenance(content, groups) {
115
+ const sections = parseReflectionObservationGroupSections(content);
116
+ if (sections.length === 0 || groups.length === 0) {
117
+ return [];
118
+ }
119
+ return sections.map((section, index) => {
120
+ const bodyLines = new Set(section.body
121
+ .split("\n")
122
+ .map((line) => line.trim())
123
+ .filter(Boolean));
124
+ const matchingGroups = groups.filter((group) => {
125
+ const groupLines = group.content
126
+ .split("\n")
127
+ .map((line) => line.trim())
128
+ .filter(Boolean);
129
+ return groupLines.some((line) => bodyLines.has(line));
130
+ });
131
+ const fallbackGroup = groups[Math.min(index, groups.length - 1)];
132
+ const resolvedGroups = matchingGroups.length > 0 ? matchingGroups : fallbackGroup ? [fallbackGroup] : [];
133
+ const canonicalGroupId = getCanonicalGroupId(section.heading, index);
134
+ return {
135
+ id: canonicalGroupId,
136
+ range: combineObservationGroupRanges(resolvedGroups),
137
+ kind: "reflection",
138
+ content: section.body,
139
+ };
140
+ });
141
+ }
142
+ export function reconcileObservationGroupsFromReflection(content, sourceObservations) {
143
+ const sourceGroups = parseObservationGroups(sourceObservations);
144
+ if (sourceGroups.length === 0) {
145
+ return null;
146
+ }
147
+ const normalizedContent = content.trim();
148
+ if (!normalizedContent) {
149
+ return "";
150
+ }
151
+ const derivedGroups = deriveObservationGroupProvenance(normalizedContent, sourceGroups);
152
+ if (derivedGroups.length > 0) {
153
+ return derivedGroups
154
+ .map((group) => wrapInObservationGroup(group.content, group.range, group.id, undefined, group.kind))
155
+ .join("\n\n");
156
+ }
157
+ return wrapInObservationGroup(normalizedContent, combineObservationGroupRanges(sourceGroups), generateAnchorId(), undefined, "reflection");
158
+ }
159
+ //# sourceMappingURL=observation-groups.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observation-groups.js","sourceRoot":"","sources":["../../../src/memory/observation-groups.ts"],"names":[],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AAE,KAAK,CAAC,IAAI,CAAC,CACpF;aACA,IAAI,CAAC,MAAM,CAAC,CAAC;IAClB,CAAC;IAED,OAAO,sBAAsB,CAC3B,iBAAiB,EACjB,6BAA6B,CAAC,YAAY,CAAC,EAC3C,gBAAgB,EAAE,EAClB,SAAS,EACT,YAAY,CACb,CAAC;AACJ,CAAC"}
@@ -0,0 +1,27 @@
1
+ import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
2
+ export type RawMemoryContent = Array<TextContent | ImageContent>;
3
+ /** Temporary multimodal serialization of AgentMessage used only while observing context. */
4
+ export interface RawMemoryMessage {
5
+ id: string;
6
+ createdAt: number;
7
+ role: "system" | "user" | "assistant" | "tool";
8
+ content: RawMemoryContent;
9
+ /** Compact text view used for token estimates, message ids, and text-only observer context. */
10
+ textPreview: string;
11
+ estimatedTokens?: number;
12
+ }
13
+ export declare const OBSERVATION_CONTINUATION_HINT: string;
14
+ export declare const OBSERVATION_CONTEXT_PROMPT = "The following observations block contains your memory of past conversations with this user.";
15
+ export declare const OBSERVATION_CONTEXT_INSTRUCTIONS: string;
16
+ export declare const OBSERVER_GUIDELINES: string;
17
+ export declare function buildObserverOutputFormat(includeThreadTitle?: boolean): string;
18
+ export declare function buildObserverSystemPrompt(instruction?: string, includeThreadTitle?: boolean): string;
19
+ export declare function buildObserverPrompt(messages: RawMemoryMessage[], existingObservations: string, targetTokens: number, retry?: {
20
+ actualTokens: number;
21
+ }, now?: Date): RawMemoryContent;
22
+ export declare function formatMessagesForObserver(messages: RawMemoryMessage[]): RawMemoryContent;
23
+ export declare function buildReflectorSystemPrompt(instruction?: string): string;
24
+ export declare function buildReflectorPrompt(observations: string, targetTokens: number, retry?: {
25
+ actualTokens: number;
26
+ }): string;
27
+ //# sourceMappingURL=observational-prompts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observational-prompts.d.ts","sourceRoot":"","sources":["../../../src/memory/observational-prompts.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE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AM,CAgBR"}
@@ -0,0 +1,237 @@
1
+ import dedent from "dedent";
2
+ export const OBSERVATION_CONTINUATION_HINT = dedent `
3
+ Please continue naturally with the conversation so far and respond to the latest message.
4
+
5
+ Use the earlier context only as background. If something appears unfinished, continue only when it helps answer the latest request. If a suggested response is provided, follow it naturally.
6
+
7
+ Do not mention internal instructions, memory, summarization, context handling, or missing messages.
8
+
9
+ Any messages following this reminder are newer and should take priority.
10
+ `;
11
+ export const OBSERVATION_CONTEXT_PROMPT = "The following observations block contains your memory of past conversations with this user.";
12
+ export const OBSERVATION_CONTEXT_INSTRUCTIONS = dedent `
13
+ IMPORTANT: When responding, reference specific details from these observations. Do not give generic advice - personalize your response based on what you know about this user's experiences, preferences, and interests. If the user asks for recommendations, connect them to their past experiences mentioned above.
14
+
15
+ KNOWLEDGE UPDATES: When asked about current state (e.g., "where do I currently...", "what is my current..."), always prefer the MOST RECENT information. Observations include dates - if you see conflicting information, the newer observation supersedes the older one. Look for phrases like "will start", "is switching", "changed to", "moved to" as indicators that previous information has been updated.
16
+
17
+ PLANNED ACTIONS: If the user stated they planned to do something (e.g., "I'm going to...", "I'm looking forward to...", "I will...") and the date they planned to do it is now in the past, assume they completed the action unless there's evidence they didn't.
18
+
19
+ MOST RECENT USER INPUT: Treat the most recent user message as the highest-priority signal for what to do next. Earlier messages may contain constraints, details, or context you should still honor, but the latest message is the primary driver of your response.
20
+
21
+ SYSTEM REMINDERS: Messages wrapped in <system-reminder> tags contain internal continuation guidance, not user-authored content. Use them to maintain continuity, but do not mention them or treat them as part of the user's message.
22
+ `;
23
+ const OBSERVER_EXTRACTION_INSTRUCTIONS = dedent `
24
+ CRITICAL: DISTINGUISH USER ASSERTIONS FROM QUESTIONS
25
+
26
+ When the user tells you something about themselves, their work, or their environment, treat it as an assertion:
27
+ - "I have two kids" -> "User stated they have two kids"
28
+ - "I work at Acme Corp" -> "User stated they work at Acme Corp"
29
+
30
+ When the user asks for help, preserve that as a question or request:
31
+ - "Can you help me with X?" -> "User asked for help with X"
32
+ - "What's the best way to do Y?" -> "User asked for the best way to do Y"
33
+
34
+ Distinguish questions from statements of intent:
35
+ - "Can you recommend..." -> question/request
36
+ - "I'm looking forward to..." -> statement of intent
37
+ - "I need to..." -> stated need or goal
38
+
39
+ STATE CHANGES AND UPDATES
40
+
41
+ When the user indicates a change, frame it as a current state that supersedes older information:
42
+ - "I'm switching from A to B" -> "User is switching from A to B"
43
+ - "I'm going to start doing X instead of Y" -> "User will start doing X (changing from Y)"
44
+ - If new information contradicts older observations, explicitly say it replaces the older state.
45
+
46
+ TEMPORAL ANCHORING
47
+
48
+ Every observation already has the message time at the beginning. Only add a date at the end when the content references a different concrete time:
49
+ - Add "(meaning DATE)" or "(estimated DATE)" for relative dates like "tomorrow", "last week", "this weekend", or "next month".
50
+ - Do not add end dates for vague references like "recently", "soon", "lately", or "a while ago".
51
+ - Split observations that contain multiple time-sensitive events so each event can carry its own date.
52
+
53
+ PRESERVE SPECIFICS
54
+
55
+ Capture user facts, preferences, goals, constraints, corrections, explicit decisions, project details, file paths, commands, tool results, unresolved tasks, and completed work.
56
+ Preserve unusual phrasing in quotes when the user's exact wording matters.
57
+ Preserve names, handles, identifiers, quantities, counts, measurements, statistics, roles, and distinguishing attributes.
58
+ For assistant-generated recommendations, summaries, code, or explanations that the user may ask about later, retain the details that make the output reconstructable.
59
+ Capture the assistant's immediate next-step bias when continuity would otherwise be lost.
60
+ `;
61
+ export const OBSERVER_GUIDELINES = dedent `
62
+ - Be specific enough for the assistant to act on
63
+ - Good: "User prefers short, direct answers without lengthy explanations"
64
+ - Bad: "User stated a preference" (too vague)
65
+ - Add 1 to 5 observations per exchange
66
+ - Use terse language to save tokens. Sentences should be dense without unnecessary words
67
+ - Do not add repetitive observations that have already been observed. Group repeated similar actions under a single parent with sub-bullets for new results
68
+ - If the agent calls tools, observe what was called, why, and what was learned
69
+ - When observing files with line numbers, include the line number if useful
70
+ - If the agent provides a detailed response, observe the contents so it could be repeated
71
+ - Make sure each observation starts with a priority emoji (🔴, 🟡, 🟢) or a completion marker (✅)
72
+ - Capture short and medium user messages nearly verbatim; summarize long messages but keep key quotes that carry intent
73
+ - User confirmations or explicit resolved outcomes should be ✅ when they clearly signal something is done; unresolved or critical user facts remain 🔴
74
+ - Treat ✅ as a memory signal that tells the assistant something is finished and should not be repeated unless new information changes it
75
+ - Make completion observations answer "What exactly is now done?"
76
+ - Prefer concrete resolved outcomes over meta-level workflow or bookkeeping updates
77
+ - When multiple concrete things were completed, capture them concretely rather than collapsing them into vague progress
78
+ - Observe WHAT the agent did and WHAT it means
79
+ - If the user provides detailed messages, code snippets, or exact text they are iterating on, preserve all important details
80
+ `;
81
+ export function buildObserverOutputFormat(includeThreadTitle = false) {
82
+ const threadTitleSection = includeThreadTitle
83
+ ? dedent `
84
+ - threadTitle: A short, noun-phrase title for this conversation (2-5 words). Only update when the topic meaningfully changes.
85
+ `
86
+ : "";
87
+ return dedent `
88
+ Use priority levels:
89
+ - 🔴 High: explicit user assertions, facts, preferences, requests, unresolved goals, critical context
90
+ - 🟡 Medium: project details, learned information, tool results
91
+ - 🟢 Low: minor details, uncertain observations
92
+ - ✅ Completed: concrete task finished, question answered, issue resolved, goal achieved, or subtask completed
93
+
94
+ Group related observations by indenting:
95
+ * 🔴 (14:33) Agent debugging auth issue
96
+ * -> ran git status, found 3 modified files
97
+ * -> viewed auth.ts:45-60, found missing null check
98
+ * ✅ Tests passing, auth issue resolved
99
+
100
+ Group observations by date, then list each with 24-hour time.
101
+
102
+ observations:
103
+ Date: Dec 4, 2025
104
+ * 🔴 (14:30) User prefers direct answers
105
+ * 🔴 (14:31) Working on feature X
106
+
107
+ currentTask:
108
+ State the current task(s) explicitly:
109
+ - Primary: what the agent is currently working on
110
+ - Secondary: other pending tasks, marked "waiting for user" when appropriate
111
+ - If the agent started doing something without user approval, note that it is off-task
112
+
113
+ suggestedContinuation:
114
+ Hint for the agent's immediate next message. If the assistant needs to respond to the user, say that it should pause for user reply before continuing other tasks.
115
+ ${threadTitleSection}
116
+ `;
117
+ }
118
+ export function buildObserverSystemPrompt(instruction, includeThreadTitle = false) {
119
+ return dedent `
120
+ You are the memory consciousness of an AI assistant. Your observations will be the ONLY information the assistant has about past interactions with this user.
121
+
122
+ Extract observations that will help the assistant remember:
123
+
124
+ ${OBSERVER_EXTRACTION_INSTRUCTIONS}
125
+
126
+ === STRUCTURED OUTPUT FIELDS ===
127
+
128
+ Call the structured output tool with these fields. Do not write free-form text outside the tool call.
129
+
130
+ ${buildObserverOutputFormat(includeThreadTitle)}
131
+
132
+ === GUIDELINES ===
133
+
134
+ ${OBSERVER_GUIDELINES}
135
+
136
+ === IMPORTANT: THREAD ATTRIBUTION ===
137
+
138
+ Do NOT add thread identifiers, thread IDs, or tags to your observations.
139
+ Thread attribution is handled externally by the system.
140
+ Simply output your observations without any thread-related markup.
141
+
142
+ Remember: These observations are the assistant's ONLY memory. Make them count.
143
+
144
+ User messages are extremely important. If the user asks a question or gives a new task, make it clear in <current-task> that this is the priority.
145
+ ${instruction ? `\n\n=== CUSTOM INSTRUCTIONS ===\n\n${instruction}` : ""}
146
+ `;
147
+ }
148
+ export function buildObserverPrompt(messages, existingObservations, targetTokens, retry, now = new Date()) {
149
+ const retryInstruction = retry
150
+ ? dedent `
151
+ The previous observation log was approximately ${retry.actualTokens.toLocaleString("en-US")} tokens, which exceeded the ${targetTokens.toLocaleString("en-US")}-token budget.
152
+
153
+ Retry with a shorter observation log under approximately ${targetTokens.toLocaleString("en-US")} tokens. Preserve the highest-priority user facts, unresolved work, concrete decisions, and completion markers first.
154
+ `
155
+ : dedent `
156
+ Target budget: keep the new observation log under approximately ${targetTokens.toLocaleString("en-US")} tokens.
157
+ `;
158
+ const previous = existingObservations.trim()
159
+ ? dedent `
160
+ ## Existing Observations
161
+
162
+ Do not repeat these existing observations. New observations will be appended.
163
+
164
+ ${existingObservations}
165
+
166
+ ---
167
+ `
168
+ : "";
169
+ const header = dedent `
170
+ ${previous}
171
+ ## New Message History to Observe
172
+
173
+ Current date: ${now.toISOString()}
174
+ `;
175
+ return [
176
+ { type: "text", text: header },
177
+ ...formatMessagesForObserver(messages),
178
+ {
179
+ type: "text",
180
+ text: dedent `
181
+ ---
182
+
183
+ ${retryInstruction}
184
+
185
+ Extract new observations from this message history. When images are attached to a message, inspect them directly and summarize relevant visual details, user-visible text, UI state, diagrams, errors, or other facts needed for future continuity.
186
+ `,
187
+ },
188
+ ];
189
+ }
190
+ export function formatMessagesForObserver(messages) {
191
+ return messages.flatMap((message) => {
192
+ const date = new Date(message.createdAt).toISOString();
193
+ const parts = [
194
+ {
195
+ type: "text",
196
+ text: `--- message boundary (${date}) ---\n${message.role.toUpperCase()} [${message.id}]\n${message.textPreview}`,
197
+ },
198
+ ];
199
+ parts.push(...message.content.filter(isImageContent));
200
+ return parts;
201
+ });
202
+ }
203
+ function isImageContent(part) {
204
+ return part.type !== "text";
205
+ }
206
+ export function buildReflectorSystemPrompt(instruction) {
207
+ return dedent `
208
+ You are the reflection agent for an observational memory system.
209
+
210
+ Condense and restructure observations while preserving important facts, dates, user preferences, unresolved work, and completion markers.
211
+
212
+ Rules:
213
+ - Keep observations useful to the acting assistant.
214
+ - Deduplicate repeated facts.
215
+ - Preserve chronology and concrete details.
216
+ - Preserve observation group headings/ranges when possible.
217
+ - Do not invent details.
218
+ ${instruction ? `\nCustom instructions:\n${instruction}` : ""}
219
+ `;
220
+ }
221
+ export function buildReflectorPrompt(observations, targetTokens, retry) {
222
+ const budgetInstruction = retry
223
+ ? dedent `
224
+ The previous reflected observation log was approximately ${retry.actualTokens.toLocaleString("en-US")} tokens, which exceeded the ${targetTokens.toLocaleString("en-US")}-token budget.
225
+
226
+ Retry with a shorter reflected observation log under approximately ${targetTokens.toLocaleString("en-US")} tokens. Preserve high-priority facts, unresolved work, concrete decisions, chronology, and completion markers first.
227
+ `
228
+ : `Target budget: keep the reflected observation log under approximately ${targetTokens.toLocaleString("en-US")} tokens.`;
229
+ return dedent `
230
+ Reflect on these observations and return a condensed observation log.
231
+
232
+ ${budgetInstruction}
233
+
234
+ ${observations}
235
+ `;
236
+ }
237
+ //# sourceMappingURL=observational-prompts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observational-prompts.js","sourceRoot":"","sources":["../../../src/memory/observational-prompts.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAgB5B,MAAM,CAAC,MAAM,6BAA6B,GAAG,MAAM,CAAA;;;;;;;;CAQlD,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GACrC,6FAA6F,CAAC;AAEhG,MAAM,CAAC,MAAM,gCAAgC,GAAG,MAAM,CAAA;;;;;;;;;;CAUrD,CAAC;AAEF,MAAM,gCAAgC,GAAG,MAAM,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqC9C,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAA;;;;;;;;;;;;;;;;;;;CAmBxC,CAAC;AAEF,MAAM,UAAU,yBAAyB,CAAC,kBAAkB,GAAG,KAAK;IAClE,MAAM,kBAAkB,GAAG,kBAAkB;QAC3C,CAAC,CAAC,MAAM,CAAA;;OAEL;QACH,CAAC,CAAC,EAAE,CAAC;IAEP,OAAO,MAAM,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA4BT,kBAAkB;GACrB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,WAAoB,EACpB,kBAAkB,GAAG,KAAK;IAE1B,OAAO,MAAM,CAAA;;;;;MAKT,gCAAgC;;;;;;MAMhC,yBAAyB,CAAC,kBAAkB,CAAC;;;;MAI7C,mBAAmB;;;;;;;;;;;MAWnB,WAAW,CAAC,CAAC,CAAC,sCAAsC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE;GACzE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,mBAAmB,CACjC,QAA4B,EAC5B,oBAA4B,EAC5B,YAAoB,EACpB,KAA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AO,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC;QACtD,OAAO,KAAK,CAAC;IACf,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,cAAc,CAAC,IAAgC;IACtD,OAAO,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC;AAC9B,CAAC;AAED,MAAM,UAAU,0BAA0B,CAAC,WAAoB;IAC7D,OAAO,MAAM,CAAA;;;;;;;;;;;MAWT,WAAW,CAAC,CAAC,CAAC,2BAA2B,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE;GAC9D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,YAAoB,EACpB,YAAoB,EACpB,KAAgC;IAEhC,MAAM,iBAAiB,GAAG,KAAK;QAC7B,CAAC,CAAC,MAAM,CAAA;mEACuD,KAAK,CAAC,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC,+BAA+B,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC;;6EAEnG,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC;OAC1G;QACH,CAAC,CAAC,yEAAyE,YAAY,CAAC,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC;IAE5H,OAAO,MAAM,CAAA;;;MAGT,iBAAiB;;MAEjB,YAAY;GACf,CAAC;AACJ,CAAC"}
@@ -0,0 +1,63 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { Model, Usage } from "@earendil-works/pi-ai";
3
+ import type { MemoryStore } from "./store.js";
4
+ import type { ObservationalMemoryActivityEvent, ObservationalMemorySettings, ObservationalMemorySettingsInput } from "../types/memory.js";
5
+ import { type RawMemoryMessage } from "./observational-prompts.js";
6
+ export declare const OBSERVATIONAL_MEMORY_DEFAULTS: {
7
+ readonly observation: {
8
+ readonly messageTokens: 100000;
9
+ readonly maxTokensPerBatch: 35000;
10
+ readonly bufferActivation: 30000;
11
+ };
12
+ readonly reflection: {
13
+ readonly observationTokens: 60000;
14
+ readonly bufferActivation: 40000;
15
+ };
16
+ };
17
+ export interface ObserverResult {
18
+ /** New observation log text extracted from raw messages. */
19
+ observations: string;
20
+ /** Current task state distilled for continuity and optional thread metadata. */
21
+ currentTask?: string;
22
+ /** Hint for the actor's next response after context has been compressed. */
23
+ suggestedContinuation?: string;
24
+ /** Optional short title when the observer is asked to name the session/thread. */
25
+ threadTitle?: string;
26
+ }
27
+ export interface ReflectorResult {
28
+ /** Condensed observation log produced from existing observations. */
29
+ observations: string;
30
+ /** Hint for the actor's next response after reflection rewrites memory. */
31
+ suggestedContinuation?: string;
32
+ }
33
+ export interface ModelByInputTokensConfig {
34
+ upTo: Record<number, Model<any>>;
35
+ }
36
+ export declare class ModelByInputTokens {
37
+ private readonly thresholds;
38
+ constructor(config: ModelByInputTokensConfig);
39
+ resolve(inputTokens: number): Model<any>;
40
+ getThresholds(): number[];
41
+ }
42
+ export interface ObservationalMemoryTransformOptions {
43
+ memory: MemoryStore;
44
+ actorModel: string;
45
+ settings?: ObservationalMemorySettingsInput;
46
+ onUsage?: (usage: Usage) => void;
47
+ onActivity?: (event: ObservationalMemoryActivityEvent) => void;
48
+ }
49
+ export declare function resolveObservationalMemorySettings(input?: ObservationalMemorySettingsInput): ObservationalMemorySettings;
50
+ export declare function validateObservationalMemorySettings(settings: ObservationalMemorySettings): void;
51
+ export declare function createObservationalMemoryTransform(options: ObservationalMemoryTransformOptions): (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
52
+ export declare function optimizeObservationsForContext(observations: string): string;
53
+ export declare function enforceObservationTokenBudget(options: {
54
+ text: string;
55
+ targetTokens: number;
56
+ retry: (actualTokens: number) => Promise<string>;
57
+ }): Promise<string>;
58
+ export declare function trimObservationTextToTokenBudget(text: string, targetTokens: number): string;
59
+ export declare function includeToolPairMessages(messages: AgentMessage[], retainedIds: Set<RawMemoryMessage["id"]>): void;
60
+ export declare function agentMessagesToRaw(messages: AgentMessage[]): RawMemoryMessage[];
61
+ export declare function agentMessageToRaw(message: AgentMessage): RawMemoryMessage | undefined;
62
+ export declare function sanitizeObservationLines(observations: string): string;
63
+ //# sourceMappingURL=observational.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observational.d.ts","sourceRoot":"","sources":["../../../src/memory/observational.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAgB,KAAK,EAAe,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAIrF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,KAAK,EAGV,gCAAgC,EAChC,2BAA2B,EAC3B,gCAAgC,EACjC,MAAM,oBAAoB,CAAC;AAQ5B,OAAO,EAQL,KAAK,gBAAgB,EACtB,MAAM,4BAA4B,CAAC;AAEpC,eAAO,MAAM,6BAA6B;;;;;;;;;;CAmBhC,CAAC;AAEX,MAAM,WAAW,cAAc;IAC7B,4DAA4D;IAC5D,YAAY,EAAE,MAAM,CAAC;IACrB,gFAAgF;IAChF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4EAA4E;IAC5E,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,kFAAkF;IAClF,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAMD,MAAM,WAAW,eAAe;IAC9B,qEAAqE;IACrE,YAAY,EAAE,MAAM,CAAC;IACrB,2EAA2E;IAC3E,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AA0CD,MAAM,WAAW,wBAAwB;IACvC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;CAClC;AAED,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA8C;gBAE7D,MAAM,EAAE,wBAAwB;IAkB5C,OAAO,CAAC,WAAW,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC;IAYxC,aAAa,IAAI,M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