@getfamiliar/shared 0.1.2

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 (83) hide show
  1. package/build/AgentRun.d.ts +187 -0
  2. package/build/AgentRun.js +1 -0
  3. package/build/AgentRunBus.d.ts +147 -0
  4. package/build/AgentRunBus.js +362 -0
  5. package/build/Calendar.d.ts +450 -0
  6. package/build/Calendar.js +37 -0
  7. package/build/ChatMessage.d.ts +53 -0
  8. package/build/ChatMessage.js +11 -0
  9. package/build/ChatMessageBus.d.ts +110 -0
  10. package/build/ChatMessageBus.js +257 -0
  11. package/build/Config.d.ts +83 -0
  12. package/build/Config.js +1 -0
  13. package/build/ContainerTool.d.ts +34 -0
  14. package/build/ContainerTool.js +1 -0
  15. package/build/CronExpression.d.ts +53 -0
  16. package/build/CronExpression.js +77 -0
  17. package/build/Event.d.ts +280 -0
  18. package/build/Event.js +14 -0
  19. package/build/EventBus.d.ts +198 -0
  20. package/build/EventBus.js +482 -0
  21. package/build/HandlerCatalog.d.ts +75 -0
  22. package/build/HandlerCatalog.js +165 -0
  23. package/build/InferenceEvent.d.ts +30 -0
  24. package/build/InferenceEvent.js +1 -0
  25. package/build/InferenceEventBus.d.ts +39 -0
  26. package/build/InferenceEventBus.js +80 -0
  27. package/build/Mail.d.ts +250 -0
  28. package/build/Mail.js +73 -0
  29. package/build/MailStyleTemplate.d.ts +71 -0
  30. package/build/MailStyleTemplate.js +47 -0
  31. package/build/ModelMetaData.d.ts +63 -0
  32. package/build/ModelMetaData.js +12 -0
  33. package/build/PathGlob.d.ts +20 -0
  34. package/build/PathGlob.js +33 -0
  35. package/build/Plugin.d.ts +709 -0
  36. package/build/Plugin.js +29 -0
  37. package/build/PostgresConnection.d.ts +75 -0
  38. package/build/PostgresConnection.js +162 -0
  39. package/build/ScheduledSubagent.d.ts +49 -0
  40. package/build/ScheduledSubagent.js +1 -0
  41. package/build/ScheduledSubagentBus.d.ts +94 -0
  42. package/build/ScheduledSubagentBus.js +187 -0
  43. package/build/Schema.d.ts +84 -0
  44. package/build/Schema.js +570 -0
  45. package/build/StepResult.d.ts +103 -0
  46. package/build/StepResult.js +1 -0
  47. package/build/StepResultBus.d.ts +64 -0
  48. package/build/StepResultBus.js +169 -0
  49. package/build/Timezone.d.ts +58 -0
  50. package/build/Timezone.js +84 -0
  51. package/build/ToolCall.d.ts +25 -0
  52. package/build/ToolCall.js +1 -0
  53. package/build/ToolCallBus.d.ts +65 -0
  54. package/build/ToolCallBus.js +110 -0
  55. package/build/ToolLevel.d.ts +20 -0
  56. package/build/ToolLevel.js +2 -0
  57. package/build/ToolRunner.d.ts +118 -0
  58. package/build/ToolRunner.js +192 -0
  59. package/build/ToolsExpressionUtils.d.ts +80 -0
  60. package/build/ToolsExpressionUtils.js +102 -0
  61. package/build/WorkspaceFile.d.ts +104 -0
  62. package/build/WorkspaceFile.js +7 -0
  63. package/build/estimateTokens.d.ts +16 -0
  64. package/build/estimateTokens.js +18 -0
  65. package/build/index.d.ts +37 -0
  66. package/build/index.js +26 -0
  67. package/build/logging/Logger.d.ts +66 -0
  68. package/build/logging/Logger.js +90 -0
  69. package/build/markdownHtml.d.ts +14 -0
  70. package/build/markdownHtml.js +21 -0
  71. package/build/markdownTerminal.d.ts +14 -0
  72. package/build/markdownTerminal.js +376 -0
  73. package/build/testing/MockAgentRunBus.d.ts +52 -0
  74. package/build/testing/MockAgentRunBus.js +175 -0
  75. package/build/testing/MockBusStore.d.ts +22 -0
  76. package/build/testing/MockBusStore.js +22 -0
  77. package/build/testing/MockEventBus.d.ts +20 -0
  78. package/build/testing/MockEventBus.js +57 -0
  79. package/build/testing/MockLogger.d.ts +52 -0
  80. package/build/testing/MockLogger.js +65 -0
  81. package/build/testing/index.d.ts +4 -0
  82. package/build/testing/index.js +4 -0
  83. package/package.json +63 -0
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Lifecycle states for an `agentruns` row.
3
+ *
4
+ * Each agentrun is a single agent invocation that responds to (or
5
+ * descends from) an `events` row. Transitions:
6
+ *
7
+ * - `pending`: ready to be picked by the {@link AgentrunScheduler}.
8
+ * Either fresh (no in-memory runner) or a paused runner that has
9
+ * been re-pended after its `start_subagent` children all settled.
10
+ * - `running`: actively executing JS / making model calls. The
11
+ * Scheduler holds an in-memory entry for this row.
12
+ * - `waiting`: parked inside a `start_subagent` tool callback. The
13
+ * in-memory runner is still alive but its `agent.generate()` is
14
+ * awaiting the subagent. Moves back to `pending` once every
15
+ * `calltype='started'` child of this row has settled.
16
+ * - `done` / `failed`: terminal. Set by {@link AgentRunBus.settle},
17
+ * which also recomputes the parent event's terminal state in the
18
+ * same transaction.
19
+ */
20
+ export type AgentRunState = "pending" | "running" | "waiting" | "done" | "failed";
21
+ /**
22
+ * How a child agentrun was spawned. `null` for root agentruns (those
23
+ * created by the input-event watcher in response to an event). See
24
+ * the matching SQL CHECK in `Schema.ts`.
25
+ */
26
+ export type AgentRunCallType = "scheduled" | "started";
27
+ /**
28
+ * Shape of a row in the `agentruns` table after JSON-decoding from
29
+ * postgres. `id`, `eventId`, and `parentAgentrunId` are kept as strings
30
+ * because postgres `bigint` exceeds JavaScript's safe integer range.
31
+ */
32
+ export interface AgentRunRow {
33
+ /** Database primary key (bigint as string). */
34
+ readonly id: string;
35
+ /** FK to {@link EventRow.id} — the root event this tree responds to. */
36
+ readonly eventId: string;
37
+ /**
38
+ * FK to another {@link AgentRunRow.id}, or `null` for the root
39
+ * agentrun of an event. Forms the response tree.
40
+ */
41
+ readonly parentAgentrunId: string | null;
42
+ /**
43
+ * Topic copied from the originating event at queue time. Combined
44
+ * with {@link handler} to resolve a workspace markdown file.
45
+ */
46
+ readonly topic: string;
47
+ /**
48
+ * Basename of the handler file in the workspace (e.g. `index`,
49
+ * `analyze`). Resolution rules — for topic `chat:whatsapp` and
50
+ * handler `analyze`:
51
+ * 1. `workspace/chat/whatsapp/analyze.md`
52
+ * 2. fallback `workspace/chat/analyze.md`
53
+ */
54
+ readonly handler: string;
55
+ /**
56
+ * Resolved model id actually used for this run, of the form
57
+ * `<provider>/<modelId>` (e.g. `featherless/zai-org/GLM-5.1`).
58
+ * Distinct from the handler's *declared* model in markdown:
59
+ * carries the resolved provider prefix even when the handler
60
+ * left it bare. `null` for any agentrun that never reached the
61
+ * `agent.generate()` call (handler-load failures, etc.).
62
+ * Stamped by AgentRunner immediately after model resolution and
63
+ * never mutated afterwards.
64
+ */
65
+ readonly model: string | null;
66
+ /**
67
+ * Higher = processed first within a queue. Inherited from the
68
+ * originating event at spawn; constant per row for now.
69
+ */
70
+ readonly priority: number;
71
+ /** Lifecycle state — see {@link AgentRunState}. */
72
+ readonly state: AgentRunState;
73
+ /** Optional prompt seed supplied by the queueing caller. */
74
+ readonly prompt: string | null;
75
+ /**
76
+ * Resolved system prompt the agent ran under (SOUL.md +
77
+ * CONTEXT.md + handler body + tool list). Populated by
78
+ * AgentRunner only when `core.logSystemPrompt` is enabled;
79
+ * otherwise `null`. Read by the report layer's
80
+ * `renderAgentrunStart` when `withDetails` is on.
81
+ */
82
+ readonly systemPrompt: string | null;
83
+ /**
84
+ * Verbatim model-message array assembled for the first
85
+ * `agent.generate()` call (prior history plus the run's leading
86
+ * user turn). Populated by AgentRunner only when
87
+ * `inference.captureInitialMessageHistory` is enabled; otherwise
88
+ * `null`. Surfaced by the report layer's `-vv` view. Kept `unknown`
89
+ * (like {@link payload}) rather than coupled to the SDK
90
+ * `ModelMessage` type.
91
+ */
92
+ readonly initialMessages: unknown;
93
+ /** Spawn-time inputs from the calling agent (or the root event). */
94
+ readonly payload: unknown;
95
+ /** Structured terminal output (arbitrary JSON) when the run reaches `done` / `failed`. */
96
+ readonly result: unknown;
97
+ /**
98
+ * The agent's final text output. Populated by the agentrun watcher
99
+ * on success. Distinct from {@link result} so callers (notably
100
+ * `HostContext.events.emit`'s await-and-return path) have a
101
+ * typed, dedicated text channel without rummaging in JSON.
102
+ */
103
+ readonly resultText: string | null;
104
+ /** Error message when state is `failed`. */
105
+ readonly error: string | null;
106
+ /**
107
+ * Inherited from the originating event (root agentrun) or the parent
108
+ * agentrun (children spawned via `schedule_subagent` / `start_subagent`).
109
+ * `true` when the run descends from a trusted user-input source;
110
+ * `false` otherwise. Tools that gate risky behavior on the call
111
+ * site's trust level read this flag rather than rummaging through
112
+ * the event payload.
113
+ */
114
+ readonly privileged: boolean;
115
+ /**
116
+ * How this agentrun was spawned. `null` for root agentruns;
117
+ * `'scheduled'` for children spawned by `schedule_subagent` without a
118
+ * future `when` (fire-and-forget immediate dispatch); `'started'`
119
+ * for children of `start_subagent` (parent parks in `waiting` until
120
+ * this row settles).
121
+ */
122
+ readonly calltype: AgentRunCallType | null;
123
+ /**
124
+ * Number of retry attempts already made. Bumped each time
125
+ * `AgentRunner` postpones the row due to a retryable inference
126
+ * error. Compared against the per-handler `maxRetries` cap on
127
+ * each subsequent attempt; once `retry_count >= cap` the run
128
+ * settles `failed` instead of being postponed again.
129
+ */
130
+ readonly retryCount: number;
131
+ /**
132
+ * Earliest moment the agentrun watcher is allowed to re-claim
133
+ * this row. `null` means "claim immediately" (default for fresh
134
+ * inserts). A future timestamp parks the row so other agentruns
135
+ * — potentially using different models — can use the watcher
136
+ * slot in the meantime.
137
+ */
138
+ readonly notBefore: Date | null;
139
+ /** Insert timestamp — postgres `now()` at INSERT. */
140
+ readonly createdAt: Date;
141
+ /** Last update timestamp — bumped to `now()` on every update. */
142
+ readonly updatedAt: Date;
143
+ }
144
+ /** Input shape for {@link AgentRunBus.add}. */
145
+ export interface NewAgentRun {
146
+ /** FK to the root event. Required. */
147
+ readonly eventId: string;
148
+ /** FK to the parent agentrun, or omitted/null for the root agentrun. */
149
+ readonly parentAgentrunId?: string | null;
150
+ /** Topic copied from the event. Required. */
151
+ readonly topic: string;
152
+ /** Handler basename (e.g. `index`). Required. */
153
+ readonly handler: string;
154
+ /** Defaults to 50; usually inherited from the event. */
155
+ readonly priority?: number;
156
+ /** Initial state; default `"pending"`. */
157
+ readonly state?: AgentRunState;
158
+ /** Optional prompt seed. */
159
+ readonly prompt?: string | null;
160
+ /** Optional spawn-time payload. */
161
+ readonly payload?: unknown;
162
+ /**
163
+ * Trust flag. Default `false` — the SQL column default covers
164
+ * omission. Callers usually copy the value from the originating
165
+ * event (root agentrun) or parent agentrun (children).
166
+ */
167
+ readonly privileged?: boolean;
168
+ /**
169
+ * How this agentrun was spawned. Omitted / `null` for root rows
170
+ * inserted by the input-event watcher. Set to `'scheduled'` or
171
+ * `'started'` by the tool that spawned the child.
172
+ */
173
+ readonly calltype?: AgentRunCallType | null;
174
+ }
175
+ /** Patch shape for {@link AgentRunBus.update}. */
176
+ export interface AgentRunPatch {
177
+ readonly state?: AgentRunState;
178
+ readonly payload?: unknown;
179
+ readonly result?: unknown;
180
+ readonly resultText?: string | null;
181
+ readonly error?: string | null;
182
+ readonly priority?: number;
183
+ readonly model?: string | null;
184
+ readonly systemPrompt?: string | null;
185
+ readonly initialMessages?: unknown;
186
+ readonly calltype?: AgentRunCallType | null;
187
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,147 @@
1
+ import type { AgentRunPatch, AgentRunRow, NewAgentRun } from "./AgentRun.js";
2
+ import type { Logger } from "./logging/Logger.js";
3
+ import type { PostgresConnection } from "./PostgresConnection.js";
4
+ /**
5
+ * Disposer returned by {@link AgentRunBus.listen}. Calling it
6
+ * unsubscribes the handler from the underlying NOTIFY channel.
7
+ * Idempotent: calling more than once is safe.
8
+ */
9
+ export type AgentRunUnsubscribe = () => Promise<void>;
10
+ /**
11
+ * Domain client for the `agentruns` table — the assistant's response
12
+ * tree. Each row is one agent invocation that responds to (or descends
13
+ * from) an `events` row.
14
+ *
15
+ * Uses an injected {@link PostgresConnection} for pool + LISTEN access;
16
+ * does not own connection lifecycle.
17
+ *
18
+ * The bus is purely a CRUD surface — no claim queue, no in-process
19
+ * blocking primitive. The {@link import("@getfamiliar/container").AgentrunScheduler}
20
+ * is the sole authority on which row runs next and is guaranteed
21
+ * singleton inside the container, so a postgres-side claim queue
22
+ * (`FOR UPDATE SKIP LOCKED`) would be overkill. The Scheduler reads
23
+ * eligible pending rows via {@link listEligible} and writes lifecycle
24
+ * transitions via {@link update} / {@link settle} / {@link postpone}.
25
+ *
26
+ * The terminal write goes through {@link settle}, which transitions the
27
+ * agentrun to `done` / `failed` *and* recomputes the parent event's
28
+ * terminal state in the same transaction. That keeps the event
29
+ * terminal logic invariant-free — no counter to corrupt — at the cost
30
+ * of one extra query per terminal write.
31
+ */
32
+ export declare class AgentRunBus {
33
+ private readonly connection;
34
+ private readonly log;
35
+ constructor(connection: PostgresConnection, log?: Logger);
36
+ /**
37
+ * Apply the events + agentruns schema (idempotent). The same SQL
38
+ * bundle is consumed by {@link EventBus.installSchema}, so calling
39
+ * either is sufficient on daemon start.
40
+ */
41
+ installSchema(): Promise<void>;
42
+ /**
43
+ * Insert a new agentrun and return the persisted row.
44
+ *
45
+ * @throws If the underlying FK / check constraints reject the row
46
+ * (unknown `eventId`, malformed `topic`, invalid `calltype`).
47
+ */
48
+ add(run: NewAgentRun): Promise<AgentRunRow>;
49
+ /**
50
+ * Patch one or more fields on an existing agentrun by id. Always
51
+ * bumps `updated_at`. **Do not** use this to write a terminal state
52
+ * — use {@link settle} instead so the parent event's terminal state
53
+ * is recomputed in the same transaction.
54
+ */
55
+ update(id: string, patch: AgentRunPatch): Promise<void>;
56
+ /**
57
+ * Terminal write for an agentrun. Transitions the row to `done` or
58
+ * `failed`, optionally recording `result` / `resultText` / `error`,
59
+ * and recomputes the parent event's terminal state in the **same
60
+ * transaction**.
61
+ *
62
+ * The reactive event update is intentionally not a counter: it
63
+ * relies on the `agentruns(event_id)` index to check whether any
64
+ * sibling agentruns are still pending or running.
65
+ */
66
+ settle(id: string, toState: "done" | "failed", outcome?: {
67
+ readonly result?: unknown;
68
+ readonly resultText?: string | null;
69
+ readonly error?: string | null;
70
+ }): Promise<void>;
71
+ /**
72
+ * Fetch one agentrun by id, or `undefined` when missing.
73
+ */
74
+ getById(id: string): Promise<AgentRunRow | undefined>;
75
+ /**
76
+ * Fetch every agentrun in `state='pending'` whose `not_before` window
77
+ * has opened, in dispatch order (`priority desc, id asc`). The
78
+ * {@link AgentrunScheduler} calls this once per scheduling pass.
79
+ *
80
+ * Returns an empty array when nothing is ready. The Scheduler then
81
+ * waits on its NOTIFY subscription or a parked `not_before` timer
82
+ * before re-checking.
83
+ */
84
+ listEligible(): Promise<readonly AgentRunRow[]>;
85
+ /**
86
+ * `true` when every `calltype='started'` child of `parentId` is in
87
+ * a terminal state (`done` / `failed`). Used by the Scheduler
88
+ * after a started child settles, to decide whether the parent can
89
+ * leave `waiting` and go back to `pending`.
90
+ *
91
+ * Returns `true` when there are no started children at all (the
92
+ * trivially-vacuous case); the Scheduler still owns the "should
93
+ * we actually re-pend this parent?" decision and only invokes
94
+ * this method when at least one started child has just settled.
95
+ */
96
+ areAllStartedChildrenSettled(parentId: string): Promise<boolean>;
97
+ /**
98
+ * Fetch all agentrun rows whose `updated_at` is `>= since`, ordered
99
+ * by `(updated_at, id)`. Used by the polling-based report layer to
100
+ * pick up new agentruns and state transitions without NOTIFY.
101
+ */
102
+ listSince(since: Date): Promise<AgentRunRow[]>;
103
+ /**
104
+ * Fetch all agentruns belonging to one event, ordered by id.
105
+ * Used by the report layer to aggregate token totals and runtime
106
+ * across an event's full agentrun tree at finalization time.
107
+ */
108
+ listByEventId(eventId: string): Promise<readonly AgentRunRow[]>;
109
+ /**
110
+ * Postpone an agentrun after a retryable inference error.
111
+ * Returns the row to `pending`, bumps `retry_count`, sets
112
+ * `not_before` to the supplied timestamp, and records the latest
113
+ * attempt's error text. The existing `agentruns_changed` UPDATE
114
+ * trigger fires on the state write so a NOTIFY-subscribed
115
+ * Scheduler wakes up — it just won't include the row in
116
+ * {@link listEligible} until `not_before` passes.
117
+ *
118
+ * Throws if the row is missing (mirrors {@link settle}).
119
+ */
120
+ postpone(id: string, runAfter: Date, errorText: string | null): Promise<void>;
121
+ /**
122
+ * Subscribe to {@link AGENTRUNS_CHANNEL}. The notification payload
123
+ * (`<event_id>:<id>`) is parsed, the row is fetched by id, and
124
+ * `handler` is invoked with it. Fires on both INSERT and state
125
+ * UPDATE — callers that only care about one transition must filter
126
+ * on `row.state` themselves.
127
+ *
128
+ * Errors thrown by `handler` are caught and logged so one bad
129
+ * subscriber doesn't break others on the same channel.
130
+ *
131
+ * Returns a disposer; call it to unlisten. Idempotent.
132
+ *
133
+ * The {@link AgentrunScheduler} subscribes via
134
+ * {@link PostgresConnection.listen} directly (it only needs a
135
+ * "something changed" wake hint, not full row fetches); this
136
+ * helper exists for host-side consumers like
137
+ * `HostContext.events.emit`'s `onAgentRun` callback.
138
+ */
139
+ listen(handler: (row: AgentRunRow) => void | Promise<void>): Promise<AgentRunUnsubscribe>;
140
+ /**
141
+ * Inner notification dispatcher for {@link listen}. Parses the
142
+ * channel payload (`<event_id>:<id>`), fetches the row by id, and
143
+ * invokes the handler — catching and logging any error from the
144
+ * handler itself.
145
+ */
146
+ private dispatchNotification;
147
+ }