@ftrdotdev/pi-delegates 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +128 -0
- package/LICENSE +21 -0
- package/OPERATIONS.md +130 -0
- package/README.md +456 -2
- package/ROADMAP.md +179 -0
- package/TESTING.md +896 -0
- package/agents.ts +8 -0
- package/examples/README.md +114 -0
- package/examples/gated.ts +28 -0
- package/index.ts +9 -0
- package/package.json +94 -4
- package/skills/pi-delegates/SKILL.md +176 -0
- package/skills/pi-delegates/references/control.md +159 -0
- package/skills/pi-delegates/references/definitions.md +163 -0
- package/skills/pi-delegates/references/gates.md +175 -0
- package/skills/pi-delegates/references/launch.md +184 -0
- package/src/docs-contract.test.ts +106 -0
- package/src/domain/definitions.test.ts +41 -0
- package/src/domain/definitions.ts +163 -0
- package/src/domain/failure.ts +33 -0
- package/src/domain/ids.ts +13 -0
- package/src/domain/model-source.ts +30 -0
- package/src/domain/names.ts +35 -0
- package/src/domain/orchestration/admission.ts +78 -0
- package/src/domain/orchestration/control.test.ts +1332 -0
- package/src/domain/orchestration/control.ts +457 -0
- package/src/domain/orchestration/fanout.test.ts +524 -0
- package/src/domain/orchestration/fanout.ts +372 -0
- package/src/domain/orchestration/gates.test.ts +685 -0
- package/src/domain/orchestration/gates.ts +360 -0
- package/src/domain/orchestration/launch.test.ts +372 -0
- package/src/domain/orchestration/launch.ts +691 -0
- package/src/domain/orchestration/requests.test.ts +695 -0
- package/src/domain/orchestration/requests.ts +782 -0
- package/src/domain/orchestration/review.test.ts +292 -0
- package/src/domain/orchestration/review.ts +168 -0
- package/src/domain/orchestration/run-wait.test.ts +265 -0
- package/src/domain/orchestration/run-wait.ts +256 -0
- package/src/domain/orchestration/workflow-section.test.ts +62 -0
- package/src/domain/orchestration/workflow-section.ts +99 -0
- package/src/domain/orchestration/workflow.test.ts +1566 -0
- package/src/domain/orchestration/workflow.ts +778 -0
- package/src/domain/run-records.test.ts +27 -0
- package/src/domain/run-records.ts +689 -0
- package/src/domain/settlement.test.ts +186 -0
- package/src/domain/settlement.ts +137 -0
- package/src/domain/shapes.test.ts +185 -0
- package/src/domain/skills.test.ts +477 -0
- package/src/domain/skills.ts +114 -0
- package/src/domain/tool-schema.test.ts +46 -0
- package/src/domain/tool-schema.ts +20 -0
- package/src/domain/toolkit.test.ts +215 -0
- package/src/domain/toolkit.ts +374 -0
- package/src/domain/turn-budget.test.ts +37 -0
- package/src/domain/turn-budget.ts +23 -0
- package/src/domain/view.test.ts +803 -0
- package/src/domain/view.ts +491 -0
- package/src/example.test.ts +15 -0
- package/src/extension/commands.test.ts +485 -0
- package/src/extension/commands.ts +230 -0
- package/src/extension/entry.test.ts +1276 -0
- package/src/extension/entry.ts +380 -0
- package/src/extension/gate-alerts.test.ts +237 -0
- package/src/extension/gate-alerts.ts +143 -0
- package/src/extension/guard.test.ts +48 -0
- package/src/extension/guard.ts +31 -0
- package/src/extension/host-signals.test.ts +20 -0
- package/src/extension/host-signals.ts +13 -0
- package/src/extension/inspector-command.test.ts +1343 -0
- package/src/extension/inspector-command.ts +685 -0
- package/src/extension/prompt.test.ts +108 -0
- package/src/extension/prompt.ts +50 -0
- package/src/extension/request-alerts.test.ts +183 -0
- package/src/extension/request-alerts.ts +181 -0
- package/src/extension/retry-observer.test.ts +292 -0
- package/src/extension/retry-observer.ts +150 -0
- package/src/extension/revocation.test.ts +81 -0
- package/src/extension/revocation.ts +84 -0
- package/src/extension/settle-alerts.test.ts +579 -0
- package/src/extension/settle-alerts.ts +175 -0
- package/src/extension/shortcut.test.ts +62 -0
- package/src/extension/shortcut.ts +105 -0
- package/src/extension/tools.test.ts +1294 -0
- package/src/extension/tools.ts +553 -0
- package/src/extension/version.test.ts +115 -0
- package/src/extension/version.ts +97 -0
- package/src/goldens.test.ts +294 -0
- package/src/harness-policy.test.ts +76 -0
- package/src/layers.test.ts +309 -0
- package/src/layers.ts +405 -0
- package/src/package-manifest.test.ts +170 -0
- package/src/presentation/actions.test.ts +221 -0
- package/src/presentation/actions.ts +85 -0
- package/src/presentation/activity.test.ts +386 -0
- package/src/presentation/activity.ts +66 -0
- package/src/presentation/close.test.ts +359 -0
- package/src/presentation/inspector.test.ts +682 -0
- package/src/presentation/inspector.ts +442 -0
- package/src/presentation/overlay.test.ts +553 -0
- package/src/presentation/overlay.ts +229 -0
- package/src/presentation/repaint.test.ts +365 -0
- package/src/presentation/shortcut.ts +2 -0
- package/src/presentation/snapshot.test.ts +535 -0
- package/src/presentation/snapshot.ts +306 -0
- package/src/presentation/status.test.ts +43 -0
- package/src/presentation/status.ts +30 -0
- package/src/presentation/strip.test.ts +203 -0
- package/src/presentation/strip.ts +67 -0
- package/src/presentation/wording.test.ts +388 -0
- package/src/presentation/wording.ts +294 -0
- package/src/runtime/bridge.test.ts +131 -0
- package/src/runtime/bridge.ts +128 -0
- package/src/runtime/clock.test.ts +31 -0
- package/src/runtime/clock.ts +31 -0
- package/src/runtime/config.test.ts +63 -0
- package/src/runtime/config.ts +92 -0
- package/src/runtime/context.test.ts +19 -0
- package/src/runtime/context.ts +9 -0
- package/src/runtime/execution-env.test.ts +33 -0
- package/src/runtime/execution-env.ts +15 -0
- package/src/runtime/extensions.test.ts +86 -0
- package/src/runtime/extensions.ts +152 -0
- package/src/runtime/handle.ts +54 -0
- package/src/runtime/log.test.ts +140 -0
- package/src/runtime/log.ts +91 -0
- package/src/runtime/mcp.test.ts +1450 -0
- package/src/runtime/mcp.ts +1005 -0
- package/src/runtime/models.test.ts +145 -0
- package/src/runtime/models.ts +259 -0
- package/src/runtime/observe.test.ts +50 -0
- package/src/runtime/observe.ts +150 -0
- package/src/runtime/runtime-state.test.ts +25 -0
- package/src/runtime/runtime-state.ts +36 -0
- package/src/runtime/session-tag.ts +11 -0
- package/src/runtime/session.test.ts +352 -0
- package/src/runtime/session.ts +263 -0
- package/src/runtime/storage.ts +29 -0
- package/src/test-hygiene.test.ts +97 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
2
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
3
|
+
import { createRegistry, Harness, MemoryStorage } from "@earendil-works/pi-durable";
|
|
4
|
+
import { assert, it } from "@effect/vitest";
|
|
5
|
+
import {
|
|
6
|
+
stubHostSource,
|
|
7
|
+
stubModel,
|
|
8
|
+
STUB_MODEL_ID,
|
|
9
|
+
STUB_PROVIDER,
|
|
10
|
+
} from "../../test-support/stub-model-source.ts";
|
|
11
|
+
import {
|
|
12
|
+
HostModelAdapter,
|
|
13
|
+
UnsupportedModelCapability,
|
|
14
|
+
type UnsupportedCapability,
|
|
15
|
+
} from "./models.ts";
|
|
16
|
+
|
|
17
|
+
const answerText = async (harness: Harness, conversationId: number): Promise<string> => {
|
|
18
|
+
const conversation = await harness.conversation(conversationId as never, BACKGROUND_CONTEXT);
|
|
19
|
+
assert.ok(conversation);
|
|
20
|
+
const view = await conversation.context(BACKGROUND_CONTEXT);
|
|
21
|
+
const last = [...view.messages].reverse().find((message) => message.role === "assistant") as
|
|
22
|
+
| AssistantMessage
|
|
23
|
+
| undefined;
|
|
24
|
+
return (last?.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("");
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
it("a durable run is answered by the host registry's model", async () => {
|
|
28
|
+
const host = stubHostSource({ text: "hello" });
|
|
29
|
+
const harness = await Harness.open(
|
|
30
|
+
new MemoryStorage(),
|
|
31
|
+
{ models: new HostModelAdapter(host), registry: createRegistry() },
|
|
32
|
+
BACKGROUND_CONTEXT,
|
|
33
|
+
);
|
|
34
|
+
try {
|
|
35
|
+
const root = await harness.root(BACKGROUND_CONTEXT, {
|
|
36
|
+
agent: { model: { provider: STUB_PROVIDER, modelId: STUB_MODEL_ID } },
|
|
37
|
+
});
|
|
38
|
+
const settled = await (
|
|
39
|
+
await root.submit({ type: "input", content: "hi" }, BACKGROUND_CONTEXT)
|
|
40
|
+
).wait(BACKGROUND_CONTEXT);
|
|
41
|
+
assert.strictEqual(settled.status, "done");
|
|
42
|
+
assert.strictEqual(await answerText(harness, root.id as unknown as number), "hello");
|
|
43
|
+
assert.deepStrictEqual(host.calls, [{ provider: STUB_PROVIDER, modelId: STUB_MODEL_ID }]);
|
|
44
|
+
} finally {
|
|
45
|
+
await harness.close(BACKGROUND_CONTEXT);
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("simple completion is served from the streamed result", async () => {
|
|
50
|
+
const host = stubHostSource({ text: "short" });
|
|
51
|
+
const adapter = new HostModelAdapter(host);
|
|
52
|
+
const message = await adapter.completeSimple(stubModel, { messages: [] });
|
|
53
|
+
assert.strictEqual(message.content[0]?.type, "text");
|
|
54
|
+
assert.strictEqual(message.content[0]?.type === "text" ? message.content[0].text : "", "short");
|
|
55
|
+
assert.strictEqual(host.streamSimpleCalls, 1);
|
|
56
|
+
assert.strictEqual(host.completeSimpleCalls, 0);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const unsupportedMembers: ReadonlyArray<{
|
|
60
|
+
readonly capability: UnsupportedCapability;
|
|
61
|
+
readonly call: (adapter: HostModelAdapter) => unknown;
|
|
62
|
+
}> = [
|
|
63
|
+
{ capability: "providerEnumeration", call: (adapter) => adapter.getProviders() },
|
|
64
|
+
{ capability: "providerSignIn", call: (adapter) => adapter.login() },
|
|
65
|
+
{ capability: "providerSignOut", call: (adapter) => adapter.logout("stub") },
|
|
66
|
+
{ capability: "deferredStream", call: (adapter) => adapter.streamDeferred() },
|
|
67
|
+
{ capability: "deferredFetch", call: (adapter) => adapter.fetchDeferred(stubModel) },
|
|
68
|
+
{ capability: "deferredCancel", call: (adapter) => adapter.cancelDeferred(stubModel) },
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
it("each unsupported capability names itself", async () => {
|
|
72
|
+
const host = stubHostSource();
|
|
73
|
+
const adapter = new HostModelAdapter(host);
|
|
74
|
+
for (const { capability, call } of unsupportedMembers) {
|
|
75
|
+
let caught: unknown;
|
|
76
|
+
try {
|
|
77
|
+
await call(adapter);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
caught = error;
|
|
80
|
+
}
|
|
81
|
+
assert.ok(caught instanceof UnsupportedModelCapability, capability);
|
|
82
|
+
assert.strictEqual(caught.capability, capability);
|
|
83
|
+
assert.ok(caught.message.includes(capability), caught.message);
|
|
84
|
+
const namesProvider =
|
|
85
|
+
capability === "providerSignOut" ||
|
|
86
|
+
capability === "deferredFetch" ||
|
|
87
|
+
capability === "deferredCancel";
|
|
88
|
+
if (namesProvider) assert.ok(caught.message.includes("stub"), caught.message);
|
|
89
|
+
}
|
|
90
|
+
assert.deepStrictEqual(host.calls, []);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("catalogue and auth reads come from the facade", async () => {
|
|
94
|
+
const host = stubHostSource();
|
|
95
|
+
const adapter = new HostModelAdapter(host);
|
|
96
|
+
assert.deepStrictEqual(adapter.getModelsOfType("chat"), [stubModel]);
|
|
97
|
+
assert.deepStrictEqual(await adapter.getAvailableOfType("chat"), [stubModel]);
|
|
98
|
+
assert.deepStrictEqual(await adapter.getAuth("stub"), { auth: {}, source: "api-key" });
|
|
99
|
+
assert.deepStrictEqual(await adapter.checkAuth("stub"), {
|
|
100
|
+
type: "api_key",
|
|
101
|
+
source: "environment",
|
|
102
|
+
});
|
|
103
|
+
assert.strictEqual(adapter.getModel(STUB_PROVIDER, STUB_MODEL_ID)?.id, STUB_MODEL_ID);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("an unknown model produces the host's error, not a substitute", async () => {
|
|
107
|
+
const host = stubHostSource();
|
|
108
|
+
const harness = await Harness.open(
|
|
109
|
+
new MemoryStorage(),
|
|
110
|
+
{ models: new HostModelAdapter(host), registry: createRegistry() },
|
|
111
|
+
BACKGROUND_CONTEXT,
|
|
112
|
+
);
|
|
113
|
+
try {
|
|
114
|
+
const root = await harness.root(BACKGROUND_CONTEXT, {
|
|
115
|
+
agent: { model: { provider: STUB_PROVIDER, modelId: "missing" } },
|
|
116
|
+
});
|
|
117
|
+
const settled = await (
|
|
118
|
+
await root.submit({ type: "input", content: "hi" }, BACKGROUND_CONTEXT)
|
|
119
|
+
).wait(BACKGROUND_CONTEXT);
|
|
120
|
+
assert.strictEqual(settled.status, "unanswered");
|
|
121
|
+
assert.strictEqual(settled.status === "unanswered" ? settled.reason : undefined, "no_model");
|
|
122
|
+
assert.deepStrictEqual(host.calls, []);
|
|
123
|
+
} finally {
|
|
124
|
+
await harness.close(BACKGROUND_CONTEXT);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("getAvailable filters by provider and forwards auth options", async () => {
|
|
129
|
+
const other = { ...stubModel, id: "other-1", provider: "other" };
|
|
130
|
+
const host = stubHostSource({
|
|
131
|
+
models: [stubModel, other],
|
|
132
|
+
available: [stubModel, other] as never,
|
|
133
|
+
});
|
|
134
|
+
const calls: unknown[][] = [];
|
|
135
|
+
const original = host.getAvailableOfType;
|
|
136
|
+
host.getAvailableOfType = (async (...args: unknown[]) => {
|
|
137
|
+
calls.push(args);
|
|
138
|
+
return (original as (...inner: unknown[]) => unknown)(...args);
|
|
139
|
+
}) as typeof host.getAvailableOfType;
|
|
140
|
+
const adapter = new HostModelAdapter(host);
|
|
141
|
+
const options = { signal: new AbortController().signal };
|
|
142
|
+
assert.deepStrictEqual(await adapter.getAvailable("stub", options), [stubModel]);
|
|
143
|
+
assert.deepStrictEqual(await adapter.getAvailable(), [stubModel, other]);
|
|
144
|
+
assert.deepStrictEqual(calls[0], ["chat", "stub", options]);
|
|
145
|
+
});
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type {
|
|
3
|
+
AnyModel,
|
|
4
|
+
Api,
|
|
5
|
+
AssistantImages,
|
|
6
|
+
AssistantMessage,
|
|
7
|
+
AssistantMessageEventStream,
|
|
8
|
+
AuthOperationOptions,
|
|
9
|
+
ClassifierApi,
|
|
10
|
+
ClassifierContext,
|
|
11
|
+
ClassifierModel,
|
|
12
|
+
ClassifierResult,
|
|
13
|
+
Context,
|
|
14
|
+
ImageApi,
|
|
15
|
+
ImageModel,
|
|
16
|
+
ImagesContext,
|
|
17
|
+
Model,
|
|
18
|
+
ModelType,
|
|
19
|
+
ModelTypeMap,
|
|
20
|
+
ModelsApiStreamOptions,
|
|
21
|
+
ModelsClassifierOptions,
|
|
22
|
+
ModelsImagesOptions,
|
|
23
|
+
ModelsRefreshOptions,
|
|
24
|
+
ModelsRefreshResult,
|
|
25
|
+
ModelsSimpleStreamOptions,
|
|
26
|
+
Provider,
|
|
27
|
+
} from "@earendil-works/pi-ai";
|
|
28
|
+
import type { Models } from "@earendil-works/pi-ai/models";
|
|
29
|
+
import { Schema } from "effect";
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The facade subset this adapter may read. A `Pick`, so `tsc` fails when the
|
|
33
|
+
* facade moves.
|
|
34
|
+
*/
|
|
35
|
+
export type HostModelSource = Pick<
|
|
36
|
+
ModelRegistry,
|
|
37
|
+
| "getProvider"
|
|
38
|
+
| "getAll"
|
|
39
|
+
| "getAvailable"
|
|
40
|
+
| "find"
|
|
41
|
+
| "getModelsOfType"
|
|
42
|
+
| "getModelOfType"
|
|
43
|
+
| "getAvailableOfType"
|
|
44
|
+
| "getProviderAuthStatus"
|
|
45
|
+
| "getProviderAuth"
|
|
46
|
+
| "isUsingOAuth"
|
|
47
|
+
| "refresh"
|
|
48
|
+
| "stream"
|
|
49
|
+
| "streamSimple"
|
|
50
|
+
| "complete"
|
|
51
|
+
| "classify"
|
|
52
|
+
| "generateImages"
|
|
53
|
+
>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The facade's members that the durable `Models` contract needs and the
|
|
57
|
+
* ModelRegistry cannot serve. Every one rejects or throws; none is emulated.
|
|
58
|
+
*
|
|
59
|
+
* | `Models` member | ModelRegistry 1.6.0 |
|
|
60
|
+
* | --- | --- |
|
|
61
|
+
* | `getProviders` | no provider enumeration |
|
|
62
|
+
* | `login` | owned by Pi's `/login` |
|
|
63
|
+
* | `logout` | owned by Pi's `/logout` |
|
|
64
|
+
* | `streamDeferred` | no deferred transport |
|
|
65
|
+
* | `fetchDeferred` | no deferred transport |
|
|
66
|
+
* | `cancelDeferred` | no deferred transport |
|
|
67
|
+
*/
|
|
68
|
+
export const UnsupportedCapability = Schema.Union([
|
|
69
|
+
Schema.Literal("providerSignIn"),
|
|
70
|
+
Schema.Literal("providerSignOut"),
|
|
71
|
+
Schema.Literal("deferredStream"),
|
|
72
|
+
Schema.Literal("deferredFetch"),
|
|
73
|
+
Schema.Literal("deferredCancel"),
|
|
74
|
+
Schema.Literal("providerEnumeration"),
|
|
75
|
+
]);
|
|
76
|
+
export type UnsupportedCapability = typeof UnsupportedCapability.Type;
|
|
77
|
+
|
|
78
|
+
export class UnsupportedModelCapability extends Schema.TaggedError<
|
|
79
|
+
UnsupportedModelCapability,
|
|
80
|
+
{ readonly brand: unique symbol }
|
|
81
|
+
>()("UnsupportedModelCapability", { capability: UnsupportedCapability, message: Schema.String }) {}
|
|
82
|
+
|
|
83
|
+
const unsupported = (
|
|
84
|
+
capability: UnsupportedCapability,
|
|
85
|
+
provider: string | undefined,
|
|
86
|
+
): UnsupportedModelCapability =>
|
|
87
|
+
UnsupportedModelCapability.make({
|
|
88
|
+
capability,
|
|
89
|
+
message:
|
|
90
|
+
`The host's model registry cannot serve ${capability}` +
|
|
91
|
+
(provider === undefined ? "." : ` for provider ${provider}.`),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const MODEL_TYPES: readonly ModelType[] = ["chat", "image", "classifier"];
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Presents the host session's `ModelRegistry` as the durable runtime's
|
|
98
|
+
* `Models`. Catalogue and auth reads pass through; six capabilities the facade
|
|
99
|
+
* cannot serve reject with a typed error naming the capability and provider.
|
|
100
|
+
*/
|
|
101
|
+
export class HostModelAdapter implements Models {
|
|
102
|
+
constructor(private readonly host: HostModelSource) {}
|
|
103
|
+
|
|
104
|
+
getProviders(): readonly Provider[] {
|
|
105
|
+
throw unsupported("providerEnumeration", undefined);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
getProvider(id: string): Provider | undefined {
|
|
109
|
+
return this.host.getProvider(id);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
getModels(provider?: string): readonly Model<Api>[] {
|
|
113
|
+
const models = this.host.getAll();
|
|
114
|
+
return provider === undefined ? models : models.filter((model) => model.provider === provider);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
getModel(provider: string, id: string): Model<Api> | undefined {
|
|
118
|
+
return this.host.find(provider, id);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
getModelsOfType<TType extends ModelType>(
|
|
122
|
+
type: TType,
|
|
123
|
+
provider?: string,
|
|
124
|
+
): readonly ModelTypeMap[TType][] {
|
|
125
|
+
return this.host.getModelsOfType(type, provider);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
getModelOfType<TType extends ModelType>(
|
|
129
|
+
type: TType,
|
|
130
|
+
provider: string,
|
|
131
|
+
id: string,
|
|
132
|
+
): ModelTypeMap[TType] | undefined {
|
|
133
|
+
return this.host.getModelOfType(type, provider, id);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
getAllModels(provider?: string): readonly AnyModel[] {
|
|
137
|
+
return MODEL_TYPES.flatMap((type) => this.host.getModelsOfType(type, provider));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
refresh(options?: ModelsRefreshOptions): Promise<ModelsRefreshResult> {
|
|
141
|
+
return this.host.refresh(options);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async checkAuth(
|
|
145
|
+
providerId: string,
|
|
146
|
+
_options?: AuthOperationOptions,
|
|
147
|
+
): Promise<{ readonly source?: string; readonly type: "api_key" | "oauth" } | undefined> {
|
|
148
|
+
const status = this.host.getProviderAuthStatus(providerId);
|
|
149
|
+
if (!status.configured) return undefined;
|
|
150
|
+
const model = this.getModels(providerId)[0];
|
|
151
|
+
const type = model !== undefined && this.host.isUsingOAuth(model) ? "oauth" : "api_key";
|
|
152
|
+
return status.source === undefined ? { type } : { type, source: status.source };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async getAvailable(
|
|
156
|
+
providerId?: string,
|
|
157
|
+
options?: AuthOperationOptions,
|
|
158
|
+
): Promise<readonly Model<Api>[]> {
|
|
159
|
+
const available = await Promise.all(
|
|
160
|
+
MODEL_TYPES.map((type) => this.host.getAvailableOfType(type, providerId, options)),
|
|
161
|
+
);
|
|
162
|
+
return (available.flat() as readonly Model<Api>[]).filter(
|
|
163
|
+
(model) => providerId === undefined || model.provider === providerId,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
getAvailableOfType<TType extends ModelType>(
|
|
168
|
+
type: TType,
|
|
169
|
+
providerId?: string,
|
|
170
|
+
options?: AuthOperationOptions,
|
|
171
|
+
): Promise<readonly ModelTypeMap[TType][]> {
|
|
172
|
+
return this.host.getAvailableOfType(type, providerId, options);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async getAllAvailable(
|
|
176
|
+
providerId?: string,
|
|
177
|
+
options?: AuthOperationOptions,
|
|
178
|
+
): Promise<readonly AnyModel[]> {
|
|
179
|
+
const available: AnyModel[] = [];
|
|
180
|
+
for (const type of MODEL_TYPES) {
|
|
181
|
+
available.push(...(await this.host.getAvailableOfType(type, providerId, options)));
|
|
182
|
+
}
|
|
183
|
+
return available;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
readonly getAuth: Models["getAuth"] = (modelOrProvider: string | AnyModel) => {
|
|
187
|
+
const provider =
|
|
188
|
+
typeof modelOrProvider === "string" ? modelOrProvider : modelOrProvider.provider;
|
|
189
|
+
return this.host.getProviderAuth(provider);
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
login(): Promise<never> {
|
|
193
|
+
return Promise.reject(unsupported("providerSignIn", undefined));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
logout(providerId: string): Promise<never> {
|
|
197
|
+
return Promise.reject(unsupported("providerSignOut", providerId));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
stream<TApi extends Api>(
|
|
201
|
+
model: Model<TApi>,
|
|
202
|
+
context: Context,
|
|
203
|
+
options?: ModelsApiStreamOptions<TApi>,
|
|
204
|
+
): AssistantMessageEventStream {
|
|
205
|
+
return this.host.stream(model, context, options);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
complete<TApi extends Api>(
|
|
209
|
+
model: Model<TApi>,
|
|
210
|
+
context: Context,
|
|
211
|
+
options?: ModelsApiStreamOptions<TApi>,
|
|
212
|
+
): Promise<AssistantMessage> {
|
|
213
|
+
return this.host.complete(model, context, options);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
streamSimple(
|
|
217
|
+
model: Model<Api>,
|
|
218
|
+
context: Context,
|
|
219
|
+
options?: ModelsSimpleStreamOptions,
|
|
220
|
+
): AssistantMessageEventStream {
|
|
221
|
+
return this.host.streamSimple(model, context, options);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
completeSimple(
|
|
225
|
+
model: Model<Api>,
|
|
226
|
+
context: Context,
|
|
227
|
+
options?: ModelsSimpleStreamOptions,
|
|
228
|
+
): Promise<AssistantMessage> {
|
|
229
|
+
return this.streamSimple(model, context, options).result();
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
streamDeferred(): AssistantMessageEventStream {
|
|
233
|
+
throw unsupported("deferredStream", undefined);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
fetchDeferred(model: Model<Api>): Promise<never> {
|
|
237
|
+
return Promise.reject(unsupported("deferredFetch", model.provider));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
cancelDeferred(model: Model<Api>): Promise<never> {
|
|
241
|
+
return Promise.reject(unsupported("deferredCancel", model.provider));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
generateImages(
|
|
245
|
+
model: ImageModel<ImageApi>,
|
|
246
|
+
context: ImagesContext,
|
|
247
|
+
options?: ModelsImagesOptions,
|
|
248
|
+
): Promise<AssistantImages> {
|
|
249
|
+
return this.host.generateImages(model, context, options);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
classify(
|
|
253
|
+
model: ClassifierModel<ClassifierApi>,
|
|
254
|
+
context: ClassifierContext,
|
|
255
|
+
options?: ModelsClassifierOptions,
|
|
256
|
+
): Promise<ClassifierResult> {
|
|
257
|
+
return this.host.classify(model, context, options);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { assert, it } from "@effect/vitest";
|
|
2
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
3
|
+
import { endOf, sinkObserver } from "./observe.ts";
|
|
4
|
+
|
|
5
|
+
it("a permanent source failure folds to failed with its message", () => {
|
|
6
|
+
assert.deepStrictEqual(endOf({ kind: "failed", error: new Error("boom") }), {
|
|
7
|
+
kind: "failed",
|
|
8
|
+
reason: "boom",
|
|
9
|
+
});
|
|
10
|
+
assert.deepStrictEqual(endOf({ kind: "listener_error", error: new Error("listener") }), {
|
|
11
|
+
kind: "failed",
|
|
12
|
+
reason: "listener",
|
|
13
|
+
});
|
|
14
|
+
assert.deepStrictEqual(endOf({ kind: "failed", error: "plain text" }), {
|
|
15
|
+
kind: "failed",
|
|
16
|
+
reason: "plain text",
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it("a retirement folds to ended, whatever retired the watch", () => {
|
|
21
|
+
for (const kind of ["stopped", "aborted", "ended"] as const) {
|
|
22
|
+
assert.deepStrictEqual(endOf({ kind }), { kind: "ended" });
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("the observer forwards a value and drops a recoverable failure", () => {
|
|
27
|
+
const values: string[] = [];
|
|
28
|
+
const observer = sinkObserver<string>({
|
|
29
|
+
advance: (value) => values.push(value),
|
|
30
|
+
end: () => assert.fail("the sink ended before the watch did"),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
observer.advance({ kind: "value", value: "one", ops: [], retired: false }, BACKGROUND_CONTEXT);
|
|
34
|
+
observer.advance({ kind: "failed", error: new Error("later") }, BACKGROUND_CONTEXT);
|
|
35
|
+
|
|
36
|
+
assert.deepStrictEqual(values, ["one"]);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("the observer ends the sink with the folded kind and reason", () => {
|
|
40
|
+
const ends: Array<{ readonly kind: string; readonly reason?: string }> = [];
|
|
41
|
+
const observer = sinkObserver<string>({
|
|
42
|
+
advance: () => assert.fail("an end must not advance the sink"),
|
|
43
|
+
end: (kind, reason) => ends.push({ kind, ...(reason === undefined ? {} : { reason }) }),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
observer.end({ kind: "failed", error: new Error("boom") });
|
|
47
|
+
observer.end({ kind: "stopped" });
|
|
48
|
+
|
|
49
|
+
assert.deepStrictEqual(ends, [{ kind: "failed", reason: "boom" }, { kind: "ended" }]);
|
|
50
|
+
});
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { JsonValue } from "@earendil-works/chord/json";
|
|
2
|
+
import type {
|
|
3
|
+
JsonObject,
|
|
4
|
+
Observer,
|
|
5
|
+
SessionDocFamilyToken,
|
|
6
|
+
SessionDocToken,
|
|
7
|
+
TaskGraph,
|
|
8
|
+
WatchCall,
|
|
9
|
+
WatchEnd,
|
|
10
|
+
} from "@earendil-works/pi-durable";
|
|
11
|
+
import type { RunActivity } from "../presentation/activity.ts";
|
|
12
|
+
import type { SessionRuntime } from "./session.ts";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What a consumer sees: a value per change, and one end. The harness's five
|
|
16
|
+
* end kinds fold to two here — `ended | stopped | aborted` are a retirement,
|
|
17
|
+
* `failed | listener_error` are a failure — because the consumer only asks
|
|
18
|
+
* "is this address gone, and do I retry or not".
|
|
19
|
+
*/
|
|
20
|
+
export interface DocSink<T> {
|
|
21
|
+
readonly advance: (value: Readonly<T>) => void;
|
|
22
|
+
readonly end: (kind: DocEndKind, reason?: string) => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type DocEndKind = "ended" | "failed";
|
|
26
|
+
|
|
27
|
+
/** How to detach one attached observation. Idempotent. */
|
|
28
|
+
export type Detach = () => void;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The observation boundary the live owner consumes. Addresses are the owner's
|
|
32
|
+
* names (`index:runs`, `run:<id>`, `gate:<run>:<gate>`, `graph:tasks`,
|
|
33
|
+
* `live:<conversation>`); the real seam maps each to a durable token.
|
|
34
|
+
*/
|
|
35
|
+
export interface ObservationSeam {
|
|
36
|
+
observeSessionDoc<T extends JsonObject>(
|
|
37
|
+
address: string,
|
|
38
|
+
token: SessionDocToken<T>,
|
|
39
|
+
sink: DocSink<T>,
|
|
40
|
+
): Promise<Detach | undefined>;
|
|
41
|
+
observeFamilyDoc<T extends JsonObject, I extends JsonValue>(
|
|
42
|
+
address: string,
|
|
43
|
+
token: SessionDocFamilyToken<T, I>,
|
|
44
|
+
key: string,
|
|
45
|
+
sink: DocSink<T>,
|
|
46
|
+
): Promise<Detach | undefined>;
|
|
47
|
+
observeTaskGraph(address: string, sink: DocSink<TaskGraph>): Promise<Detach>;
|
|
48
|
+
watchActivity(
|
|
49
|
+
address: string,
|
|
50
|
+
conversationId: number,
|
|
51
|
+
onActivity: (activity: RunActivity) => void,
|
|
52
|
+
onEnd?: (kind: DocEndKind, reason?: string) => void,
|
|
53
|
+
): Promise<Detach>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The fold table, shared by every observation in the package. */
|
|
57
|
+
export const endOf = (end: WatchEnd): { readonly kind: DocEndKind; readonly reason?: string } =>
|
|
58
|
+
end.kind === "failed" || end.kind === "listener_error"
|
|
59
|
+
? {
|
|
60
|
+
kind: "failed",
|
|
61
|
+
reason: end.error instanceof Error ? end.error.message : String(end.error),
|
|
62
|
+
}
|
|
63
|
+
: { kind: "ended" };
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The one observer every helper wraps its sink in. `advance` records and
|
|
67
|
+
* returns: it may not await, may not call a Session API, and must not throw.
|
|
68
|
+
*/
|
|
69
|
+
export const sinkObserver = <T>(sink: DocSink<T>): Observer<Readonly<T>> => ({
|
|
70
|
+
advance(call: WatchCall<Readonly<T>>) {
|
|
71
|
+
if (call.kind !== "value") return;
|
|
72
|
+
sink.advance(call.value);
|
|
73
|
+
},
|
|
74
|
+
end(end: WatchEnd) {
|
|
75
|
+
const folded = endOf(end);
|
|
76
|
+
sink.end(folded.kind, folded.reason);
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Observe one session-scoped document. `undefined` when the address is absent,
|
|
82
|
+
* which the caller treats as a request it retries on its next fold. The sink
|
|
83
|
+
* sees the value at attach, then one value per change at that address.
|
|
84
|
+
*/
|
|
85
|
+
export const observeSessionDoc = async <T extends JsonObject>(
|
|
86
|
+
runtime: SessionRuntime,
|
|
87
|
+
token: SessionDocToken<T>,
|
|
88
|
+
sink: DocSink<T>,
|
|
89
|
+
): Promise<Detach | undefined> => {
|
|
90
|
+
let advanced = false;
|
|
91
|
+
const observer = sinkObserver<T>({
|
|
92
|
+
advance: (value) => {
|
|
93
|
+
advanced = true;
|
|
94
|
+
sink.advance(value);
|
|
95
|
+
},
|
|
96
|
+
end: (kind, reason) => sink.end(kind, reason),
|
|
97
|
+
});
|
|
98
|
+
const observation = await runtime.run((context) =>
|
|
99
|
+
runtime.harness.observeDoc(token, observer, context),
|
|
100
|
+
);
|
|
101
|
+
if (observation === undefined) return undefined;
|
|
102
|
+
if (!advanced) sink.advance(observation.value);
|
|
103
|
+
return () => observation.detach();
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** Observe one session-family document by key. `undefined` when the address is absent. */
|
|
107
|
+
export const observeFamilyDoc = async <T extends JsonObject, I extends JsonValue>(
|
|
108
|
+
runtime: SessionRuntime,
|
|
109
|
+
token: SessionDocFamilyToken<T, I>,
|
|
110
|
+
key: string,
|
|
111
|
+
sink: DocSink<T>,
|
|
112
|
+
): Promise<Detach | undefined> => {
|
|
113
|
+
let advanced = false;
|
|
114
|
+
const observer = sinkObserver<T>({
|
|
115
|
+
advance: (value) => {
|
|
116
|
+
advanced = true;
|
|
117
|
+
sink.advance(value);
|
|
118
|
+
},
|
|
119
|
+
end: (kind, reason) => sink.end(kind, reason),
|
|
120
|
+
});
|
|
121
|
+
const observation = await runtime.run((context) =>
|
|
122
|
+
runtime.harness.observeDoc(token, key, observer, context),
|
|
123
|
+
);
|
|
124
|
+
if (observation === undefined) return undefined;
|
|
125
|
+
if (!advanced) sink.advance(observation.value);
|
|
126
|
+
return () => observation.detach();
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Observe the session's task graph. Never absent: one attachment covers every
|
|
131
|
+
* live task, and it publishes only the nodes a commit changed.
|
|
132
|
+
*/
|
|
133
|
+
export const observeTaskGraph = async (
|
|
134
|
+
runtime: SessionRuntime,
|
|
135
|
+
sink: DocSink<TaskGraph>,
|
|
136
|
+
): Promise<Detach> => {
|
|
137
|
+
let advanced = false;
|
|
138
|
+
const observer = sinkObserver<TaskGraph>({
|
|
139
|
+
advance: (value) => {
|
|
140
|
+
advanced = true;
|
|
141
|
+
sink.advance(value);
|
|
142
|
+
},
|
|
143
|
+
end: (kind, reason) => sink.end(kind, reason),
|
|
144
|
+
});
|
|
145
|
+
const observation = await runtime.run((context) =>
|
|
146
|
+
runtime.harness.observeTaskGraph(observer, context),
|
|
147
|
+
);
|
|
148
|
+
if (!advanced) sink.advance(observation.value);
|
|
149
|
+
return () => observation.detach();
|
|
150
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { assert, it } from "@effect/vitest";
|
|
2
|
+
|
|
3
|
+
import { makeRuntimeState } from "./runtime-state.ts";
|
|
4
|
+
|
|
5
|
+
it("setState notifies every listener and a detached listener hears nothing", () => {
|
|
6
|
+
const machine = makeRuntimeState();
|
|
7
|
+
const heard: string[] = [];
|
|
8
|
+
const detach = machine.onState((state) => heard.push(state.kind));
|
|
9
|
+
machine.onState((state) => heard.push(`second:${state.kind}`));
|
|
10
|
+
|
|
11
|
+
machine.setState({ kind: "ready" });
|
|
12
|
+
detach();
|
|
13
|
+
machine.setState({ kind: "closed", reason: "stopped" });
|
|
14
|
+
|
|
15
|
+
assert.deepStrictEqual(heard, ["ready", "second:ready", "second:closed"]);
|
|
16
|
+
assert.deepStrictEqual(machine.state(), { kind: "closed", reason: "stopped" });
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("a fresh machine is opening and a listener never sees a state from before it attached", () => {
|
|
20
|
+
const machine = makeRuntimeState();
|
|
21
|
+
machine.setState({ kind: "ready" });
|
|
22
|
+
const heard: string[] = [];
|
|
23
|
+
machine.onState((state) => heard.push(state.kind));
|
|
24
|
+
assert.deepStrictEqual(heard, []);
|
|
25
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Where one session stands: the harness reports into it, and the surfaces read it. */
|
|
2
|
+
export type RuntimeState =
|
|
3
|
+
| { readonly kind: "opening" }
|
|
4
|
+
| { readonly kind: "ready" }
|
|
5
|
+
| { readonly kind: "failing"; readonly reason: string }
|
|
6
|
+
| { readonly kind: "closed"; readonly reason?: string };
|
|
7
|
+
|
|
8
|
+
/** The one mutable state and its listeners: the session's whole lifecycle surface. */
|
|
9
|
+
export interface RuntimeStateMachine {
|
|
10
|
+
readonly state: () => RuntimeState;
|
|
11
|
+
readonly setState: (state: RuntimeState) => void;
|
|
12
|
+
/** Registers a listener; the returned function detaches it. */
|
|
13
|
+
readonly onState: (listener: (state: RuntimeState) => void) => () => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A state value and its listener set, with no harness and no layer: a session
|
|
18
|
+
* starts `opening`, the harness moves it, and presentation subscribes.
|
|
19
|
+
*/
|
|
20
|
+
export const makeRuntimeState = (): RuntimeStateMachine => {
|
|
21
|
+
let state: RuntimeState = { kind: "opening" };
|
|
22
|
+
const listeners = new Set<(state: RuntimeState) => void>();
|
|
23
|
+
return {
|
|
24
|
+
state: () => state,
|
|
25
|
+
setState: (next) => {
|
|
26
|
+
state = next;
|
|
27
|
+
for (const listener of listeners) listener(next);
|
|
28
|
+
},
|
|
29
|
+
onState: (listener) => {
|
|
30
|
+
listeners.add(listener);
|
|
31
|
+
return () => {
|
|
32
|
+
listeners.delete(listener);
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Context as EffectContext } from "effect";
|
|
2
|
+
import type { SessionRuntime } from "./session.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The session's resolved runtime, as the graph provides it. A leaf module so
|
|
6
|
+
* `workflow.ts` can require it without loading `session.ts`, which reaches back
|
|
7
|
+
* to `workflow.ts` through `extensions.ts`.
|
|
8
|
+
*/
|
|
9
|
+
export class SessionRuntimeTag extends EffectContext.Service<SessionRuntimeTag, SessionRuntime>()(
|
|
10
|
+
"@ftrdotdev/pi-delegates/runtime/session-tag/SessionRuntimeTag",
|
|
11
|
+
) {}
|