@haikeilabs/agentware 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +45 -0
  2. package/dist/evals/cases/file_search.d.ts +4 -0
  3. package/dist/evals/cases/file_search.d.ts.map +1 -0
  4. package/dist/evals/cases/file_search.js +99 -0
  5. package/dist/evals/cases/general.d.ts +4 -0
  6. package/dist/evals/cases/general.d.ts.map +1 -0
  7. package/dist/evals/cases/general.js +113 -0
  8. package/dist/evals/index.d.ts +5 -0
  9. package/dist/evals/index.d.ts.map +1 -0
  10. package/dist/evals/index.js +4 -0
  11. package/dist/evals/main.d.ts +2 -0
  12. package/dist/evals/main.d.ts.map +1 -0
  13. package/dist/evals/main.js +109 -0
  14. package/dist/evals/models.d.ts +38 -0
  15. package/dist/evals/models.d.ts.map +1 -0
  16. package/dist/evals/models.js +69 -0
  17. package/dist/evals/runner.d.ts +40 -0
  18. package/dist/evals/runner.d.ts.map +1 -0
  19. package/dist/evals/runner.js +131 -0
  20. package/dist/executor/executor.d.ts +42 -0
  21. package/dist/executor/executor.d.ts.map +1 -0
  22. package/dist/executor/executor.js +63 -0
  23. package/dist/executor/index.d.ts +2 -0
  24. package/dist/executor/index.d.ts.map +1 -0
  25. package/dist/executor/index.js +1 -0
  26. package/dist/index.d.ts +10 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +9 -0
  29. package/dist/jobs/index.d.ts +3 -0
  30. package/dist/jobs/index.d.ts.map +1 -0
  31. package/dist/jobs/index.js +2 -0
  32. package/dist/jobs/job.d.ts +18 -0
  33. package/dist/jobs/job.d.ts.map +1 -0
  34. package/dist/jobs/job.js +20 -0
  35. package/dist/jobs/manager.d.ts +23 -0
  36. package/dist/jobs/manager.d.ts.map +1 -0
  37. package/dist/jobs/manager.js +63 -0
  38. package/dist/llm/backend.d.ts +9 -0
  39. package/dist/llm/backend.d.ts.map +1 -0
  40. package/dist/llm/backend.js +1 -0
  41. package/dist/llm/index.d.ts +4 -0
  42. package/dist/llm/index.d.ts.map +1 -0
  43. package/dist/llm/index.js +1 -0
  44. package/dist/llm/request.d.ts +28 -0
  45. package/dist/llm/request.d.ts.map +1 -0
  46. package/dist/llm/request.js +7 -0
  47. package/dist/llm/response.d.ts +17 -0
  48. package/dist/llm/response.d.ts.map +1 -0
  49. package/dist/llm/response.js +1 -0
  50. package/dist/llmcontext/context_window.d.ts +36 -0
  51. package/dist/llmcontext/context_window.d.ts.map +1 -0
  52. package/dist/llmcontext/context_window.js +115 -0
  53. package/dist/llmcontext/index.d.ts +4 -0
  54. package/dist/llmcontext/index.d.ts.map +1 -0
  55. package/dist/llmcontext/index.js +3 -0
  56. package/dist/llmcontext/manager.d.ts +27 -0
  57. package/dist/llmcontext/manager.d.ts.map +1 -0
  58. package/dist/llmcontext/manager.js +27 -0
  59. package/dist/llmcontext/strategies.d.ts +21 -0
  60. package/dist/llmcontext/strategies.d.ts.map +1 -0
  61. package/dist/llmcontext/strategies.js +180 -0
  62. package/dist/memory/client.d.ts +107 -0
  63. package/dist/memory/client.d.ts.map +1 -0
  64. package/dist/memory/client.js +210 -0
  65. package/dist/memory/index.d.ts +5 -0
  66. package/dist/memory/index.d.ts.map +1 -0
  67. package/dist/memory/index.js +2 -0
  68. package/dist/memory/tools.d.ts +22 -0
  69. package/dist/memory/tools.d.ts.map +1 -0
  70. package/dist/memory/tools.js +57 -0
  71. package/dist/middleware/audit.d.ts +27 -0
  72. package/dist/middleware/audit.d.ts.map +1 -0
  73. package/dist/middleware/audit.js +26 -0
  74. package/dist/middleware/guardrails/error_tracker.d.ts +34 -0
  75. package/dist/middleware/guardrails/error_tracker.d.ts.map +1 -0
  76. package/dist/middleware/guardrails/error_tracker.js +70 -0
  77. package/dist/middleware/guardrails/nudge.d.ts +17 -0
  78. package/dist/middleware/guardrails/nudge.d.ts.map +1 -0
  79. package/dist/middleware/guardrails/nudge.js +67 -0
  80. package/dist/middleware/guardrails/response_validator.d.ts +29 -0
  81. package/dist/middleware/guardrails/response_validator.d.ts.map +1 -0
  82. package/dist/middleware/guardrails/response_validator.js +145 -0
  83. package/dist/middleware/guardrails/step_enforcer.d.ts +20 -0
  84. package/dist/middleware/guardrails/step_enforcer.d.ts.map +1 -0
  85. package/dist/middleware/guardrails/step_enforcer.js +65 -0
  86. package/dist/middleware/index.d.ts +5 -0
  87. package/dist/middleware/index.d.ts.map +1 -0
  88. package/dist/middleware/index.js +4 -0
  89. package/dist/middleware/inference.d.ts +28 -0
  90. package/dist/middleware/inference.d.ts.map +1 -0
  91. package/dist/middleware/inference.js +141 -0
  92. package/dist/middleware/middleware.d.ts +22 -0
  93. package/dist/middleware/middleware.d.ts.map +1 -0
  94. package/dist/middleware/middleware.js +51 -0
  95. package/dist/middleware/policy.d.ts +46 -0
  96. package/dist/middleware/policy.d.ts.map +1 -0
  97. package/dist/middleware/policy.js +122 -0
  98. package/dist/middleware/types.d.ts +42 -0
  99. package/dist/middleware/types.d.ts.map +1 -0
  100. package/dist/middleware/types.js +36 -0
  101. package/dist/prompts/generator.d.ts +10 -0
  102. package/dist/prompts/generator.d.ts.map +1 -0
  103. package/dist/prompts/generator.js +24 -0
  104. package/dist/prompts/index.d.ts +2 -0
  105. package/dist/prompts/index.d.ts.map +1 -0
  106. package/dist/prompts/index.js +1 -0
  107. package/dist/toolformat/formatter.d.ts +20 -0
  108. package/dist/toolformat/formatter.d.ts.map +1 -0
  109. package/dist/toolformat/formatter.js +22 -0
  110. package/dist/toolformat/index.d.ts +2 -0
  111. package/dist/toolformat/index.d.ts.map +1 -0
  112. package/dist/toolformat/index.js +1 -0
  113. package/dist/tools/async.d.ts +42 -0
  114. package/dist/tools/async.d.ts.map +1 -0
  115. package/dist/tools/async.js +89 -0
  116. package/dist/tools/index.d.ts +5 -0
  117. package/dist/tools/index.d.ts.map +1 -0
  118. package/dist/tools/index.js +3 -0
  119. package/dist/tools/registry.d.ts +11 -0
  120. package/dist/tools/registry.d.ts.map +1 -0
  121. package/dist/tools/registry.js +27 -0
  122. package/dist/tools/tool.d.ts +29 -0
  123. package/dist/tools/tool.d.ts.map +1 -0
  124. package/dist/tools/tool.js +31 -0
  125. package/package.json +49 -0
@@ -0,0 +1,115 @@
1
+ import { TieredCompact } from "./strategies.js";
2
+ export function defaultContextWarning(tokens, budget, pct) {
3
+ if (pct >= 0.8) {
4
+ return "[Context is nearly full. Summarize critical findings and complete current task.]";
5
+ }
6
+ if (pct >= 0.65) {
7
+ return "[Context is filling up. Be concise and front-load important information.]";
8
+ }
9
+ return null;
10
+ }
11
+ export class ContextWindowManager {
12
+ contextWindow;
13
+ compactionRatio;
14
+ counter;
15
+ strategy;
16
+ lastKnownTokens;
17
+ contextThresholds;
18
+ onContextThreshold;
19
+ firedThresholds;
20
+ onCompact;
21
+ constructor(contextWindow, counter = null, strategy = null, contextThresholds = null, onContextThreshold = null, onCompact = null) {
22
+ this.contextWindow = contextWindow;
23
+ this.compactionRatio = 0.75;
24
+ this.counter = counter ?? defaultCounter;
25
+ this.strategy = strategy ?? new TieredCompact();
26
+ this.lastKnownTokens = null;
27
+ this.contextThresholds = contextThresholds
28
+ ? [...contextThresholds].sort((a, b) => a - b)
29
+ : [0.65, 0.8];
30
+ this.onContextThreshold = onContextThreshold ?? defaultContextWarning;
31
+ this.firedThresholds = new Set();
32
+ this.onCompact = onCompact;
33
+ }
34
+ setCompactionRatio(ratio) {
35
+ this.compactionRatio = ratio;
36
+ }
37
+ updateTokenCount(totalTokens) {
38
+ this.lastKnownTokens = totalTokens;
39
+ }
40
+ check(messages) {
41
+ const currentTokens = this.estimateTokens(messages);
42
+ const threshold = Math.floor(this.contextWindow * this.compactionRatio);
43
+ return [currentTokens, currentTokens >= threshold];
44
+ }
45
+ shouldCompact(messages) {
46
+ const currentTokens = this.estimateTokens(messages);
47
+ const threshold = Math.floor(this.contextWindow * this.compactionRatio);
48
+ return currentTokens > threshold;
49
+ }
50
+ compact(messages) {
51
+ const tokensBefore = this.estimateTokens(messages);
52
+ const messagesBefore = messages.length;
53
+ const targetTokens = Math.floor(this.contextWindow * this.compactionRatio);
54
+ const compacted = this.strategy.compact(messages, targetTokens, this.counter);
55
+ const tokensAfter = this.counter(compacted);
56
+ const messagesAfter = compacted.length;
57
+ let phaseReached = 0;
58
+ if (this.strategy instanceof TieredCompact) {
59
+ phaseReached = this.strategy.lastPhase;
60
+ }
61
+ if (this.onCompact !== null) {
62
+ const event = {
63
+ step_index: 0,
64
+ tokens_before: tokensBefore,
65
+ tokens_after: tokensAfter,
66
+ budget_tokens: this.contextWindow,
67
+ messages_before: messagesBefore,
68
+ messages_after: messagesAfter,
69
+ phase_reached: phaseReached,
70
+ strategy_name: this.strategy.name(),
71
+ };
72
+ this.onCompact(event);
73
+ }
74
+ this.lastKnownTokens = null;
75
+ this.firedThresholds.clear();
76
+ return compacted;
77
+ }
78
+ checkThresholds(messages) {
79
+ const currentTokens = this.estimateTokens(messages);
80
+ const budget = this.contextWindow;
81
+ if (currentTokens === 0 || budget === 0) {
82
+ return null;
83
+ }
84
+ const pct = currentTokens / budget;
85
+ for (let i = this.contextThresholds.length - 1; i >= 0; i--) {
86
+ const threshold = this.contextThresholds[i];
87
+ if (pct >= threshold) {
88
+ if (!this.firedThresholds.has(threshold)) {
89
+ this.firedThresholds.add(threshold);
90
+ return this.onContextThreshold(currentTokens, budget, pct);
91
+ }
92
+ }
93
+ }
94
+ return null;
95
+ }
96
+ estimateTokens(messages) {
97
+ if (this.lastKnownTokens !== null) {
98
+ return this.lastKnownTokens;
99
+ }
100
+ return this.counter(messages);
101
+ }
102
+ }
103
+ export function defaultCounter(messages) {
104
+ let total = 0;
105
+ for (const m of messages) {
106
+ let overhead = m.role.length + 4;
107
+ if (m.tool_calls) {
108
+ for (const tc of m.tool_calls) {
109
+ overhead += tc.name.length + 1;
110
+ }
111
+ }
112
+ total += Math.floor(m.content.length / 4) + overhead;
113
+ }
114
+ return total;
115
+ }
@@ -0,0 +1,4 @@
1
+ export { ContextManager, InMemoryContextManager, ToolResultEntry, } from "./manager.js";
2
+ export { CompactionStrategy, TieredCompact, TokenCounter, findEligibleEnd, } from "./strategies.js";
3
+ export { ContextWindowManager, CompactEvent, CompactCallback, defaultCounter, defaultContextWarning, ThresholdCallback, } from "./context_window.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/llmcontext/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,eAAe,GAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,eAAe,EACf,cAAc,EACd,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,qBAAqB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { InMemoryContextManager, } from "./manager.js";
2
+ export { TieredCompact, findEligibleEnd, } from "./strategies.js";
3
+ export { ContextWindowManager, defaultCounter, defaultContextWarning, } from "./context_window.js";
@@ -0,0 +1,27 @@
1
+ import type { Message } from "../llm/index.js";
2
+ export interface ToolResultEntry {
3
+ call_id: string;
4
+ tool_name: string;
5
+ args: Record<string, unknown>;
6
+ output: string;
7
+ success: boolean;
8
+ }
9
+ export interface ContextManager {
10
+ appendPrompt(jobId: string, msg: Message): void;
11
+ appendResponse(jobId: string, msg: Message): void;
12
+ appendToolCalls(jobId: string, calls: unknown[]): void;
13
+ appendToolResults(jobId: string, results: ToolResultEntry[]): void;
14
+ getHistory(jobId: string): Message[];
15
+ purge(jobId: string): void;
16
+ }
17
+ export declare class InMemoryContextManager implements ContextManager {
18
+ private history;
19
+ appendPrompt(jobId: string, msg: Message): void;
20
+ appendResponse(jobId: string, msg: Message): void;
21
+ appendToolCalls(_jobId: string, _calls: unknown[]): void;
22
+ appendToolResults(_jobId: string, _results: ToolResultEntry[]): void;
23
+ getHistory(jobId: string): Message[];
24
+ purge(jobId: string): void;
25
+ private ensureHistory;
26
+ }
27
+ //# sourceMappingURL=manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/llmcontext/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;IAChD,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;IAClD,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IACvD,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,EAAE,GAAG,IAAI,CAAC;IACnE,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,EAAE,CAAC;IACrC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,qBAAa,sBAAuB,YAAW,cAAc;IAC3D,OAAO,CAAC,OAAO,CAAqC;IAEpD,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI;IAI/C,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI;IAIjD,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI;IAIxD,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,eAAe,EAAE,GAAG,IAAI;IAIpE,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,EAAE;IAIpC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI1B,OAAO,CAAC,aAAa;CAMtB"}
@@ -0,0 +1,27 @@
1
+ export class InMemoryContextManager {
2
+ history = new Map();
3
+ appendPrompt(jobId, msg) {
4
+ this.ensureHistory(jobId).push(msg);
5
+ }
6
+ appendResponse(jobId, msg) {
7
+ this.ensureHistory(jobId).push(msg);
8
+ }
9
+ appendToolCalls(_jobId, _calls) {
10
+ // Not stored in this implementation
11
+ }
12
+ appendToolResults(_jobId, _results) {
13
+ // Not stored in this implementation
14
+ }
15
+ getHistory(jobId) {
16
+ return this.history.get(jobId) || [];
17
+ }
18
+ purge(jobId) {
19
+ this.history.delete(jobId);
20
+ }
21
+ ensureHistory(jobId) {
22
+ if (!this.history.has(jobId)) {
23
+ this.history.set(jobId, []);
24
+ }
25
+ return this.history.get(jobId);
26
+ }
27
+ }
@@ -0,0 +1,21 @@
1
+ import { Message } from "../llm/request.js";
2
+ export type TokenCounter = (messages: Message[]) => number;
3
+ export interface CompactionStrategy {
4
+ compact(messages: Message[], targetTokens: number, counter: TokenCounter): Message[];
5
+ name(): string;
6
+ }
7
+ export declare class TieredCompact implements CompactionStrategy {
8
+ private keepRecent;
9
+ private truncateChars;
10
+ lastPhase: number;
11
+ constructor(keepRecent?: number, truncateChars?: number);
12
+ name(): string;
13
+ compact(messages: Message[], targetTokens: number, counter: TokenCounter): Message[];
14
+ private protectedSteps;
15
+ private isProtected;
16
+ private phase1Compact;
17
+ private phase2Compact;
18
+ private phase3Compact;
19
+ }
20
+ export declare function findEligibleEnd(messages: Message[], keepRecent: number): number;
21
+ //# sourceMappingURL=strategies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategies.d.ts","sourceRoot":"","sources":["../../src/llmcontext/strategies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG5C,MAAM,MAAM,YAAY,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,KAAK,MAAM,CAAC;AAE3D,MAAM,WAAW,kBAAkB;IACjC,OAAO,CACL,QAAQ,EAAE,OAAO,EAAE,EACnB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,YAAY,GACpB,OAAO,EAAE,CAAC;IACb,IAAI,IAAI,MAAM,CAAC;CAChB;AAUD,qBAAa,aAAc,YAAW,kBAAkB;IACtD,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,aAAa,CAAS;IACvB,SAAS,EAAE,MAAM,CAAK;gBAEjB,UAAU,SAAI,EAAE,aAAa,SAAM;IAK/C,IAAI,IAAI,MAAM;IAId,OAAO,CACL,QAAQ,EAAE,OAAO,EAAE,EACnB,YAAY,EAAE,MAAM,EACpB,OAAO,EAAE,YAAY,GACpB,OAAO,EAAE;IAoCZ,OAAO,CAAC,cAAc;IAsCtB,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,aAAa;IAyCrB,OAAO,CAAC,aAAa;IA+BrB,OAAO,CAAC,aAAa;CA+BtB;AAED,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,OAAO,EAAE,EACnB,UAAU,EAAE,MAAM,GACjB,MAAM,CAmCR"}
@@ -0,0 +1,180 @@
1
+ import { MessageType } from "../middleware/types.js";
2
+ function isNudgeType(msgType) {
3
+ return (msgType === MessageType.STEP_NUDGE ||
4
+ msgType === MessageType.RETRY_NUDGE ||
5
+ msgType === MessageType.PREREQUISITE_NUDGE);
6
+ }
7
+ export class TieredCompact {
8
+ keepRecent;
9
+ truncateChars;
10
+ lastPhase = 0;
11
+ constructor(keepRecent = 2, truncateChars = 200) {
12
+ this.keepRecent = keepRecent;
13
+ this.truncateChars = truncateChars;
14
+ }
15
+ name() {
16
+ return "TieredCompact";
17
+ }
18
+ compact(messages, targetTokens, counter) {
19
+ this.lastPhase = 0;
20
+ if (!messages || messages.length === 0) {
21
+ return [];
22
+ }
23
+ const result = [...messages];
24
+ const eligibleEnd = findEligibleEnd(result, this.keepRecent);
25
+ let currentTokens = counter(result);
26
+ if (currentTokens <= targetTokens) {
27
+ return result;
28
+ }
29
+ const phase1Result = this.phase1Compact(result, eligibleEnd, counter);
30
+ currentTokens = counter(phase1Result);
31
+ this.lastPhase = 1;
32
+ if (currentTokens <= targetTokens) {
33
+ return phase1Result;
34
+ }
35
+ const phase2Result = this.phase2Compact(phase1Result, eligibleEnd, counter);
36
+ currentTokens = counter(phase2Result);
37
+ this.lastPhase = 2;
38
+ if (currentTokens <= targetTokens) {
39
+ return phase2Result;
40
+ }
41
+ const phase3Result = this.phase3Compact(phase2Result, eligibleEnd, counter);
42
+ this.lastPhase = 3;
43
+ return phase3Result;
44
+ }
45
+ protectedSteps(messages) {
46
+ const protectedSteps = new Map();
47
+ if (this.keepRecent <= 0) {
48
+ return protectedSteps;
49
+ }
50
+ const steps = [];
51
+ const stepSet = new Set();
52
+ for (const m of messages) {
53
+ if (m.meta?.step_index !== undefined && !stepSet.has(m.meta.step_index)) {
54
+ steps.push(m.meta.step_index);
55
+ stepSet.add(m.meta.step_index);
56
+ }
57
+ }
58
+ if (steps.length === 0) {
59
+ return protectedSteps;
60
+ }
61
+ if (this.keepRecent >= steps.length) {
62
+ for (const s of steps) {
63
+ protectedSteps.set(s, true);
64
+ }
65
+ return protectedSteps;
66
+ }
67
+ const startIdx = steps.length - this.keepRecent;
68
+ for (let i = startIdx; i < steps.length; i++) {
69
+ protectedSteps.set(steps[i], true);
70
+ }
71
+ return protectedSteps;
72
+ }
73
+ isProtected(msg, protectedSteps) {
74
+ if (msg.meta?.step_index === undefined) {
75
+ return false;
76
+ }
77
+ return protectedSteps.get(msg.meta.step_index) ?? false;
78
+ }
79
+ phase1Compact(messages, _eligibleEnd, _counter) {
80
+ const result = [];
81
+ const protectedSteps = this.protectedSteps(messages);
82
+ for (let i = 0; i < messages.length; i++) {
83
+ const m = messages[i];
84
+ if (i === 0 || i === 1) {
85
+ result.push(m);
86
+ continue;
87
+ }
88
+ if (this.isProtected(m, protectedSteps)) {
89
+ result.push(m);
90
+ continue;
91
+ }
92
+ if (isNudgeType(m.meta?.type ?? MessageType.USER_INPUT)) {
93
+ continue;
94
+ }
95
+ if (m.meta?.type === MessageType.TOOL_RESULT) {
96
+ if (m.content.length > this.truncateChars) {
97
+ result.push({
98
+ ...m,
99
+ content: m.content.slice(0, this.truncateChars),
100
+ });
101
+ continue;
102
+ }
103
+ }
104
+ result.push(m);
105
+ }
106
+ return result;
107
+ }
108
+ phase2Compact(messages, _eligibleEnd, _counter) {
109
+ const result = [];
110
+ const protectedSteps = this.protectedSteps(messages);
111
+ for (let i = 0; i < messages.length; i++) {
112
+ const m = messages[i];
113
+ if (i === 0 || i === 1) {
114
+ result.push(m);
115
+ continue;
116
+ }
117
+ if (this.isProtected(m, protectedSteps)) {
118
+ result.push(m);
119
+ continue;
120
+ }
121
+ if (m.meta?.type === MessageType.TOOL_RESULT) {
122
+ continue;
123
+ }
124
+ result.push(m);
125
+ }
126
+ return result;
127
+ }
128
+ phase3Compact(messages, _eligibleEnd, _counter) {
129
+ const result = [];
130
+ const protectedSteps = this.protectedSteps(messages);
131
+ for (let i = 0; i < messages.length; i++) {
132
+ const m = messages[i];
133
+ if (i === 0 || i === 1) {
134
+ result.push(m);
135
+ continue;
136
+ }
137
+ if (this.isProtected(m, protectedSteps)) {
138
+ result.push(m);
139
+ continue;
140
+ }
141
+ const msgType = m.meta?.type ?? MessageType.TEXT_RESPONSE;
142
+ if (msgType === MessageType.REASONING || msgType === MessageType.TEXT_RESPONSE) {
143
+ continue;
144
+ }
145
+ result.push(m);
146
+ }
147
+ return result;
148
+ }
149
+ }
150
+ export function findEligibleEnd(messages, keepRecent) {
151
+ if (keepRecent <= 0) {
152
+ return messages.length - 1;
153
+ }
154
+ let maxStep = -1;
155
+ for (const m of messages) {
156
+ if (m.meta?.step_index !== undefined && m.meta.step_index > maxStep) {
157
+ maxStep = m.meta.step_index;
158
+ }
159
+ }
160
+ if (maxStep < 0) {
161
+ const protectedCount = Math.min(keepRecent, messages.length);
162
+ return messages.length - 1 - protectedCount;
163
+ }
164
+ const protectedSteps = new Map();
165
+ let currentStep = maxStep;
166
+ for (let i = 0; i < keepRecent; i++) {
167
+ protectedSteps.set(currentStep, true);
168
+ currentStep--;
169
+ if (currentStep < 0) {
170
+ break;
171
+ }
172
+ }
173
+ for (let i = messages.length - 1; i >= 0; i--) {
174
+ const stepIdx = messages[i].meta?.step_index;
175
+ if (stepIdx === undefined || !protectedSteps.get(stepIdx)) {
176
+ return i;
177
+ }
178
+ }
179
+ return -1;
180
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Wiki memory - TypeScript client for the Go core's ontology-constrained
3
+ * wiki memory.
4
+ *
5
+ * WikiMemory spawns the Go MCP stdio server (`memctl serve`) scoped to one
6
+ * user. The subprocess owns enforcement: every call passes the Go
7
+ * middleware chain (declarative policy + ontology evaluator + audit), and
8
+ * in-band attempts to change user scope are denied. The API is async
9
+ * (subprocess I/O); inference stays in the Python SDK.
10
+ *
11
+ * ## Providing Your Own Ontology
12
+ *
13
+ * The T-box (schema) is fully composable — pass paths to your own TTL files.
14
+ * Multiple files are merged. Use absolute paths or paths relative to your
15
+ * working directory.
16
+ *
17
+ * Example TTL file (my-ontology.ttl):
18
+ * ```turtle
19
+ * @prefix ex: <http://example.org/> .
20
+ * @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
21
+ * @prefix owl: <http://www.w3.org/2002/07/owl#> .
22
+ *
23
+ * ex:Project a owl:Class ;
24
+ * rdfs:label "Project"@en ;
25
+ * rdfs:comment "A software project" .
26
+ *
27
+ * ex:Task a owl:Class ;
28
+ * rdfs:label "Task"@en ;
29
+ * rdfs:subClassOf ex:Project .
30
+ *
31
+ * ex:hasStatus a owl:ObjectProperty ;
32
+ * rdfs:domain ex:Project ;
33
+ * rdfs:range ex:Status .
34
+ *
35
+ * ex:Status a owl:Class ;
36
+ * rdfs:label "Status"@en .
37
+ * ```
38
+ *
39
+ * Example usage:
40
+ * ```typescript
41
+ * const wiki = new WikiMemory({
42
+ * userId: "alice",
43
+ * root: "./memory",
44
+ * tboxPaths: [
45
+ * "./my-ontology.ttl", // your custom ontology
46
+ * "./shared-skills.ttl", // another TTL file
47
+ * ],
48
+ * });
49
+ * ```
50
+ *
51
+ * The repo includes example ontologies in `ontologies/`:
52
+ * - `ontologies/education/TBOX_LEARNING_SOFTWARE.ttl` (learning software concepts)
53
+ * - `ontologies/social/twitch_topics.ttl` (SKOS concepts)
54
+ * - `ontologies/thesaurus/*.ttl` (SKOS testing)
55
+ */
56
+ export declare const MEMORY_TOOLS: readonly ["memory_ingest", "memory_write_page", "memory_query", "memory_get_claims", "memory_lint"];
57
+ export declare const DIAGNOSTICS_MARKER = "diagnostics: ";
58
+ /** Structured ontology violation from a DENY decision. */
59
+ export interface DiagnosticViolation {
60
+ constraint: string;
61
+ term: string;
62
+ message: string;
63
+ nearest: string[];
64
+ }
65
+ /** Extract structured violations from a deny reason, if present. */
66
+ export declare function parseDiagnostics(errorText: string): DiagnosticViolation[];
67
+ export declare class MemoryServerError extends Error {
68
+ }
69
+ export interface WikiMemoryOptions {
70
+ userId: string;
71
+ root: string;
72
+ tboxPaths: string[];
73
+ /** Path to the memctl binary; defaults to $PEDRO_MEMCTL or "memctl". */
74
+ memctlPath?: string;
75
+ sessionId?: string;
76
+ }
77
+ /** Result triple matching the SDK's executor convention. */
78
+ export type ToolResult = [unknown, boolean, string];
79
+ export declare class WikiMemory {
80
+ readonly userId: string;
81
+ private proc;
82
+ private lines;
83
+ private pending;
84
+ private nextId;
85
+ private ready;
86
+ constructor(options: WikiMemoryOptions);
87
+ private onLine;
88
+ private failAll;
89
+ private notify;
90
+ private request;
91
+ /** Execute a memory tool. Resolves to [outputText, success, error]. */
92
+ execute(toolName: string, args: Record<string, unknown>): Promise<ToolResult>;
93
+ /** List the memory tools served by the core. */
94
+ tools(): Promise<Array<{
95
+ name: string;
96
+ description: string;
97
+ }>>;
98
+ ingest(sourceId: string, text: string): Promise<ToolResult>;
99
+ writePage(content: string): Promise<ToolResult>;
100
+ query(question: string): Promise<ToolResult>;
101
+ getClaims(pageId?: string): Promise<ToolResult>;
102
+ lint(): Promise<ToolResult>;
103
+ private parsed;
104
+ /** Terminate the memory server subprocess. */
105
+ close(): void;
106
+ }
107
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/memory/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AAKH,eAAO,MAAM,YAAY,qGAMf,CAAC;AAEX,eAAO,MAAM,kBAAkB,kBAAkB,CAAC;AAElD,0DAA0D;AAC1D,MAAM,WAAW,mBAAmB;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,oEAAoE;AACpE,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,mBAAmB,EAAE,CAgBzE;AAED,qBAAa,iBAAkB,SAAQ,KAAK;CAAG;AAE/C,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,wEAAwE;IACxE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,4DAA4D;AAC5D,MAAM,MAAM,UAAU,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAQpD,qBAAa,UAAU;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,IAAI,CAAiC;IAC7C,OAAO,CAAC,KAAK,CAAY;IACzB,OAAO,CAAC,OAAO,CAGP;IACR,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,KAAK,CAAgB;gBAEjB,OAAO,EAAE,iBAAiB;IA2BtC,OAAO,CAAC,MAAM;IAoBd,OAAO,CAAC,OAAO;IAMf,OAAO,CAAC,MAAM;IAId,OAAO,CAAC,OAAO;IAYf,uEAAuE;IACjE,OAAO,CACX,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5B,OAAO,CAAC,UAAU,CAAC;IAetB,gDAAgD;IAC1C,KAAK,IAAI,OAAO,CAAC,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAM9D,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAI3D,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAI/C,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAI5C,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAM/C,IAAI,IAAI,OAAO,CAAC,UAAU,CAAC;IAIjC,OAAO,CAAC,MAAM;IASd,8CAA8C;IAC9C,KAAK,IAAI,IAAI;CAId"}