@howaboua/pi-agent-comms 0.0.1-dev.14.1.g7d1d3da173aa → 0.0.1

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.
@@ -1,85 +1,116 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- import { Check } from "typebox/value";
2
+ import {
3
+ arr,
4
+ bool,
5
+ compile,
6
+ int,
7
+ nul,
8
+ obj,
9
+ opt,
10
+ str,
11
+ union,
12
+ unsafe,
13
+ } from "@earendil-works/pi-schema";
4
14
 
5
- const OPTIONAL_STRING = Type.Optional(Type.String());
6
- const OPTIONAL_BOOLEAN = Type.Optional(Type.Boolean());
7
- const MATCH = Type.Object({ line_number: Type.Integer(), line: Type.String() });
15
+ const OPTIONAL_STRING = opt(str());
16
+ const OPTIONAL_BOOLEAN = opt(bool());
17
+ const MATCH = obj({ line_number: int(), line: str() }, { open: true });
8
18
 
9
19
  // Pi codemode needs this declaration to return structuredContent rather than text.
10
- export const NOTES_OUTPUT_SCHEMA = Type.Object(
11
- {},
12
- { additionalProperties: true },
13
- );
20
+ export const NOTES_OUTPUT_SCHEMA = {
21
+ ...obj({}, { open: true }),
22
+ additionalProperties: true,
23
+ };
14
24
 
15
- const NOTES_RESULT_SCHEMA = Type.Object(
25
+ const NOTES_RESULT_SCHEMA = obj(
16
26
  {
17
- file: Type.Optional(
18
- Type.Union([
19
- Type.Object({
20
- path: Type.String(),
21
- content: OPTIONAL_STRING,
22
- append_only: OPTIONAL_BOOLEAN,
23
- }),
24
- Type.Null(),
27
+ file: opt(
28
+ union([
29
+ obj(
30
+ {
31
+ path: str(),
32
+ content: OPTIONAL_STRING,
33
+ append_only: OPTIONAL_BOOLEAN,
34
+ },
35
+ { open: true },
36
+ ),
37
+ nul(),
25
38
  ]),
26
39
  ),
27
- files: Type.Optional(
28
- Type.Array(
29
- Type.Object({
30
- path: Type.String(),
31
- updated_at: OPTIONAL_STRING,
32
- created_at: OPTIONAL_STRING,
33
- matches: Type.Optional(Type.Array(MATCH)),
34
- truncated: OPTIONAL_BOOLEAN,
35
- append_only: OPTIONAL_BOOLEAN,
36
- }),
40
+ files: opt(
41
+ arr(
42
+ obj(
43
+ {
44
+ path: str(),
45
+ updated_at: OPTIONAL_STRING,
46
+ created_at: OPTIONAL_STRING,
47
+ matches: opt(arr(MATCH)),
48
+ truncated: OPTIONAL_BOOLEAN,
49
+ append_only: OPTIONAL_BOOLEAN,
50
+ },
51
+ { open: true },
52
+ ),
37
53
  ),
38
54
  ),
39
55
  usage: OPTIONAL_STRING,
40
- warnings: Type.Optional(Type.Array(Type.String())),
56
+ warnings: opt(arr(str())),
41
57
  warning: OPTIONAL_STRING,
42
58
  truncated: OPTIONAL_BOOLEAN,
43
59
  read_only: OPTIONAL_BOOLEAN,
44
60
  saved_at: OPTIONAL_STRING,
45
61
  captured_at: OPTIONAL_STRING,
46
62
  results: OPTIONAL_STRING,
47
- actions: Type.Optional(Type.Record(Type.String(), Type.String())),
63
+ actions: opt(
64
+ unsafe<Record<string, string>>({
65
+ type: "object",
66
+ patternProperties: { "^.*$": str() },
67
+ }),
68
+ ),
48
69
  writes: OPTIONAL_STRING,
49
70
  paths: OPTIONAL_STRING,
50
71
  ranges: OPTIONAL_STRING,
51
72
  defaults: OPTIONAL_STRING,
52
73
  },
53
- { additionalProperties: false },
74
+ { open: false },
54
75
  );
55
76
 
77
+ const notesResultSchemaValidator = compile(NOTES_RESULT_SCHEMA);
78
+
56
79
  /** One canonical payload for native text and every programmatic caller. */
57
80
  export function noteResult(payload: unknown): AgentToolResult<unknown> {
58
- if (!Check(NOTES_RESULT_SCHEMA, payload))
81
+ if (!notesResultSchemaValidator.check(payload))
59
82
  throw new Error(
60
83
  "Notes returned invalid data. Read the note before retrying a write.",
61
84
  );
62
- // Sharing annotations and storage bookkeeping are not note contents.
85
+ // Keep recovery warnings, but omit sharing and storage bookkeeping.
63
86
  const {
64
87
  read_only: _readOnly,
65
- warning: _warning,
88
+ warning,
66
89
  saved_at: _savedAt,
67
90
  captured_at: _capturedAt,
68
91
  ...visible
69
92
  } = payload;
93
+ if (warning !== undefined)
94
+ visible.warnings = [...(visible.warnings ?? []), warning];
70
95
  if (visible.file)
71
96
  visible.file = {
72
97
  path: visible.file.path,
73
98
  ...(visible.file.content === undefined
74
99
  ? {}
75
100
  : { content: visible.file.content }),
101
+ ...(visible.file.append_only === undefined
102
+ ? {}
103
+ : { append_only: visible.file.append_only }),
76
104
  };
77
105
  if (visible.files)
78
- visible.files = visible.files.map(({ path, matches, truncated }) => ({
79
- path,
80
- ...(matches === undefined ? {} : { matches }),
81
- ...(truncated === undefined ? {} : { truncated }),
82
- }));
106
+ visible.files = visible.files.map(
107
+ ({ path, matches, truncated, append_only }) => ({
108
+ path,
109
+ ...(matches === undefined ? {} : { matches }),
110
+ ...(truncated === undefined ? {} : { truncated }),
111
+ ...(append_only === undefined ? {} : { append_only }),
112
+ }),
113
+ );
83
114
  return {
84
115
  content: [{ type: "text", text: JSON.stringify(visible) }],
85
116
  structuredContent: visible,
@@ -69,6 +69,7 @@ export function normalizeQueryInput(
69
69
  if (action !== undefined) params["action"] = action;
70
70
  if (namespace === "notes") {
71
71
  alias(params, "address", "path");
72
+ if (action === "read") alias(params, "end_line", "stop_line");
72
73
  if (action === "write" || action === "append") {
73
74
  alias(params, "content", "text");
74
75
  alias(params, "body", "text");
@@ -1,5 +1,4 @@
1
- import { Type } from "typebox";
2
- import { Check } from "typebox/value";
1
+ import { arr, compile, obj, str } from "@earendil-works/pi-schema";
3
2
  import type {
4
3
  SavedSessionLoader,
5
4
  SavedSessionLocator,
@@ -12,13 +11,18 @@ import {
12
11
  import { savedFamilyIdentity } from "./saved-sharing-records.js";
13
12
  import type { NotesStore } from "./store.js";
14
13
 
15
- const Locations = Type.Array(
16
- Type.Object({
17
- machine: Type.String({ minLength: 1 }),
18
- sessionFile: Type.String({ minLength: 1 }),
19
- }),
14
+ const Locations = arr(
15
+ obj(
16
+ {
17
+ machine: str({ minLength: 1 }),
18
+ sessionFile: str({ minLength: 1 }),
19
+ },
20
+ { open: true },
21
+ ),
20
22
  );
21
23
 
24
+ const locationsValidator = compile(Locations);
25
+
22
26
  /** Local is relative to the session carrying the edge, not the machine running this reader. */
23
27
  export function createSavedSessionAccess(
24
28
  store: Pick<NotesStore, "sessionFile">,
@@ -100,7 +104,7 @@ export function createSavedSessionAccess(
100
104
  signal?.throwIfAborted();
101
105
  const value = await loader.find(threadId, signal);
102
106
  signal?.throwIfAborted();
103
- if (!Check(Locations, value))
107
+ if (!locationsValidator.check(value))
104
108
  throw new Error(
105
109
  "Saved session discovery response is invalid. Update Notes on the other machine and retry.",
106
110
  );
@@ -1,6 +1,14 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- import { Check } from "typebox/value";
2
+ import {
3
+ arr,
4
+ compile,
5
+ nul,
6
+ num,
7
+ obj,
8
+ opt,
9
+ str,
10
+ union,
11
+ } from "@earendil-works/pi-schema";
4
12
 
5
13
  export { readSavedNotesSession } from "./saved-session.mjs";
6
14
  export interface SavedNotesSession {
@@ -10,22 +18,30 @@ export interface SavedNotesSession {
10
18
  savedAt?: number;
11
19
  }
12
20
 
13
- const SavedEntry = Type.Object({
14
- type: Type.String(),
15
- id: Type.String(),
16
- parentId: Type.Union([Type.String(), Type.Null()]),
17
- timestamp: Type.String(),
18
- });
19
- const SavedSession = Type.Object({
20
- threadId: Type.String({ minLength: 1 }),
21
- entries: Type.Array(SavedEntry),
22
- branch: Type.Array(SavedEntry),
23
- savedAt: Type.Optional(Type.Number()),
24
- });
21
+ const SavedEntry = obj(
22
+ {
23
+ type: str(),
24
+ id: str(),
25
+ parentId: union([str(), nul()]),
26
+ timestamp: str(),
27
+ },
28
+ { open: true },
29
+ );
30
+ const SavedSession = obj(
31
+ {
32
+ threadId: str({ minLength: 1 }),
33
+ entries: arr(SavedEntry),
34
+ branch: arr(SavedEntry),
35
+ savedAt: opt(num()),
36
+ },
37
+ { open: true },
38
+ );
39
+
40
+ const savedSessionValidator = compile(SavedSession);
25
41
 
26
42
  /** Remote loaders carry data, not authority. Native identity is checked by the graph reader. */
27
43
  export function validateSavedNotesSession(value: unknown): SavedNotesSession {
28
- if (!Check(SavedSession, value))
44
+ if (!savedSessionValidator.check(value))
29
45
  throw new Error(
30
46
  "Saved session response is invalid. Update Notes on the other machine and retry.",
31
47
  );
@@ -1,5 +1,15 @@
1
- import { type Static, Type } from "typebox";
2
- import { Check } from "typebox/value";
1
+ import {
2
+ arr,
3
+ compile,
4
+ lit,
5
+ num,
6
+ obj,
7
+ opt,
8
+ type Static,
9
+ str,
10
+ union,
11
+ unknown,
12
+ } from "@earendil-works/pi-schema";
3
13
  import {
4
14
  CONTEXT_AGENT_PATTERN,
5
15
  canonicalAgentName,
@@ -9,79 +19,104 @@ import {
9
19
  } from "./agent-identity.js";
10
20
  import type { SavedNotesSession } from "./saved-session.js";
11
21
 
12
- const Agent = Type.String({ pattern: CONTEXT_AGENT_PATTERN });
13
- export const Identity = Type.Object({
14
- protocol: Type.Literal(1),
15
- sessionId: Type.String(),
16
- threadId: Type.String(),
17
- agentName: Agent,
18
- storageAgentName: Type.Optional(Agent),
19
- storage: Type.Optional(
20
- Type.Union([Type.Literal("session"), Type.Literal("remote")]),
21
- ),
22
- routing: Type.Optional(Type.Unknown()),
23
- });
24
- export const Member = Type.Object({
25
- threadId: Type.String(),
26
- sessionId: Type.String(),
27
- agentName: Agent,
28
- machine: Type.String(),
29
- sessionFile: Type.String(),
30
- });
31
- export const Plan = Type.Object({
32
- controllerSessionId: Type.String(),
33
- targetSessionId: Type.String(),
34
- context: Type.Optional(
35
- Type.Object({
36
- controller: Identity,
37
- target: Identity,
38
- alias: Agent,
39
- controllerAlias: Agent,
40
- controllerFile: Type.Optional(Type.String()),
41
- controllerMachine: Type.Optional(Type.String()),
42
- controllerNotes: Type.Unknown(),
43
- targetNotes: Type.Unknown(),
44
- }),
45
- ),
46
- });
47
- export const Route = Type.Object({
48
- plan: Plan,
49
- machine: Type.String(),
50
- sessionFile: Type.String(),
51
- phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
52
- detached: Type.Optional(
53
- Type.Object({ context: Type.Optional(Type.Unknown()) }),
54
- ),
55
- });
56
- export const Detachment = Type.Object({
57
- plan: Plan,
58
- context: Type.Optional(Type.Unknown()),
59
- });
60
- export const Snapshot = Type.Object({
61
- protocol: Type.Literal(1),
62
- timestamp: Type.Number(),
63
- files: Type.Array(
64
- Type.Object({
65
- path: Type.String(),
66
- text: Type.String(),
67
- createdAt: Type.Number(),
68
- updatedAt: Type.Number(),
69
- operation: Type.Union([
70
- Type.Literal("local_append_overlay"),
71
- Type.Literal("local_replacement"),
72
- ]),
73
- }),
74
- ),
75
- });
76
- export const Parent = Type.Object({
77
- transport: Type.Literal("shepherdr"),
78
- parent: Type.String(),
79
- savedParent: Type.Optional(
80
- Type.Object({ machine: Type.String(), sessionFile: Type.String() }),
81
- ),
82
- });
22
+ const Agent = str({ pattern: CONTEXT_AGENT_PATTERN });
23
+ export const Identity = obj(
24
+ {
25
+ protocol: lit(1),
26
+ sessionId: str(),
27
+ threadId: str(),
28
+ agentName: Agent,
29
+ storageAgentName: opt(Agent),
30
+ storage: opt(union([lit("session"), lit("remote")])),
31
+ routing: opt(unknown()),
32
+ },
33
+ { open: true },
34
+ );
35
+ export const Member = obj(
36
+ {
37
+ threadId: str(),
38
+ sessionId: str(),
39
+ agentName: Agent,
40
+ machine: str(),
41
+ sessionFile: str(),
42
+ },
43
+ { open: true },
44
+ );
45
+ export const Plan = obj(
46
+ {
47
+ controllerSessionId: str(),
48
+ targetSessionId: str(),
49
+ context: opt(
50
+ obj(
51
+ {
52
+ controller: Identity,
53
+ target: Identity,
54
+ alias: Agent,
55
+ controllerAlias: Agent,
56
+ controllerFile: opt(str()),
57
+ controllerMachine: opt(str()),
58
+ controllerNotes: unknown(),
59
+ targetNotes: unknown(),
60
+ },
61
+ { open: true },
62
+ ),
63
+ ),
64
+ },
65
+ { open: true },
66
+ );
67
+ export const Route = obj(
68
+ {
69
+ plan: Plan,
70
+ machine: str(),
71
+ sessionFile: str(),
72
+ phase: union([lit("pending"), lit("ready")]),
73
+ detached: opt(obj({ context: opt(unknown()) }, { open: true })),
74
+ },
75
+ { open: true },
76
+ );
77
+ export const Detachment = obj(
78
+ {
79
+ plan: Plan,
80
+ context: opt(unknown()),
81
+ },
82
+ { open: true },
83
+ );
84
+ export const Snapshot = obj(
85
+ {
86
+ protocol: lit(1),
87
+ timestamp: num(),
88
+ files: arr(
89
+ obj(
90
+ {
91
+ path: str(),
92
+ text: str(),
93
+ createdAt: num(),
94
+ updatedAt: num(),
95
+ operation: union([
96
+ lit("local_append_overlay"),
97
+ lit("local_replacement"),
98
+ ]),
99
+ },
100
+ { open: true },
101
+ ),
102
+ ),
103
+ },
104
+ { open: true },
105
+ );
106
+ export const Parent = obj(
107
+ {
108
+ transport: lit("shepherdr"),
109
+ parent: str(),
110
+ savedParent: opt(
111
+ obj({ machine: str(), sessionFile: str() }, { open: true }),
112
+ ),
113
+ },
114
+ { open: true },
115
+ );
83
116
  export type Identity = Static<typeof Identity>;
84
117
 
118
+ const identityValidator = compile(Identity);
119
+
85
120
  /** Ordinary family membership is immutable, explicit and native-session owned. */
86
121
  export function savedFamilyIdentity(
87
122
  session: Pick<SavedNotesSession, "threadId" | "entries">,
@@ -93,7 +128,7 @@ export function savedFamilyIdentity(
93
128
  (entry) =>
94
129
  entry.type === "custom" &&
95
130
  entry.customType === "codex-context-agent" &&
96
- Check(Identity, entry.data) &&
131
+ identityValidator.check(entry.data) &&
97
132
  entry.data.threadId === session.threadId,
98
133
  )
99
134
  )
@@ -109,7 +144,7 @@ export function savedNotesIdentity(
109
144
  for (const entry of session.entries) {
110
145
  if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
111
146
  continue;
112
- if (!Check(Identity, entry.data))
147
+ if (!identityValidator.check(entry.data))
113
148
  throw new Error("Invalid saved notes identity");
114
149
  if (entry.data.threadId !== session.threadId) continue;
115
150
  if (found) throw new Error("Conflicting saved notes identities");
@@ -1,7 +1,6 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import type { Static } from "typebox";
4
- import { Check } from "typebox/value";
3
+ import { compile, type Static } from "@earendil-works/pi-schema";
5
4
  import {
6
5
  canonicalAgentName,
7
6
  contextAgentNames,
@@ -28,6 +27,12 @@ import type { NotesStore } from "./store.js";
28
27
 
29
28
  export { savedNotesIdentity } from "./saved-sharing-records.js";
30
29
 
30
+ const detachmentValidator = compile(Detachment);
31
+ const memberValidator = compile(Member);
32
+ const parentValidator = compile(Parent);
33
+ const planValidator = compile(Plan);
34
+ const routeValidator = compile(Route);
35
+
31
36
  function records(session: SavedNotesSession, kind: string): unknown[] {
32
37
  return session.entries.flatMap((entry) =>
33
38
  entry.type === "custom" && entry.customType === kind ? [entry.data] : [],
@@ -193,7 +198,7 @@ async function readSharedSession(
193
198
  const routes = new Map<string, Static<typeof Route>>();
194
199
  for (const value of records(session, "shepherdr-attachment-route"))
195
200
  if (
196
- Check(Route, value) &&
201
+ routeValidator.check(value) &&
197
202
  value.plan.controllerSessionId === identity.threadId
198
203
  )
199
204
  routes.set(`${value.machine}\0${value.sessionFile}`, value);
@@ -232,10 +237,11 @@ async function readSharedSession(
232
237
  }
233
238
  const owner = records(session, "shepherdr-attachment-owner").findLast(
234
239
  (value) =>
235
- Check(Plan, value) && value.targetSessionId === identity.threadId,
240
+ planValidator.check(value) &&
241
+ value.targetSessionId === identity.threadId,
236
242
  );
237
243
  if (
238
- Check(Plan, owner) &&
244
+ planValidator.check(owner) &&
239
245
  owner.context &&
240
246
  (inside(destination, owner.context.controllerAlias) ||
241
247
  destination === canonicalAgentName(owner.context.controller.threadId))
@@ -253,9 +259,10 @@ async function readSharedSession(
253
259
  "shepherdr-attachment-detached",
254
260
  ).findLast(
255
261
  (value) =>
256
- Check(Detachment, value) && isDeepStrictEqual(value.plan, owner),
262
+ detachmentValidator.check(value) &&
263
+ isDeepStrictEqual(value.plan, owner),
257
264
  );
258
- const snapshot = Check(Detachment, detached)
265
+ const snapshot = detachmentValidator.check(detached)
259
266
  ? detached.context
260
267
  : undefined;
261
268
  return reference(
@@ -289,15 +296,16 @@ async function readSharedSession(
289
296
  let result: Record<string, unknown> | undefined;
290
297
  const members = records(session, "herdr-context-child").filter(
291
298
  (value) =>
292
- Check(Member, value) &&
299
+ memberValidator.check(value) &&
293
300
  value.threadId === identity.threadId &&
294
301
  value.sessionId === identity.sessionId,
295
302
  );
296
303
  const direct = members.filter(
297
- (member) => Check(Member, member) && member.agentName === destination,
304
+ (member) =>
305
+ memberValidator.check(member) && member.agentName === destination,
298
306
  );
299
307
  for (const member of direct.length ? direct : members) {
300
- if (!Check(Member, member)) continue;
308
+ if (!memberValidator.check(member)) continue;
301
309
  const location = locator(session, member.machine, member.sessionFile);
302
310
  // Only exploratory edges may be skipped. A recorded target must report its failure.
303
311
  const saved = await (direct.length
@@ -326,7 +334,7 @@ async function readSharedSession(
326
334
  if (direct.length) return result;
327
335
  const routing = identity.routing;
328
336
  const suffix = ".jsonl.shepherdr-context.json";
329
- if (Check(Parent, routing)) {
337
+ if (parentValidator.check(routing)) {
330
338
  const parentLocator = routing.savedParent
331
339
  ? locator(
332
340
  session,
@@ -1,5 +1,5 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { Check } from "typebox/value";
2
+ import { compile } from "@earendil-works/pi-schema";
3
3
  import { minuteTimestamp } from "../timestamps.js";
4
4
  import { contextStorageAgentName } from "./agent-identity.js";
5
5
  import type { SavedSessionLocator } from "./context-sharing.js";
@@ -16,6 +16,8 @@ import {
16
16
  } from "./saved-sharing-records.js";
17
17
  import type { NotesStore } from "./store.js";
18
18
 
19
+ const snapshotValidator = compile(Snapshot);
20
+
19
21
  export function createSharedSessionReader(
20
22
  store: Pick<NotesStore, "read">,
21
23
  access:
@@ -108,7 +110,7 @@ export function createSharedSessionReader(
108
110
  namespace === "history" ||
109
111
  (destination !== identity.agentName &&
110
112
  destination !== contextStorageAgentName(identity)) ||
111
- !Check(Snapshot, retained)
113
+ !snapshotValidator.check(retained)
112
114
  )
113
115
  return;
114
116
  const entry: SessionEntry = {