aismemory 0.8.7 → 0.8.9
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 +3 -2
- package/dist/agent-key-mode.js +5 -1
- package/dist/auto-handoff.d.ts +5 -1
- package/dist/auto-handoff.js +12 -2
- package/dist/cli/setup-core.js +149 -1
- package/dist/cli/sync-memory.js +7 -2
- package/dist/cli-info.js +4 -0
- package/dist/index.js +106 -25
- package/dist/mcp/tools.d.ts +2 -0
- package/dist/mcp/tools.js +8 -1
- package/dist/pending-device-flow.d.ts +2 -0
- package/dist/pending-device-flow.js +1 -0
- package/dist/pipeline/bulk-store.d.ts +4 -3
- package/dist/pipeline/bulk-store.js +45 -8
- package/dist/pipeline/ingestion.d.ts +1 -0
- package/dist/pipeline/ingestion.js +6 -1
- package/dist/pipeline/types.d.ts +2 -0
- package/dist/run-pass-mode.js +5 -1
- package/dist/session-identity.js +1 -0
- package/dist/tool-args.d.ts +6 -0
- package/dist/tool-args.js +7 -0
- package/dist/workspace-key-mode.js +5 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ Add to your IDE's MCP server config:
|
|
|
37
37
|
"mcpServers": {
|
|
38
38
|
"aismemory": {
|
|
39
39
|
"command": "npx",
|
|
40
|
-
"args": ["aismemory@0.8.
|
|
40
|
+
"args": ["aismemory@0.8.9"],
|
|
41
41
|
"env": {
|
|
42
42
|
"npm_config_audit": "false",
|
|
43
43
|
"npm_config_fund": "false"
|
|
@@ -117,6 +117,7 @@ unreachable, they print one warning line and let the session carry on.
|
|
|
117
117
|
| `goal_create` | Create a new goal for the current agent |
|
|
118
118
|
| `goal_list` | List goals for the current agent, with status/parent filters |
|
|
119
119
|
| `goal_update_progress` | Update a goal's progress (0-100) |
|
|
120
|
+
| `goal_activate` | Activate one of your own draft goals so it shows in your context |
|
|
120
121
|
| `goal_complete` | Mark a goal complete (success or failure) |
|
|
121
122
|
| `operating_layer_put` | Store one rule or skill in this agent's OWN operating layer, so it loads in every tool connected to the agent (`full_context` / `agent_load`). Agent API key only; takes no agent argument; only when the human asked |
|
|
122
123
|
| `agent_archive` | Archive one of your own agents by id. Restorable; nothing is deleted. Owner sign-in only |
|
|
@@ -324,7 +325,7 @@ mint a new one.
|
|
|
324
325
|
"mcpServers": {
|
|
325
326
|
"aismemory": {
|
|
326
327
|
"command": "npx",
|
|
327
|
-
"args": ["aismemory@0.8.
|
|
328
|
+
"args": ["aismemory@0.8.9"],
|
|
328
329
|
"env": {
|
|
329
330
|
"AIS_WORKSPACE_KEY": "ais_wk_...",
|
|
330
331
|
"AIS_AGENT_ID": "<the agent to start with>",
|
package/dist/agent-key-mode.js
CHANGED
|
@@ -27,7 +27,7 @@ import { emitTelemetry } from './telemetry.js';
|
|
|
27
27
|
import { retryAfterOf, shouldHonourRetryAfter, sleepSeconds } from './retry-after.js';
|
|
28
28
|
import { getAisRequestTimeoutMs, toAisRequestError } from './request-timeout.js';
|
|
29
29
|
import { withDeclaredAgent } from './declared-agent.js';
|
|
30
|
-
import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseInboxSendArgs, parseInboxReadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalCompleteArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
|
|
30
|
+
import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseInboxSendArgs, parseInboxReadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
|
|
31
31
|
import { readInboxAndMaybeAck } from './inbox-client.js';
|
|
32
32
|
import { AGENT_ARCHIVE_KEY_MODE_DETAIL } from './agent-archive.js';
|
|
33
33
|
import { OPERATING_LAYER_PUT_TOOL, putOperatingLayerEntry } from './operating-layer-write.js';
|
|
@@ -351,6 +351,10 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
|
|
|
351
351
|
progress: args.progress,
|
|
352
352
|
}, fetchImpl);
|
|
353
353
|
}
|
|
354
|
+
case 'goal_activate': {
|
|
355
|
+
const args = parseGoalActivateArgs(rawArgs);
|
|
356
|
+
return aisKeyPost(aisUrl, `/v1/agents/${agentId}/goals/${args.goalId}/activate`, apiKey, {}, fetchImpl);
|
|
357
|
+
}
|
|
354
358
|
case 'goal_complete': {
|
|
355
359
|
const args = parseGoalCompleteArgs(rawArgs);
|
|
356
360
|
return aisKeyPost(aisUrl, `/v1/agents/${agentId}/goals/${args.goalId}/complete`, apiKey, {
|
package/dist/auto-handoff.d.ts
CHANGED
|
@@ -8,10 +8,14 @@ export declare class ActivityTracker {
|
|
|
8
8
|
getStoredMemoryCount(): number;
|
|
9
9
|
getStoredMemories(): string[];
|
|
10
10
|
hasActivity(): boolean;
|
|
11
|
+
/** Drop everything recorded so far; used when the session switches agents. */
|
|
12
|
+
reset(): void;
|
|
11
13
|
}
|
|
12
14
|
export interface HandoffPayload {
|
|
13
15
|
summary: string;
|
|
14
16
|
keyLearnings: string[];
|
|
15
17
|
}
|
|
16
18
|
export declare function buildHandoffPayload(tracker: ActivityTracker): HandoffPayload;
|
|
17
|
-
export declare function setupAutoHandoff(aisUrl: string, agentId: string, token: string, tracker: ActivityTracker,
|
|
19
|
+
export declare function setupAutoHandoff(aisUrl: string, agentId: string, token: string, tracker: ActivityTracker,
|
|
20
|
+
/** Called once at exit; `saved` is true only when the server accepted the handoff. */
|
|
21
|
+
onBeforeExit?: (saved: boolean) => void, beforeWrite?: () => Promise<void>): () => void;
|
package/dist/auto-handoff.js
CHANGED
|
@@ -32,6 +32,12 @@ export class ActivityTracker {
|
|
|
32
32
|
hasActivity() {
|
|
33
33
|
return Object.keys(this.toolCounts).length > 0;
|
|
34
34
|
}
|
|
35
|
+
/** Drop everything recorded so far; used when the session switches agents. */
|
|
36
|
+
reset() {
|
|
37
|
+
this.toolCounts = {};
|
|
38
|
+
this.storedMemories = [];
|
|
39
|
+
this.storedMemoryCount = 0;
|
|
40
|
+
}
|
|
35
41
|
}
|
|
36
42
|
export function buildHandoffPayload(tracker) {
|
|
37
43
|
if (!tracker.hasActivity()) {
|
|
@@ -70,7 +76,9 @@ async function describeHandoffFailure(response) {
|
|
|
70
76
|
}
|
|
71
77
|
return `HTTP ${response.status}${detail}`;
|
|
72
78
|
}
|
|
73
|
-
export function setupAutoHandoff(aisUrl, agentId, token, tracker,
|
|
79
|
+
export function setupAutoHandoff(aisUrl, agentId, token, tracker,
|
|
80
|
+
/** Called once at exit; `saved` is true only when the server accepted the handoff. */
|
|
81
|
+
onBeforeExit, beforeWrite) {
|
|
74
82
|
let exiting = false;
|
|
75
83
|
const doHandoff = async () => {
|
|
76
84
|
if (exiting)
|
|
@@ -79,6 +87,7 @@ export function setupAutoHandoff(aisUrl, agentId, token, tracker, onBeforeExit,
|
|
|
79
87
|
if (!tracker.hasActivity())
|
|
80
88
|
return;
|
|
81
89
|
const payload = buildHandoffPayload(tracker);
|
|
90
|
+
let saved = false;
|
|
82
91
|
try {
|
|
83
92
|
if (beforeWrite)
|
|
84
93
|
await beforeWrite();
|
|
@@ -93,6 +102,7 @@ export function setupAutoHandoff(aisUrl, agentId, token, tracker, onBeforeExit,
|
|
|
93
102
|
// handoff and the session exits as though its handoff had landed, which
|
|
94
103
|
// is exactly how a production 500 on this route stayed invisible to
|
|
95
104
|
// every client (tester reconciliation 2026-09-17, defect 2).
|
|
105
|
+
saved = response.ok;
|
|
96
106
|
if (!response.ok) {
|
|
97
107
|
process.stderr.write(`[aismemory] Auto-handoff was NOT saved — the server rejected it (${await describeHandoffFailure(response)}). This session's handoff is lost.\n`);
|
|
98
108
|
}
|
|
@@ -101,7 +111,7 @@ export function setupAutoHandoff(aisUrl, agentId, token, tracker, onBeforeExit,
|
|
|
101
111
|
process.stderr.write(`[aismemory] Auto-handoff stopped: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
102
112
|
}
|
|
103
113
|
if (onBeforeExit)
|
|
104
|
-
onBeforeExit();
|
|
114
|
+
onBeforeExit(saved);
|
|
105
115
|
};
|
|
106
116
|
const onSignal = () => {
|
|
107
117
|
void doHandoff().finally(() => process.exit(0));
|
package/dist/cli/setup-core.js
CHANGED
|
@@ -589,6 +589,14 @@ function isJsonObject(value) {
|
|
|
589
589
|
function deepJsonEqual(a, b) {
|
|
590
590
|
return JSON.stringify(a) === JSON.stringify(b);
|
|
591
591
|
}
|
|
592
|
+
function jsonTextEquals(text, expected) {
|
|
593
|
+
try {
|
|
594
|
+
return deepJsonEqual(JSON.parse(text), expected);
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
592
600
|
function detectJsonIndent(existingJson) {
|
|
593
601
|
const trailingNewline = existingJson.endsWith('\n');
|
|
594
602
|
const firstIndented = existingJson.split('\n').find((line) => /^\s+\S/.test(line));
|
|
@@ -599,6 +607,139 @@ function detectJsonIndent(existingJson) {
|
|
|
599
607
|
const spaces = m?.[1]?.length ?? 2;
|
|
600
608
|
return { space: spaces, trailingNewline };
|
|
601
609
|
}
|
|
610
|
+
function skipJsonWhitespace(text, from) {
|
|
611
|
+
let i = from;
|
|
612
|
+
while (i < text.length && /\s/.test(text.charAt(i)))
|
|
613
|
+
i++;
|
|
614
|
+
return i;
|
|
615
|
+
}
|
|
616
|
+
/** Index just past the string that opens at `open`, or -1 when it never closes. */
|
|
617
|
+
function endOfJsonString(text, open) {
|
|
618
|
+
let i = open + 1;
|
|
619
|
+
while (i < text.length) {
|
|
620
|
+
const ch = text.charAt(i);
|
|
621
|
+
if (ch === '\\')
|
|
622
|
+
i += 2;
|
|
623
|
+
else if (ch === '"')
|
|
624
|
+
return i + 1;
|
|
625
|
+
else
|
|
626
|
+
i++;
|
|
627
|
+
}
|
|
628
|
+
return -1;
|
|
629
|
+
}
|
|
630
|
+
/** Index just past the JSON value that starts at `from`, or -1 when it is malformed. */
|
|
631
|
+
function endOfJsonValue(text, from) {
|
|
632
|
+
const first = text.charAt(from);
|
|
633
|
+
if (first === '"')
|
|
634
|
+
return endOfJsonString(text, from);
|
|
635
|
+
if (first === '{' || first === '[') {
|
|
636
|
+
let depth = 0;
|
|
637
|
+
let i = from;
|
|
638
|
+
while (i < text.length) {
|
|
639
|
+
const ch = text.charAt(i);
|
|
640
|
+
if (ch === '"') {
|
|
641
|
+
i = endOfJsonString(text, i);
|
|
642
|
+
if (i === -1)
|
|
643
|
+
return -1;
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (ch === '{' || ch === '[')
|
|
647
|
+
depth++;
|
|
648
|
+
else if (ch === '}' || ch === ']') {
|
|
649
|
+
depth--;
|
|
650
|
+
if (depth === 0)
|
|
651
|
+
return i + 1;
|
|
652
|
+
}
|
|
653
|
+
i++;
|
|
654
|
+
}
|
|
655
|
+
return -1;
|
|
656
|
+
}
|
|
657
|
+
let i = from;
|
|
658
|
+
while (i < text.length && !/[\s,}\]]/.test(text.charAt(i)))
|
|
659
|
+
i++;
|
|
660
|
+
return i > from ? i : -1;
|
|
661
|
+
}
|
|
662
|
+
/** The direct members of the object whose `{` is at `open`, or null when the text is not plain JSON. */
|
|
663
|
+
function scanJsonObjectMembers(text, open) {
|
|
664
|
+
if (text.charAt(open) !== '{')
|
|
665
|
+
return null;
|
|
666
|
+
const members = [];
|
|
667
|
+
let i = skipJsonWhitespace(text, open + 1);
|
|
668
|
+
if (text.charAt(i) === '}')
|
|
669
|
+
return { members, close: i };
|
|
670
|
+
for (;;) {
|
|
671
|
+
if (text.charAt(i) !== '"')
|
|
672
|
+
return null;
|
|
673
|
+
const keyEnd = endOfJsonString(text, i);
|
|
674
|
+
if (keyEnd === -1)
|
|
675
|
+
return null;
|
|
676
|
+
let key;
|
|
677
|
+
try {
|
|
678
|
+
key = JSON.parse(text.slice(i, keyEnd));
|
|
679
|
+
}
|
|
680
|
+
catch {
|
|
681
|
+
return null;
|
|
682
|
+
}
|
|
683
|
+
const colon = skipJsonWhitespace(text, keyEnd);
|
|
684
|
+
if (text.charAt(colon) !== ':')
|
|
685
|
+
return null;
|
|
686
|
+
const valueStart = skipJsonWhitespace(text, colon + 1);
|
|
687
|
+
const end = endOfJsonValue(text, valueStart);
|
|
688
|
+
if (end === -1)
|
|
689
|
+
return null;
|
|
690
|
+
members.push({ key, start: i, end, valueStart });
|
|
691
|
+
const after = skipJsonWhitespace(text, end);
|
|
692
|
+
if (text.charAt(after) === '}')
|
|
693
|
+
return { members, close: after };
|
|
694
|
+
if (text.charAt(after) !== ',')
|
|
695
|
+
return null;
|
|
696
|
+
i = skipJsonWhitespace(text, after + 1);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
/** The members of the root object's `mcpServers` object, or null when it cannot be located in plain text. */
|
|
700
|
+
function scanMcpServersMembers(text) {
|
|
701
|
+
const rootOpen = skipJsonWhitespace(text, 0);
|
|
702
|
+
const root = scanJsonObjectMembers(text, rootOpen);
|
|
703
|
+
if (root === null)
|
|
704
|
+
return null;
|
|
705
|
+
const servers = root.members.find((m) => m.key === 'mcpServers');
|
|
706
|
+
if (servers === undefined)
|
|
707
|
+
return null;
|
|
708
|
+
return scanJsonObjectMembers(text, servers.valueStart);
|
|
709
|
+
}
|
|
710
|
+
/** Add one server as the last `mcpServers` member by editing the text, or null when the layout is not simple. */
|
|
711
|
+
function insertJsonMcpEntryInPlace(existingJson, serverName, entry, space) {
|
|
712
|
+
const scanned = scanMcpServersMembers(existingJson);
|
|
713
|
+
const last = scanned?.members[scanned.members.length - 1];
|
|
714
|
+
if (scanned === null || last === undefined)
|
|
715
|
+
return null;
|
|
716
|
+
const lineStart = existingJson.lastIndexOf('\n', last.start) + 1;
|
|
717
|
+
const indent = existingJson.slice(lineStart, last.start);
|
|
718
|
+
if (!/^[ \t]+$/.test(indent))
|
|
719
|
+
return null;
|
|
720
|
+
const body = JSON.stringify(entry, null, space)
|
|
721
|
+
.split('\n')
|
|
722
|
+
.map((line, idx) => (idx === 0 ? line : `${indent}${line}`))
|
|
723
|
+
.join('\n');
|
|
724
|
+
return `${existingJson.slice(0, last.end)},\n${indent}${JSON.stringify(serverName)}: ${body}${existingJson.slice(last.end)}`;
|
|
725
|
+
}
|
|
726
|
+
/** Drop one `mcpServers` member by editing the text, or null when the layout is not simple. */
|
|
727
|
+
function removeJsonMcpEntryInPlace(existingJson, serverName) {
|
|
728
|
+
const scanned = scanMcpServersMembers(existingJson);
|
|
729
|
+
if (scanned === null || scanned.members.length < 2)
|
|
730
|
+
return null;
|
|
731
|
+
const idx = scanned.members.findIndex((m) => m.key === serverName);
|
|
732
|
+
const member = scanned.members[idx];
|
|
733
|
+
if (member === undefined)
|
|
734
|
+
return null;
|
|
735
|
+
const previous = scanned.members[idx - 1];
|
|
736
|
+
const next = scanned.members[idx + 1];
|
|
737
|
+
if (next !== undefined)
|
|
738
|
+
return existingJson.slice(0, member.start) + existingJson.slice(next.start);
|
|
739
|
+
if (previous === undefined)
|
|
740
|
+
return null;
|
|
741
|
+
return existingJson.slice(0, previous.end) + existingJson.slice(member.end);
|
|
742
|
+
}
|
|
602
743
|
/** Parse JSON, add only `mcpServers.<name>`, verify no other keys or servers change. */
|
|
603
744
|
function mergeJsonMcpConfigPreserving(existingJson, agentId, version, serverName, configPath) {
|
|
604
745
|
const parsed = parseJsonFile(configPath, existingJson);
|
|
@@ -613,7 +754,10 @@ function mergeJsonMcpConfigPreserving(existingJson, agentId, version, serverName
|
|
|
613
754
|
const nextRoot = { ...parsed, mcpServers: { ...servers, [serverName]: entry } };
|
|
614
755
|
const { space, trailingNewline } = detectJsonIndent(existingJson);
|
|
615
756
|
const serialized = JSON.stringify(nextRoot, null, space);
|
|
616
|
-
const
|
|
757
|
+
const reserialized = trailingNewline ? `${serialized}\n` : serialized;
|
|
758
|
+
// Keep the person's own layout when the entry can be added as plain text and still parses to the same object.
|
|
759
|
+
const inPlace = insertJsonMcpEntryInPlace(existingJson, serverName, entry, space);
|
|
760
|
+
const withNl = inPlace !== null && jsonTextEquals(inPlace, nextRoot) ? inPlace : reserialized;
|
|
617
761
|
let reparsed;
|
|
618
762
|
try {
|
|
619
763
|
reparsed = JSON.parse(withNl);
|
|
@@ -707,6 +851,10 @@ export function removeJsonMcpEntry(existingJson, serverName, configPath, keepEmp
|
|
|
707
851
|
delete root['mcpServers'];
|
|
708
852
|
else
|
|
709
853
|
root['mcpServers'] = merged;
|
|
854
|
+
// Other servers remain: cut the one member out of the text so the file keeps its layout.
|
|
855
|
+
const inPlace = Object.keys(merged).length > 0 ? removeJsonMcpEntryInPlace(existingJson, serverName) : null;
|
|
856
|
+
if (inPlace !== null && jsonTextEquals(inPlace, root))
|
|
857
|
+
return inPlace;
|
|
710
858
|
return stableStringifyMcp(root);
|
|
711
859
|
}
|
|
712
860
|
function codexMcpTableHeader(serverName) {
|
package/dist/cli/sync-memory.js
CHANGED
|
@@ -131,10 +131,15 @@ async function main() {
|
|
|
131
131
|
review,
|
|
132
132
|
});
|
|
133
133
|
process.stdout.write(`\n=== Sync complete ===\n`);
|
|
134
|
-
process.stdout.write(`
|
|
134
|
+
process.stdout.write(`received: ${result.received}\n`);
|
|
135
|
+
process.stdout.write(`stored: ${result.imported}\n`);
|
|
136
|
+
process.stdout.write(`already stored: ${result.deduplicated}\n`);
|
|
137
|
+
process.stdout.write(`rejected: ${result.failed.length}\n`);
|
|
138
|
+
for (const { index, error } of result.failed) {
|
|
139
|
+
process.stdout.write(` - [${index}] ${error}\n`);
|
|
140
|
+
}
|
|
135
141
|
process.stdout.write(`skippedExactDupes: ${result.skippedExactDupes}\n`);
|
|
136
142
|
process.stdout.write(`skippedByUser: ${result.skippedByUser}\n`);
|
|
137
|
-
process.stdout.write(`failed: ${result.failed.length}\n`);
|
|
138
143
|
if (result.warnings.length > 0) {
|
|
139
144
|
process.stdout.write(`\nwarnings:\n`);
|
|
140
145
|
for (const w of result.warnings)
|
package/dist/cli-info.js
CHANGED
|
@@ -37,6 +37,7 @@ export const USAGE_TEXT = [
|
|
|
37
37
|
'',
|
|
38
38
|
'Usage:',
|
|
39
39
|
' aismemory Start the MCP server on stdio',
|
|
40
|
+
' aismemory bond Print the bonding link and exit',
|
|
40
41
|
' aismemory install --identity <agent-id> Write a pinned MCP config for one agent\'s session',
|
|
41
42
|
' aismemory hooks install Add the session-start and pre-compact hook to Claude Code',
|
|
42
43
|
' aismemory enable-key-auth Enroll a device key for silent sign-in',
|
|
@@ -72,6 +73,9 @@ export function resolveInfoRequest(args, version) {
|
|
|
72
73
|
return USAGE_TEXT;
|
|
73
74
|
if (first === '--version' || first === '-v')
|
|
74
75
|
return `${version}\n`;
|
|
76
|
+
if (first === 'bond' && (args[1] === '--help' || args[1] === '-h')) {
|
|
77
|
+
return 'Usage: aismemory bond\n\nPrint the bonding link and exit.\n';
|
|
78
|
+
}
|
|
75
79
|
return null;
|
|
76
80
|
}
|
|
77
81
|
//# sourceMappingURL=cli-info.js.map
|
package/dist/index.js
CHANGED
|
@@ -294,11 +294,11 @@ class BondPendingError extends Error {
|
|
|
294
294
|
* Wire the poll loop onto a freshly built flow. Shared by the mint path and
|
|
295
295
|
* the resume path so a change to the poll/dead bookkeeping lands in one place.
|
|
296
296
|
*/
|
|
297
|
-
function attachDeviceFlowPoll(flow, interval) {
|
|
297
|
+
function attachDeviceFlowPoll(flow, interval, reauth) {
|
|
298
298
|
// flowRef points into the live flow object so auto-restart can update the
|
|
299
299
|
// surfaced URL without the caller needing to restart the MCP process.
|
|
300
300
|
const flowRef = flow;
|
|
301
|
-
const poll = pollForToken(flow.device_code, interval, flow.agent_id, flow.provisional_tenant_id, flowRef);
|
|
301
|
+
const poll = pollForToken(flow.device_code, interval, flow.agent_id, flow.provisional_tenant_id, reauth, flowRef);
|
|
302
302
|
flow.poll = poll;
|
|
303
303
|
// Mark the flow dead as soon as its poll rejects so the next
|
|
304
304
|
// `ensureCredentials` call starts a fresh flow. The `.catch` here is purely
|
|
@@ -342,7 +342,28 @@ function resumeDeviceFlow(saved) {
|
|
|
342
342
|
provisional_tenant_id: saved.provisionalTenantId,
|
|
343
343
|
provisional_token: saved.provisionalToken,
|
|
344
344
|
dead: false,
|
|
345
|
-
}, saved.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_S);
|
|
345
|
+
}, saved.interval ?? DEFAULT_DEVICE_POLL_INTERVAL_S, saved.reauth ?? Boolean(loadAgentPreference()?.agentId));
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Body for `/v1/oauth/device/authorize` (CORBOT-542808CE). When this machine
|
|
349
|
+
* has signed in before (a saved agent id on disk) but reached the device flow
|
|
350
|
+
* anyway, the sign-in expired and no device key covers it: ask for a 'reauth'
|
|
351
|
+
* code so approval can sign in as the existing agent instead of adding a
|
|
352
|
+
* duplicate. A true first run sends no mode and keeps the server's
|
|
353
|
+
* 'new_agent' default.
|
|
354
|
+
*/
|
|
355
|
+
function deviceAuthorizeBody() {
|
|
356
|
+
const defaultName = `agent-${homedir().split('/').pop() ?? 'user'}`;
|
|
357
|
+
if (loadAgentPreference()?.agentId)
|
|
358
|
+
return { name: defaultName, mode: 'reauth' };
|
|
359
|
+
const requestedName = process.env['AIS_AGENT_NAME']?.trim();
|
|
360
|
+
// Match the name length limit in AIS's /device/authorize route.
|
|
361
|
+
const maxNameLength = 100;
|
|
362
|
+
const tooLong = requestedName !== undefined && requestedName.length > maxNameLength;
|
|
363
|
+
if (tooLong) {
|
|
364
|
+
stderr(`AIS_AGENT_NAME exceeds the ${maxNameLength}-character limit. Using the default agent name.`);
|
|
365
|
+
}
|
|
366
|
+
return { name: requestedName && !tooLong ? requestedName : defaultName };
|
|
346
367
|
}
|
|
347
368
|
/** Fallback poll interval when a resumed record predates the stored field. */
|
|
348
369
|
const DEFAULT_DEVICE_POLL_INTERVAL_S = 5;
|
|
@@ -366,7 +387,8 @@ async function startDeviceFlow(priorProvisionalToken) {
|
|
|
366
387
|
// before — so this can only reduce the number of agents, never break a
|
|
367
388
|
// sign-in.
|
|
368
389
|
const carriedToken = priorProvisionalToken ?? loadPendingDeviceFlow()?.provisionalToken;
|
|
369
|
-
const
|
|
390
|
+
const body = deviceAuthorizeBody();
|
|
391
|
+
const authRes = (await aisPost('/v1/oauth/device/authorize', body, carriedToken));
|
|
370
392
|
if (!authRes.success || !authRes.data) {
|
|
371
393
|
throw new Error(`Authentication failed: ${authRes.error?.message ?? 'Unknown error'}`);
|
|
372
394
|
}
|
|
@@ -390,6 +412,7 @@ async function startDeviceFlow(priorProvisionalToken) {
|
|
|
390
412
|
userCode: user_code,
|
|
391
413
|
verificationUriComplete: verification_uri_complete,
|
|
392
414
|
interval,
|
|
415
|
+
reauth: body.mode === 'reauth',
|
|
393
416
|
codeExpiresAt: new Date(Date.now() + authRes.data.expires_in * 1000).toISOString(),
|
|
394
417
|
});
|
|
395
418
|
return attachDeviceFlowPoll({
|
|
@@ -402,9 +425,9 @@ async function startDeviceFlow(priorProvisionalToken) {
|
|
|
402
425
|
// poll is assigned by attachDeviceFlowPoll, which captures the live flow
|
|
403
426
|
// object so pollForToken can update the surfaced URL on auto-restart.
|
|
404
427
|
dead: false,
|
|
405
|
-
}, interval);
|
|
428
|
+
}, interval, body.mode === 'reauth');
|
|
406
429
|
}
|
|
407
|
-
async function pollForToken(device_code, interval, agent_id, provisional_tenant_id,
|
|
430
|
+
async function pollForToken(device_code, interval, agent_id, provisional_tenant_id, reauth,
|
|
408
431
|
/** Mutable ref so auto-restart can update the surfaced URL and provisional token in ActiveDeviceFlow */
|
|
409
432
|
flowRef) {
|
|
410
433
|
const pollIntervalMs = Math.max(interval, 5) * 1000;
|
|
@@ -436,7 +459,8 @@ flowRef) {
|
|
|
436
459
|
}
|
|
437
460
|
},
|
|
438
461
|
startNewFlow: async () => {
|
|
439
|
-
const
|
|
462
|
+
const body = deviceAuthorizeBody();
|
|
463
|
+
const authRes = (await aisPost('/v1/oauth/device/authorize', body, flowRef?.provisional_token));
|
|
440
464
|
if (!authRes.success || !authRes.data) {
|
|
441
465
|
throw new Error(`Re-authorization failed: ${authRes.error?.message ?? 'Unknown error'}`);
|
|
442
466
|
}
|
|
@@ -467,6 +491,7 @@ flowRef) {
|
|
|
467
491
|
userCode: authRes.data.user_code,
|
|
468
492
|
verificationUriComplete: authRes.data.verification_uri_complete,
|
|
469
493
|
interval: authRes.data.interval,
|
|
494
|
+
reauth: body.mode === 'reauth',
|
|
470
495
|
codeExpiresAt: new Date(Date.now() + authRes.data.expires_in * 1000).toISOString(),
|
|
471
496
|
});
|
|
472
497
|
stderr('');
|
|
@@ -494,12 +519,16 @@ flowRef) {
|
|
|
494
519
|
throw new Error('Poll loop ended without an access token');
|
|
495
520
|
}
|
|
496
521
|
const expiresAt = new Date(Date.now() + (pollResp.expires_in ?? 604800) * 1000).toISOString();
|
|
497
|
-
// A completed bond names the agent confirmed by this flow, never a
|
|
498
|
-
// machine-wide preference or the tenant's first active agent.
|
|
499
522
|
const bondClaims = decodeJwtClaims(pollResp.access_token);
|
|
500
|
-
|
|
523
|
+
if (reauth && !bondClaims.agentId) {
|
|
524
|
+
throw new Error('Reauthentication failed: the approved token is missing an agent id');
|
|
525
|
+
}
|
|
526
|
+
// Only the bond token's agent claim confirms an agent; the provisional flow
|
|
527
|
+
// agent never does (CORBOT-F456BD9D).
|
|
528
|
+
const approvedAgentId = bondClaims.agentId;
|
|
529
|
+
const { agentId, tenantId } = sessionIdentity || (!approvedAgentId && process.env['AIS_AGENT_NAME'])
|
|
501
530
|
? await resolveAgent(pollResp.access_token, agent_id, provisional_tenant_id)
|
|
502
|
-
: { agentId:
|
|
531
|
+
: { agentId: approvedAgentId ?? '', tenantId: bondClaims.tenantId ?? provisional_tenant_id };
|
|
503
532
|
const creds = {
|
|
504
533
|
token: pollResp.access_token,
|
|
505
534
|
agentId,
|
|
@@ -679,6 +708,7 @@ const tools = [
|
|
|
679
708
|
view: { type: 'string', enum: ['full', 'lean', 'bootstrap'], description: "Which projection to load. 'full' (default) is everything the stores hold, bounded to 6000 tokens. 'lean' is continuity only — last handoff first, then recent memories. 'bootstrap' is lean plus goals and inbox, for starting a session in another harness. All three honour maxTokens." },
|
|
680
709
|
maxTokens: { type: 'number', description: 'Token ceiling (500-20000; default 6000 for full, 2000 for lean, 3000 for bootstrap). Content is evicted from the tail until the payload fits — assembled context sections, then facts, then goals, then recent memories on the full view — and each eviction is named in receipt.omitted. Identity, the operating layer and the last handoff are never dropped.' },
|
|
681
710
|
openOrdersLimit: { type: 'number', description: 'Number of newest open task memories to include in bootstrap view (1-50; default 10).' },
|
|
711
|
+
harness: { type: 'string', description: 'Your current harness for session-specific guidance: chatgpt, claude-code, claude-desktop, codex, cursor, or grokbot. Omit when unknown. Unrecognized names receive no harness guidance.' },
|
|
682
712
|
contextWindowSize: { type: 'number', description: "Your model's context window in tokens (1000-10000000). The skills budget scales with it; omit for the server default." },
|
|
683
713
|
tags: { type: 'array', items: { type: 'string' }, description: 'Only memories carrying every one of these tags (forwarded to AIS). Memories tagged no-lean are omitted from lean and bootstrap reads unless you pass your own tags, anyTags, or excludeTags.' },
|
|
684
714
|
anyTags: { type: 'array', items: { type: 'string' }, description: 'Only memories carrying at least one of these tags (forwarded to AIS). Memories tagged no-lean are omitted from lean and bootstrap reads unless you pass your own tags, anyTags, or excludeTags.' },
|
|
@@ -878,6 +908,17 @@ const tools = [
|
|
|
878
908
|
required: ['goalId', 'progress'],
|
|
879
909
|
},
|
|
880
910
|
},
|
|
911
|
+
{
|
|
912
|
+
name: 'goal_activate',
|
|
913
|
+
description: 'Activate one of your own draft goals so it appears in your context. New goals start as draft.',
|
|
914
|
+
inputSchema: {
|
|
915
|
+
type: 'object',
|
|
916
|
+
properties: {
|
|
917
|
+
goalId: { type: 'string', description: 'The id of the goal.' },
|
|
918
|
+
},
|
|
919
|
+
required: ['goalId'],
|
|
920
|
+
},
|
|
921
|
+
},
|
|
881
922
|
{
|
|
882
923
|
name: 'goal_complete',
|
|
883
924
|
description: 'Mark a goal as complete (success or failure). Records the outcome for success-rate tracking.',
|
|
@@ -1028,6 +1069,20 @@ async function main() {
|
|
|
1028
1069
|
return;
|
|
1029
1070
|
}
|
|
1030
1071
|
// Subcommand dispatch — CLI entrypoints exit before MCP server startup.
|
|
1072
|
+
if (process.argv[2] === 'bond') {
|
|
1073
|
+
if (process.argv.length > 3)
|
|
1074
|
+
throw new Error('Usage: aismemory bond');
|
|
1075
|
+
if (RUN_PASS_CONFLICTING_KEY_ENV_NAMES.some((name) => process.env[name] !== undefined) ||
|
|
1076
|
+
process.env['AIS_RUN_PASS_FILE'] !== undefined || hasEnrolledKey() ||
|
|
1077
|
+
loadAgentPreference()?.ownerUserId || loadCredentials()) {
|
|
1078
|
+
process.stdout.write('AIS sign-in is already configured.\n');
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
const flow = await startDeviceFlow();
|
|
1082
|
+
// The pending flow is saved. Exit after stdout flushes instead of waiting for approval.
|
|
1083
|
+
process.stdout.write(`${flow.verification_uri_complete}\n`, () => process.exit(0));
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1031
1086
|
if (process.argv[2] === 'install') {
|
|
1032
1087
|
(await import('./cli/install.js')).main(process.argv.slice(3));
|
|
1033
1088
|
return;
|
|
@@ -1168,6 +1223,7 @@ async function main() {
|
|
|
1168
1223
|
...(startupPreference?.ownerUserId ? { keychainOwnerSession: true } : {}),
|
|
1169
1224
|
});
|
|
1170
1225
|
let activeFlow = null;
|
|
1226
|
+
let startingFlow = null;
|
|
1171
1227
|
let freshlyBondedAgentId = null;
|
|
1172
1228
|
let postAuthDone = false;
|
|
1173
1229
|
let postAuthTask = null;
|
|
@@ -1253,6 +1309,17 @@ async function main() {
|
|
|
1253
1309
|
? { ...authenticated, agentId: toolName === 'whoami' ? freshlyBondedAgentId ?? '' : '' }
|
|
1254
1310
|
: authenticated;
|
|
1255
1311
|
}
|
|
1312
|
+
async function getDeviceFlow() {
|
|
1313
|
+
if (activeFlow && !activeFlow.dead)
|
|
1314
|
+
return activeFlow;
|
|
1315
|
+
startingFlow ??= startDeviceFlow(activeFlow?.provisional_token)
|
|
1316
|
+
.then((flow) => {
|
|
1317
|
+
activeFlow = flow;
|
|
1318
|
+
return flow;
|
|
1319
|
+
})
|
|
1320
|
+
.finally(() => { startingFlow = null; });
|
|
1321
|
+
return startingFlow;
|
|
1322
|
+
}
|
|
1256
1323
|
async function acquireCredentials(softTimeoutMs = 7000) {
|
|
1257
1324
|
// CORBOT-EBCB2D2B: owner terminal sign-in uses the workspace credential
|
|
1258
1325
|
// in the OS keychain (not the DID key or a stale disk bearer) so
|
|
@@ -1312,24 +1379,23 @@ async function main() {
|
|
|
1312
1379
|
if (creds && !isCredsStale(creds.expiresAt, Date.now())) {
|
|
1313
1380
|
return creds;
|
|
1314
1381
|
}
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
}
|
|
1382
|
+
let flow;
|
|
1383
|
+
try {
|
|
1384
|
+
flow = await getDeviceFlow();
|
|
1385
|
+
}
|
|
1386
|
+
catch (error) {
|
|
1387
|
+
throw new Error(`${MISSING_CREDENTIAL_HELP} AIS sign-in could not start; check AIS_URL and connectivity, then retry.`, { cause: error });
|
|
1322
1388
|
}
|
|
1323
1389
|
const sentinel = Symbol('bond-pending');
|
|
1324
1390
|
// poll is always set by startDeviceFlow before it returns; this guard
|
|
1325
1391
|
// satisfies the type checker for the optional field.
|
|
1326
|
-
if (!
|
|
1392
|
+
if (!flow.poll) {
|
|
1327
1393
|
throw new Error('Invariant violated: activeFlow.poll is unset after startDeviceFlow');
|
|
1328
1394
|
}
|
|
1329
1395
|
let got;
|
|
1330
1396
|
try {
|
|
1331
1397
|
got = await Promise.race([
|
|
1332
|
-
|
|
1398
|
+
flow.poll,
|
|
1333
1399
|
new Promise((r) => setTimeout(() => r(sentinel), softTimeoutMs)),
|
|
1334
1400
|
]);
|
|
1335
1401
|
}
|
|
@@ -1339,11 +1405,11 @@ async function main() {
|
|
|
1339
1405
|
// Always say WHY the old flow died: a silent discard here hid three
|
|
1340
1406
|
// weeks of broken cold-start bonding (CORBOT-9CE03C6E).
|
|
1341
1407
|
stderr(`Device flow discarded (${err instanceof Error ? err.message : String(err)}); starting a fresh one.`);
|
|
1342
|
-
|
|
1343
|
-
throw new BondPendingError(
|
|
1408
|
+
const replacement = await getDeviceFlow();
|
|
1409
|
+
throw new BondPendingError(replacement.verification_uri_complete, replacement.user_code);
|
|
1344
1410
|
}
|
|
1345
1411
|
if (got === sentinel) {
|
|
1346
|
-
throw new BondPendingError(
|
|
1412
|
+
throw new BondPendingError(flow.verification_uri_complete, flow.user_code);
|
|
1347
1413
|
}
|
|
1348
1414
|
creds = got;
|
|
1349
1415
|
// Show the agent selected by this bond on whoami in this process only. A bond does
|
|
@@ -1404,9 +1470,10 @@ async function main() {
|
|
|
1404
1470
|
}
|
|
1405
1471
|
function installAutoHandoff(c) {
|
|
1406
1472
|
removeAutoHandoff?.();
|
|
1407
|
-
removeAutoHandoff = setupAutoHandoff(AIS_URL, c.agentId, c.token, activityTracker, () => {
|
|
1473
|
+
removeAutoHandoff = setupAutoHandoff(AIS_URL, c.agentId, c.token, activityTracker, (saved) => {
|
|
1408
1474
|
stopRefreshTimer();
|
|
1409
|
-
|
|
1475
|
+
if (saved)
|
|
1476
|
+
stderr('Session handoff saved');
|
|
1410
1477
|
}, () => verifyConfirmedIdentityForAutoHandoff(sessionIdentity, c.agentId, () => aisGet(`/v1/agents/${c.agentId}`, c.token), { credentialKey: identityCredentialFingerprint('oauth-bearer', c.token) }));
|
|
1411
1478
|
}
|
|
1412
1479
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
@@ -1437,12 +1504,26 @@ async function main() {
|
|
|
1437
1504
|
setCredentials: (next) => { creds = next; },
|
|
1438
1505
|
setSessionAgentOverride: (next) => {
|
|
1439
1506
|
sessionAgentOverride = next;
|
|
1507
|
+
// One agent's activity must never enter another agent's handoff.
|
|
1508
|
+
// The switch itself is the new agent's first recorded activity.
|
|
1509
|
+
if (next) {
|
|
1510
|
+
activityTracker.reset();
|
|
1511
|
+
activityTracker.recordToolUse('agent_load');
|
|
1512
|
+
}
|
|
1440
1513
|
if (next && creds)
|
|
1441
1514
|
installAutoHandoff({ ...creds, ...next });
|
|
1442
1515
|
},
|
|
1443
1516
|
getAgentContext: () => agentContext,
|
|
1444
1517
|
setAgentContext: (next) => { agentContext = next; },
|
|
1445
1518
|
ensureCredentials: (toolName) => ensureCredentials(toolName),
|
|
1519
|
+
ensureFirstBond: async () => {
|
|
1520
|
+
if (creds || hasEnrolledKey())
|
|
1521
|
+
return;
|
|
1522
|
+
const pref = loadAgentPreference();
|
|
1523
|
+
if (pref?.agentId || pref?.ownerUserId)
|
|
1524
|
+
return;
|
|
1525
|
+
await ensureCredentials();
|
|
1526
|
+
},
|
|
1446
1527
|
invalidateToken: () => { tokenManager.invalidate({ resetBackoff: true }); },
|
|
1447
1528
|
applyMemoryRefresh,
|
|
1448
1529
|
resolveAgentForLoad,
|
package/dist/mcp/tools.d.ts
CHANGED
|
@@ -60,6 +60,8 @@ export interface OAuthCallToolContext {
|
|
|
60
60
|
getAgentContext(): AgentContext | null;
|
|
61
61
|
setAgentContext(next: AgentContext | null): void;
|
|
62
62
|
ensureCredentials(toolName?: string): Promise<OAuthCredentials>;
|
|
63
|
+
/** Surfaces a pending bond link on first use before checking for a session pin. */
|
|
64
|
+
ensureFirstBond?(): Promise<void>;
|
|
63
65
|
/** Drops the TokenManager's cached token and resets its backoff window. */
|
|
64
66
|
invalidateToken(): void;
|
|
65
67
|
applyMemoryRefresh(agentId: string, token: string): void;
|
package/dist/mcp/tools.js
CHANGED
|
@@ -19,7 +19,7 @@ import { saveOAuthCredentials } from '../oauth-credentials.js';
|
|
|
19
19
|
import { hasEnrolledKey } from '../key-auth.js';
|
|
20
20
|
import { emitTelemetry, hashAgentId } from '../telemetry.js';
|
|
21
21
|
import { duplicateMemoryResult } from '../ais-http-error.js';
|
|
22
|
-
import { parseAgentLoadArgs, parseEmptyToolArgs, parseHandoffArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalCompleteArgs, } from '../tool-args.js';
|
|
22
|
+
import { parseAgentLoadArgs, parseEmptyToolArgs, parseHandoffArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, } from '../tool-args.js';
|
|
23
23
|
import { AGENT_LOAD_WRITE_REQUIRED, assertPinnedAgent, assertWriteIdentityConfirmed, clearPinnedIdentityConfirmation, identityCredentialFingerprint, requiresIdentityGate, sessionIdentityFromAgentLoad, switchedTo, unconfirmedWhoamiFromAgent, unconfirmedWhoamiPayload, verifyPinnedIdentity, whoamiMustDeferToAgentLoad, } from '../session-identity.js';
|
|
24
24
|
import { readInboxAndMaybeAck } from '../inbox-client.js';
|
|
25
25
|
import { OPERATING_LAYER_PUT_TOOL, OPERATING_LAYER_PUT_KEY_MODE_DETAIL } from '../operating-layer-write.js';
|
|
@@ -289,6 +289,8 @@ export function createOAuthCallToolHandler(ctx) {
|
|
|
289
289
|
const toolStartedAt = Date.now();
|
|
290
290
|
try {
|
|
291
291
|
if (requiresIdentityGate(name, rawArgs)) {
|
|
292
|
+
if (!ctx.getSessionIdentity())
|
|
293
|
+
await ctx.ensureFirstBond?.();
|
|
292
294
|
assertWriteIdentityConfirmed(ctx.getSessionIdentity());
|
|
293
295
|
assertPinnedAgent(ctx.getSessionIdentity(), ctx.getSessionIdentity().agentId);
|
|
294
296
|
}
|
|
@@ -539,6 +541,11 @@ export function createOAuthCallToolHandler(ctx) {
|
|
|
539
541
|
}, token);
|
|
540
542
|
break;
|
|
541
543
|
}
|
|
544
|
+
case 'goal_activate': {
|
|
545
|
+
const goalActivateArgs = parseGoalActivateArgs(rawArgs);
|
|
546
|
+
result = await aisPost(`/v1/agents/${agentId}/goals/${goalActivateArgs.goalId}/activate`, {}, token);
|
|
547
|
+
break;
|
|
548
|
+
}
|
|
542
549
|
case 'goal_complete': {
|
|
543
550
|
const goalCompleteArgs = parseGoalCompleteArgs(rawArgs);
|
|
544
551
|
result = await aisPost(`/v1/agents/${agentId}/goals/${goalCompleteArgs.goalId}/complete`, {
|
|
@@ -47,6 +47,8 @@ export interface PendingDeviceFlow {
|
|
|
47
47
|
verificationUriComplete?: string;
|
|
48
48
|
/** Server-advised poll interval in seconds. */
|
|
49
49
|
interval?: number;
|
|
50
|
+
/** Whether the saved code was issued for reauth. Older records omit this. */
|
|
51
|
+
reauth?: boolean;
|
|
50
52
|
/** ISO timestamp at which the device code stops being redeemable. */
|
|
51
53
|
codeExpiresAt?: string;
|
|
52
54
|
}
|
|
@@ -83,6 +83,7 @@ export function loadPendingDeviceFlow(home = homedir(), now = Date.now()) {
|
|
|
83
83
|
? { verificationUriComplete: parsed.verificationUriComplete }
|
|
84
84
|
: {}),
|
|
85
85
|
...(typeof parsed.interval === 'number' ? { interval: parsed.interval } : {}),
|
|
86
|
+
...(typeof parsed.reauth === 'boolean' ? { reauth: parsed.reauth } : {}),
|
|
86
87
|
...(typeof parsed.codeExpiresAt === 'string' ? { codeExpiresAt: parsed.codeExpiresAt } : {}),
|
|
87
88
|
};
|
|
88
89
|
}
|
|
@@ -12,11 +12,12 @@ export interface BulkWriteResult {
|
|
|
12
12
|
index: number;
|
|
13
13
|
error: string;
|
|
14
14
|
}>;
|
|
15
|
+
deduplicated?: number;
|
|
15
16
|
}
|
|
16
17
|
/**
|
|
17
18
|
* POST a single chunk to the AIS bulk endpoint with a hard timeout.
|
|
18
|
-
*
|
|
19
|
-
*
|
|
19
|
+
* Accepts reconciled HTTP 422 responses for batches with no new writes.
|
|
20
|
+
* Throws on other unsuccessful responses or AbortError.
|
|
20
21
|
*/
|
|
21
22
|
export declare function postBulkChunk(agentId: string, drafts: AisMemoryDraft[], creds: AisCreds, timeoutMs?: number): Promise<BulkWriteResult>;
|
|
22
23
|
/**
|
|
@@ -29,7 +30,7 @@ export declare function postSingleWrite(agentId: string, draft: AisMemoryDraft,
|
|
|
29
30
|
* Recursively write `drafts` mapped to their original `baseIndices`.
|
|
30
31
|
* On AbortError or 502/503/504, halves the chunk and retries; falls through to
|
|
31
32
|
* single-write when the chunk reaches size 1.
|
|
32
|
-
* Per-item
|
|
33
|
+
* Per-item failures are retried individually only for receipt-less servers.
|
|
33
34
|
*/
|
|
34
35
|
export declare function writeWithRetry(agentId: string, drafts: AisMemoryDraft[], baseIndices: number[], creds: AisCreds, timeoutMs?: number): Promise<BulkWriteResult>;
|
|
35
36
|
/**
|
|
@@ -1,5 +1,12 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
1
2
|
export const BULK_CHUNK_SIZE = 25;
|
|
2
3
|
export const BULK_TIMEOUT_MS = 20_000;
|
|
4
|
+
const bulkReceiptSchema = z.object({
|
|
5
|
+
received: z.number().int().nonnegative(),
|
|
6
|
+
stored: z.number().int().nonnegative(),
|
|
7
|
+
deduplicated: z.number().int().nonnegative(),
|
|
8
|
+
rejected: z.array(z.object({ index: z.number().int().nonnegative(), reason: z.string() })),
|
|
9
|
+
});
|
|
3
10
|
function memoryPayload(draft) {
|
|
4
11
|
return {
|
|
5
12
|
content: draft.content,
|
|
@@ -10,8 +17,8 @@ function memoryPayload(draft) {
|
|
|
10
17
|
}
|
|
11
18
|
/**
|
|
12
19
|
* POST a single chunk to the AIS bulk endpoint with a hard timeout.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
20
|
+
* Accepts reconciled HTTP 422 responses for batches with no new writes.
|
|
21
|
+
* Throws on other unsuccessful responses or AbortError.
|
|
15
22
|
*/
|
|
16
23
|
export async function postBulkChunk(agentId, drafts, creds, timeoutMs = BULK_TIMEOUT_MS) {
|
|
17
24
|
const controller = new AbortController();
|
|
@@ -30,12 +37,35 @@ export async function postBulkChunk(agentId, drafts, creds, timeoutMs = BULK_TIM
|
|
|
30
37
|
const text = await res.text().catch(() => '');
|
|
31
38
|
throw new Error(`AIS bulk store auth error: HTTP ${res.status}${text ? ` — ${text.slice(0, 500)}` : ''}`);
|
|
32
39
|
}
|
|
40
|
+
// A 422 can be a completed batch or a request error. Keep the body
|
|
41
|
+
// available for the legacy HTTP error if there's no receipt.
|
|
42
|
+
const json = (res.ok ? await res.json() : res.status === 422
|
|
43
|
+
? await res.clone().json().catch(() => undefined)
|
|
44
|
+
: undefined);
|
|
45
|
+
const data = json?.data;
|
|
46
|
+
const created = data?.created ?? [];
|
|
47
|
+
if (data && typeof data === 'object' &&
|
|
48
|
+
('received' in data || 'stored' in data || 'deduplicated' in data || 'rejected' in data)) {
|
|
49
|
+
const receipt = bulkReceiptSchema.safeParse(data);
|
|
50
|
+
if (!receipt.success)
|
|
51
|
+
throw new Error('AIS bulk store returned an invalid import receipt');
|
|
52
|
+
const { received, stored, deduplicated, rejected } = receipt.data;
|
|
53
|
+
if (received !== drafts.length || stored !== created.length ||
|
|
54
|
+
received !== stored + deduplicated + rejected.length ||
|
|
55
|
+
rejected.some(({ index }) => index >= received)) {
|
|
56
|
+
throw new Error('AIS bulk store returned an inconsistent import receipt');
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
created,
|
|
60
|
+
failed: rejected.map(({ index, reason }) => ({ index, error: reason })),
|
|
61
|
+
deduplicated,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
33
64
|
if (!res.ok) {
|
|
34
65
|
const text = await res.text().catch(() => '');
|
|
35
66
|
throw new Error(`AIS bulk store failed: HTTP ${res.status} ${res.statusText}${text ? ` — ${text.slice(0, 500)}` : ''}`);
|
|
36
67
|
}
|
|
37
|
-
|
|
38
|
-
return { created: json.data?.created ?? [], failed: json.data?.failed ?? [] };
|
|
68
|
+
return { created, failed: data?.failed ?? [] };
|
|
39
69
|
}
|
|
40
70
|
finally {
|
|
41
71
|
clearTimeout(timer);
|
|
@@ -87,7 +117,7 @@ export async function postSingleWrite(agentId, draft, originalIndex, creds, time
|
|
|
87
117
|
* Recursively write `drafts` mapped to their original `baseIndices`.
|
|
88
118
|
* On AbortError or 502/503/504, halves the chunk and retries; falls through to
|
|
89
119
|
* single-write when the chunk reaches size 1.
|
|
90
|
-
* Per-item
|
|
120
|
+
* Per-item failures are retried individually only for receipt-less servers.
|
|
91
121
|
*/
|
|
92
122
|
export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeoutMs = BULK_TIMEOUT_MS) {
|
|
93
123
|
if (drafts.length === 0)
|
|
@@ -100,6 +130,7 @@ export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeou
|
|
|
100
130
|
chunkResult = await postBulkChunk(agentId, drafts, creds, timeoutMs);
|
|
101
131
|
// Re-map chunk-local indices back to global.
|
|
102
132
|
chunkResult = {
|
|
133
|
+
...chunkResult,
|
|
103
134
|
created: chunkResult.created.map((c) => ({ index: baseIndices[c.index], id: c.id })),
|
|
104
135
|
failed: chunkResult.failed.map((f) => ({ index: baseIndices[f.index], error: f.error })),
|
|
105
136
|
};
|
|
@@ -117,9 +148,13 @@ export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeou
|
|
|
117
148
|
writeWithRetry(agentId, drafts.slice(0, half), baseIndices.slice(0, half), creds, timeoutMs),
|
|
118
149
|
writeWithRetry(agentId, drafts.slice(half), baseIndices.slice(half), creds, timeoutMs),
|
|
119
150
|
]);
|
|
120
|
-
return {
|
|
151
|
+
return {
|
|
152
|
+
created: [...left.created, ...right.created],
|
|
153
|
+
failed: [...left.failed, ...right.failed],
|
|
154
|
+
deduplicated: (left.deduplicated ?? 0) + (right.deduplicated ?? 0),
|
|
155
|
+
};
|
|
121
156
|
}
|
|
122
|
-
if (chunkResult.failed.length === 0)
|
|
157
|
+
if (chunkResult.deduplicated !== undefined || chunkResult.failed.length === 0)
|
|
123
158
|
return chunkResult;
|
|
124
159
|
// Retry per-item failures individually.
|
|
125
160
|
const retried = await Promise.all(chunkResult.failed.map((f) => {
|
|
@@ -141,14 +176,16 @@ export async function writeWithRetry(agentId, drafts, baseIndices, creds, timeou
|
|
|
141
176
|
export async function bulkStoreViaAis(agentId, drafts, creds) {
|
|
142
177
|
const allCreated = [];
|
|
143
178
|
const allFailed = [];
|
|
179
|
+
let deduplicated = 0;
|
|
144
180
|
for (let start = 0; start < drafts.length; start += BULK_CHUNK_SIZE) {
|
|
145
181
|
const chunk = drafts.slice(start, start + BULK_CHUNK_SIZE);
|
|
146
182
|
const baseIndices = Array.from({ length: chunk.length }, (_, i) => start + i);
|
|
147
183
|
const result = await writeWithRetry(agentId, chunk, baseIndices, creds);
|
|
148
184
|
allCreated.push(...result.created);
|
|
149
185
|
allFailed.push(...result.failed);
|
|
186
|
+
deduplicated += result.deduplicated ?? 0;
|
|
150
187
|
}
|
|
151
|
-
return { created: allCreated, failed: allFailed };
|
|
188
|
+
return { created: allCreated, failed: allFailed, deduplicated };
|
|
152
189
|
}
|
|
153
190
|
/**
|
|
154
191
|
* Single-write-only mode: bypasses bulk endpoint entirely.
|
|
@@ -12,6 +12,7 @@ export interface BulkStoreResult {
|
|
|
12
12
|
index: number;
|
|
13
13
|
error: string;
|
|
14
14
|
}>;
|
|
15
|
+
deduplicated?: number;
|
|
15
16
|
}
|
|
16
17
|
export type BulkStoreFn = (drafts: AisMemoryDraft[]) => Promise<BulkStoreResult>;
|
|
17
18
|
export type ReviewFn = (drafts: AisMemoryDraft[]) => Promise<AisMemoryDraft[]>;
|
|
@@ -43,7 +43,9 @@ export async function runIngestion(options) {
|
|
|
43
43
|
if (approved.length === 0) {
|
|
44
44
|
ledger.recordSync(agentId, adapter.id, scopeKey);
|
|
45
45
|
return {
|
|
46
|
+
received: 0,
|
|
46
47
|
imported: 0,
|
|
48
|
+
deduplicated: 0,
|
|
47
49
|
skippedExactDupes,
|
|
48
50
|
skippedByUser,
|
|
49
51
|
warnings: parsed.warnings,
|
|
@@ -53,7 +55,7 @@ export async function runIngestion(options) {
|
|
|
53
55
|
}
|
|
54
56
|
// Split approved drafts into chunks to stay within AIS bulk limit.
|
|
55
57
|
const storeResult = await chunkedBulkStore(bulkStore, approved);
|
|
56
|
-
//
|
|
58
|
+
// Already-stored rows are successful. Partial failures must not
|
|
57
59
|
// increment syncCount toward auto-commit.
|
|
58
60
|
if (storeResult.failed.length === 0) {
|
|
59
61
|
ledger.recordSync(agentId, adapter.id, scopeKey);
|
|
@@ -71,7 +73,9 @@ export async function runIngestion(options) {
|
|
|
71
73
|
mirrorWarnings.push(`local mirror append failed: ${msg}`);
|
|
72
74
|
}
|
|
73
75
|
return {
|
|
76
|
+
received: approved.length,
|
|
74
77
|
imported: storeResult.created.length,
|
|
78
|
+
deduplicated: storeResult.deduplicated ?? 0,
|
|
75
79
|
skippedExactDupes,
|
|
76
80
|
skippedByUser,
|
|
77
81
|
warnings: [...parsed.warnings, ...mirrorWarnings],
|
|
@@ -91,6 +95,7 @@ async function chunkedBulkStore(fn, drafts) {
|
|
|
91
95
|
for (let offset = 0; offset < drafts.length; offset += BULK_BATCH_SIZE) {
|
|
92
96
|
const chunk = drafts.slice(offset, offset + BULK_BATCH_SIZE);
|
|
93
97
|
const result = await fn(chunk);
|
|
98
|
+
aggregated.deduplicated = (aggregated.deduplicated ?? 0) + (result.deduplicated ?? 0);
|
|
94
99
|
for (const c of result.created) {
|
|
95
100
|
aggregated.created.push({ index: c.index + offset, id: c.id });
|
|
96
101
|
}
|
package/dist/pipeline/types.d.ts
CHANGED
package/dist/run-pass-mode.js
CHANGED
|
@@ -16,7 +16,7 @@ import { readInboxAndMaybeAck } from './inbox-client.js';
|
|
|
16
16
|
import { orient } from './cli/orientation.js';
|
|
17
17
|
import { AGENT_ARCHIVE_KEY_MODE_DETAIL } from './agent-archive.js';
|
|
18
18
|
import { fetchCredentialWhoami } from './credential-whoami.js';
|
|
19
|
-
import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalCompleteArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
|
|
19
|
+
import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
|
|
20
20
|
import { resolveDreamResponse } from './dream-poll.js';
|
|
21
21
|
import { forgetOwnMemory } from './memory-forget.js';
|
|
22
22
|
const AGENT_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
@@ -256,6 +256,10 @@ export async function dispatchToolRunPassMode(aisUrl, config, name, rawArgs, fet
|
|
|
256
256
|
progress: args.progress,
|
|
257
257
|
}, fetchImpl);
|
|
258
258
|
}
|
|
259
|
+
case 'goal_activate': {
|
|
260
|
+
const args = parseGoalActivateArgs(rawArgs);
|
|
261
|
+
return runPassPost(aisUrl, `/v1/agents/${agentId}/goals/${args.goalId}/activate`, runPassFile, {}, fetchImpl);
|
|
262
|
+
}
|
|
259
263
|
case 'goal_complete': {
|
|
260
264
|
const args = parseGoalCompleteArgs(rawArgs);
|
|
261
265
|
return runPassPost(aisUrl, `/v1/agents/${agentId}/goals/${args.goalId}/complete`, runPassFile, {
|
package/dist/session-identity.js
CHANGED
package/dist/tool-args.d.ts
CHANGED
|
@@ -93,6 +93,7 @@ export declare const fullContextArgsSchema: z.ZodObject<{
|
|
|
93
93
|
lean: "lean";
|
|
94
94
|
bootstrap: "bootstrap";
|
|
95
95
|
}>>;
|
|
96
|
+
harness: z.ZodOptional<z.ZodString>;
|
|
96
97
|
tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
97
98
|
anyTags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
98
99
|
excludeTags: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
@@ -159,6 +160,9 @@ export declare const goalUpdateProgressArgsSchema: z.ZodObject<{
|
|
|
159
160
|
goalId: z.ZodString;
|
|
160
161
|
progress: z.ZodNumber;
|
|
161
162
|
}, z.core.$strict>;
|
|
163
|
+
export declare const goalActivateArgsSchema: z.ZodObject<{
|
|
164
|
+
goalId: z.ZodString;
|
|
165
|
+
}, z.core.$strict>;
|
|
162
166
|
export declare const goalCompleteArgsSchema: z.ZodObject<{
|
|
163
167
|
goalId: z.ZodString;
|
|
164
168
|
success: z.ZodBoolean;
|
|
@@ -200,6 +204,7 @@ export type InboxReadArgs = z.infer<typeof inboxReadArgsSchema>;
|
|
|
200
204
|
export type GoalCreateArgs = z.infer<typeof goalCreateArgsSchema>;
|
|
201
205
|
export type GoalListArgs = z.infer<typeof goalListArgsSchema>;
|
|
202
206
|
export type GoalUpdateProgressArgs = z.infer<typeof goalUpdateProgressArgsSchema>;
|
|
207
|
+
export type GoalActivateArgs = z.infer<typeof goalActivateArgsSchema>;
|
|
203
208
|
export type GoalCompleteArgs = z.infer<typeof goalCompleteArgsSchema>;
|
|
204
209
|
export type InboxAckArgs = z.infer<typeof inboxAckArgsSchema>;
|
|
205
210
|
export declare function formatValidationError(error: z.ZodError): string;
|
|
@@ -237,5 +242,6 @@ export declare function parseInboxReadArgs(raw: unknown): InboxReadArgs;
|
|
|
237
242
|
export declare function parseGoalCreateArgs(raw: unknown): GoalCreateArgs;
|
|
238
243
|
export declare function parseGoalListArgs(raw: unknown): GoalListArgs;
|
|
239
244
|
export declare function parseGoalUpdateProgressArgs(raw: unknown): GoalUpdateProgressArgs;
|
|
245
|
+
export declare function parseGoalActivateArgs(raw: unknown): GoalActivateArgs;
|
|
240
246
|
export declare function parseGoalCompleteArgs(raw: unknown): GoalCompleteArgs;
|
|
241
247
|
export declare function parseInboxAckArgs(raw: unknown): InboxAckArgs;
|
package/dist/tool-args.js
CHANGED
|
@@ -169,6 +169,7 @@ export const fullContextArgsSchema = z
|
|
|
169
169
|
memoriesLimit: z.number().int().min(1).max(50).optional(),
|
|
170
170
|
/** View mode: full (default), lean (bounded), bootstrap (cross-harness session start). */
|
|
171
171
|
view: z.enum(['full', 'lean', 'bootstrap']).optional(),
|
|
172
|
+
harness: z.string().optional(),
|
|
172
173
|
/** Only memories carrying every one of these tags (forwarded to AIS). */
|
|
173
174
|
tags: tagsArgSchema.optional(),
|
|
174
175
|
/** Only memories carrying at least one of these tags (forwarded to AIS). */
|
|
@@ -282,6 +283,7 @@ export const goalUpdateProgressArgsSchema = z
|
|
|
282
283
|
progress: z.number().min(0).max(100),
|
|
283
284
|
})
|
|
284
285
|
.strict();
|
|
286
|
+
export const goalActivateArgsSchema = z.object({ goalId: goalUuidSchema }).strict();
|
|
285
287
|
export const goalCompleteArgsSchema = z
|
|
286
288
|
.object({
|
|
287
289
|
goalId: goalUuidSchema,
|
|
@@ -467,6 +469,8 @@ export function buildFullContextQuery(args) {
|
|
|
467
469
|
params.set('memoriesLimit', String(args.memoriesLimit));
|
|
468
470
|
if (args.view !== undefined)
|
|
469
471
|
params.set('view', args.view);
|
|
472
|
+
if (args.harness !== undefined)
|
|
473
|
+
params.set('harness', args.harness);
|
|
470
474
|
if (args.maxTokens !== undefined)
|
|
471
475
|
params.set('maxTokens', String(args.maxTokens));
|
|
472
476
|
if (args.openOrdersLimit !== undefined)
|
|
@@ -499,6 +503,9 @@ export function parseGoalListArgs(raw) {
|
|
|
499
503
|
export function parseGoalUpdateProgressArgs(raw) {
|
|
500
504
|
return parseOrThrow(goalUpdateProgressArgsSchema, raw);
|
|
501
505
|
}
|
|
506
|
+
export function parseGoalActivateArgs(raw) {
|
|
507
|
+
return parseOrThrow(goalActivateArgsSchema, raw);
|
|
508
|
+
}
|
|
502
509
|
export function parseGoalCompleteArgs(raw) {
|
|
503
510
|
return parseOrThrow(goalCompleteArgsSchema, raw);
|
|
504
511
|
}
|
|
@@ -30,7 +30,7 @@ import { readInboxAndMaybeAck } from './inbox-client.js';
|
|
|
30
30
|
import { orient } from './cli/orientation.js';
|
|
31
31
|
import { AGENT_ARCHIVE_KEY_MODE_DETAIL } from './agent-archive.js';
|
|
32
32
|
import { fetchCredentialWhoami } from './credential-whoami.js';
|
|
33
|
-
import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseAgentLoadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalCompleteArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
|
|
33
|
+
import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseAgentLoadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxSendArgs, parseInboxReadArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
|
|
34
34
|
import { resolveDreamResponse } from './dream-poll.js';
|
|
35
35
|
import { forgetOwnMemory } from './memory-forget.js';
|
|
36
36
|
/** Thrown by loadWorkspaceKeyConfig when AIS_WORKSPACE_KEY is set without AIS_AGENT_ID. */
|
|
@@ -301,6 +301,10 @@ export async function dispatchToolWorkspaceKeyMode(aisUrl, config, name, rawArgs
|
|
|
301
301
|
progress: args.progress,
|
|
302
302
|
}, fetchImpl);
|
|
303
303
|
}
|
|
304
|
+
case 'goal_activate': {
|
|
305
|
+
const args = parseGoalActivateArgs(rawArgs);
|
|
306
|
+
return wksKeyPost(aisUrl, `/v1/agents/${agentId}/goals/${args.goalId}/activate`, workspaceKey, {}, fetchImpl);
|
|
307
|
+
}
|
|
304
308
|
case 'goal_complete': {
|
|
305
309
|
const args = parseGoalCompleteArgs(rawArgs);
|
|
306
310
|
return wksKeyPost(aisUrl, `/v1/agents/${agentId}/goals/${args.goalId}/complete`, workspaceKey, {
|
package/package.json
CHANGED