@geminixiang/mikan 1.0.0-beta.20 → 1.0.0-beta.21
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 +34 -0
- package/README.md +18 -11
- package/dist/adapters/buffered-responder.d.ts +60 -0
- package/dist/adapters/buffered-responder.d.ts.map +1 -0
- package/dist/adapters/buffered-responder.js +201 -0
- package/dist/adapters/buffered-responder.js.map +1 -0
- package/dist/adapters/discord/context.d.ts.map +1 -1
- package/dist/adapters/discord/context.js +42 -177
- package/dist/adapters/discord/context.js.map +1 -1
- package/dist/adapters/github/bot.d.ts +14 -76
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +52 -443
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/client.d.ts +4 -0
- package/dist/adapters/github/client.d.ts.map +1 -1
- package/dist/adapters/github/client.js +5 -0
- package/dist/adapters/github/client.js.map +1 -1
- package/dist/adapters/github/context.d.ts.map +1 -1
- package/dist/adapters/github/context.js +32 -104
- package/dist/adapters/github/context.js.map +1 -1
- package/dist/adapters/github/github-ops.d.ts +90 -0
- package/dist/adapters/github/github-ops.d.ts.map +1 -0
- package/dist/adapters/github/github-ops.js +405 -0
- package/dist/adapters/github/github-ops.js.map +1 -0
- package/dist/adapters/github/repo.d.ts +2 -0
- package/dist/adapters/github/repo.d.ts.map +1 -1
- package/dist/adapters/github/repo.js +5 -0
- package/dist/adapters/github/repo.js.map +1 -1
- package/dist/adapters/github/tools/checks.d.ts.map +1 -1
- package/dist/adapters/github/tools/checks.js +6 -17
- package/dist/adapters/github/tools/checks.js.map +1 -1
- package/dist/adapters/github/tools/issue.d.ts.map +1 -1
- package/dist/adapters/github/tools/issue.js +6 -17
- package/dist/adapters/github/tools/issue.js.map +1 -1
- package/dist/adapters/github/tools/pr.d.ts.map +1 -1
- package/dist/adapters/github/tools/pr.js +6 -17
- package/dist/adapters/github/tools/pr.js.map +1 -1
- package/dist/adapters/github/tools/read.d.ts.map +1 -1
- package/dist/adapters/github/tools/read.js +6 -17
- package/dist/adapters/github/tools/read.js.map +1 -1
- package/dist/adapters/github/tools/review-reply.d.ts.map +1 -1
- package/dist/adapters/github/tools/review-reply.js +6 -17
- package/dist/adapters/github/tools/review-reply.js.map +1 -1
- package/dist/adapters/github/tools/sync.d.ts.map +1 -1
- package/dist/adapters/github/tools/sync.js +6 -17
- package/dist/adapters/github/tools/sync.js.map +1 -1
- package/dist/adapters/slack/bot.js +1 -1
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/telegram/context.d.ts.map +1 -1
- package/dist/adapters/telegram/context.js +33 -151
- package/dist/adapters/telegram/context.js.map +1 -1
- package/dist/agent.d.ts +0 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +28 -32
- package/dist/agent.js.map +1 -1
- package/dist/cli/arg-grammar.d.ts +25 -0
- package/dist/cli/arg-grammar.d.ts.map +1 -0
- package/dist/cli/arg-grammar.js +59 -0
- package/dist/cli/arg-grammar.js.map +1 -0
- package/dist/cli/boot.d.ts +16 -0
- package/dist/cli/boot.d.ts.map +1 -0
- package/dist/cli/boot.js +119 -0
- package/dist/cli/boot.js.map +1 -0
- package/dist/cli/ext.js +9 -11
- package/dist/cli/ext.js.map +1 -1
- package/dist/commands/extensions.js +2 -2
- package/dist/commands/extensions.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +5 -2
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +8 -8
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/sandbox.d.ts.map +1 -1
- package/dist/commands/sandbox.js +7 -5
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/config.d.ts +0 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +8 -41
- package/dist/config.js.map +1 -1
- package/dist/env-manifest.d.ts +35 -0
- package/dist/env-manifest.d.ts.map +1 -0
- package/dist/env-manifest.js +225 -0
- package/dist/env-manifest.js.map +1 -0
- package/dist/events.d.ts +0 -10
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +9 -82
- package/dist/events.js.map +1 -1
- package/dist/execution-resolver.d.ts +1 -0
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +33 -36
- package/dist/execution-resolver.js.map +1 -1
- package/dist/harness/event-format.d.ts +66 -0
- package/dist/harness/event-format.d.ts.map +1 -0
- package/dist/harness/event-format.js +112 -0
- package/dist/harness/event-format.js.map +1 -0
- package/dist/harness/extensions/loader.d.ts +9 -6
- package/dist/harness/extensions/loader.d.ts.map +1 -1
- package/dist/harness/extensions/loader.js +35 -50
- package/dist/harness/extensions/loader.js.map +1 -1
- package/dist/harness/extensions/types.d.ts +10 -14
- package/dist/harness/extensions/types.d.ts.map +1 -1
- package/dist/harness/extensions/types.js.map +1 -1
- package/dist/harness/index.d.ts +1 -0
- package/dist/harness/index.d.ts.map +1 -1
- package/dist/harness/index.js +1 -0
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/runner.d.ts +16 -0
- package/dist/harness/runner.d.ts.map +1 -1
- package/dist/harness/runner.js +27 -1
- package/dist/harness/runner.js.map +1 -1
- package/dist/harness/subagent-runner.d.ts +18 -1
- package/dist/harness/subagent-runner.d.ts.map +1 -1
- package/dist/harness/subagent-runner.js +62 -30
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/main.js +69 -121
- package/dist/main.js.map +1 -1
- package/dist/observability/instrument.js +6 -4
- package/dist/observability/instrument.js.map +1 -1
- package/dist/observability/sentry.d.ts.map +1 -1
- package/dist/observability/sentry.js +3 -2
- package/dist/observability/sentry.js.map +1 -1
- package/dist/runtime/conversation-runtime.js +13 -3
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/types.d.ts +4 -0
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/sandbox/cloudflare.d.ts +1 -0
- package/dist/sandbox/cloudflare.d.ts.map +1 -1
- package/dist/sandbox/cloudflare.js +4 -1
- package/dist/sandbox/cloudflare.js.map +1 -1
- package/dist/sandbox/container.d.ts +1 -0
- package/dist/sandbox/container.d.ts.map +1 -1
- package/dist/sandbox/container.js +4 -1
- package/dist/sandbox/container.js.map +1 -1
- package/dist/sandbox/firecracker.d.ts +1 -0
- package/dist/sandbox/firecracker.d.ts.map +1 -1
- package/dist/sandbox/firecracker.js +4 -1
- package/dist/sandbox/firecracker.js.map +1 -1
- package/dist/sandbox/gondolin-bootstrap.d.ts +26 -0
- package/dist/sandbox/gondolin-bootstrap.d.ts.map +1 -0
- package/dist/sandbox/gondolin-bootstrap.js +27 -0
- package/dist/sandbox/gondolin-bootstrap.js.map +1 -0
- package/dist/sandbox/gondolin-contract.d.ts +125 -0
- package/dist/sandbox/gondolin-contract.d.ts.map +1 -0
- package/dist/sandbox/gondolin-contract.js +155 -0
- package/dist/sandbox/gondolin-contract.js.map +1 -0
- package/dist/sandbox/gondolin-fleet.d.ts +1 -1
- package/dist/sandbox/gondolin-fleet.d.ts.map +1 -1
- package/dist/sandbox/gondolin-fleet.js +1 -1
- package/dist/sandbox/gondolin-fleet.js.map +1 -1
- package/dist/sandbox/gondolin-gateway.d.ts +1 -0
- package/dist/sandbox/gondolin-gateway.d.ts.map +1 -1
- package/dist/sandbox/gondolin-gateway.js +13 -6
- package/dist/sandbox/gondolin-gateway.js.map +1 -1
- package/dist/sandbox/gondolin-inventory.d.ts +2 -16
- package/dist/sandbox/gondolin-inventory.d.ts.map +1 -1
- package/dist/sandbox/gondolin-inventory.js +2 -12
- package/dist/sandbox/gondolin-inventory.js.map +1 -1
- package/dist/sandbox/gondolin-placement.d.ts +0 -2
- package/dist/sandbox/gondolin-placement.d.ts.map +1 -1
- package/dist/sandbox/gondolin-placement.js +0 -6
- package/dist/sandbox/gondolin-placement.js.map +1 -1
- package/dist/sandbox/gondolin-recovery.d.ts +33 -0
- package/dist/sandbox/gondolin-recovery.d.ts.map +1 -0
- package/dist/sandbox/gondolin-recovery.js +39 -0
- package/dist/sandbox/gondolin-recovery.js.map +1 -0
- package/dist/sandbox/gondolin-remote.d.ts +2 -5
- package/dist/sandbox/gondolin-remote.d.ts.map +1 -1
- package/dist/sandbox/gondolin-remote.js +12 -39
- package/dist/sandbox/gondolin-remote.js.map +1 -1
- package/dist/sandbox/gondolin-worker-client.d.ts +8 -12
- package/dist/sandbox/gondolin-worker-client.d.ts.map +1 -1
- package/dist/sandbox/gondolin-worker-client.js +13 -15
- package/dist/sandbox/gondolin-worker-client.js.map +1 -1
- package/dist/sandbox/gondolin-worker.d.ts +2 -40
- package/dist/sandbox/gondolin-worker.d.ts.map +1 -1
- package/dist/sandbox/gondolin-worker.js.map +1 -1
- package/dist/sandbox/gondolin.d.ts +1 -0
- package/dist/sandbox/gondolin.d.ts.map +1 -1
- package/dist/sandbox/gondolin.js +8 -4
- package/dist/sandbox/gondolin.js.map +1 -1
- package/dist/sandbox/host.d.ts +1 -0
- package/dist/sandbox/host.d.ts.map +1 -1
- package/dist/sandbox/host.js +3 -0
- package/dist/sandbox/host.js.map +1 -1
- package/dist/sandbox/index.d.ts +9 -1
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +14 -0
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/types.d.ts +5 -0
- package/dist/sandbox/types.d.ts.map +1 -1
- package/dist/sandbox/types.js.map +1 -1
- package/dist/sandbox/utils.d.ts +1 -0
- package/dist/sandbox/utils.d.ts.map +1 -1
- package/dist/sandbox/utils.js +5 -2
- package/dist/sandbox/utils.js.map +1 -1
- package/dist/sessions/chat-history-sync.d.ts +32 -0
- package/dist/sessions/chat-history-sync.d.ts.map +1 -0
- package/dist/sessions/{agent-memory-file-manager.js → chat-history-sync.js} +24 -83
- package/dist/sessions/chat-history-sync.js.map +1 -0
- package/dist/sessions/conversation-log.d.ts +13 -0
- package/dist/sessions/conversation-log.d.ts.map +1 -0
- package/dist/sessions/conversation-log.js +47 -0
- package/dist/sessions/conversation-log.js.map +1 -0
- package/dist/sessions/rotation.d.ts +2 -0
- package/dist/sessions/rotation.d.ts.map +1 -0
- package/dist/sessions/rotation.js +39 -0
- package/dist/sessions/rotation.js.map +1 -0
- package/dist/sessions/store.d.ts.map +1 -1
- package/dist/sessions/store.js +4 -10
- package/dist/sessions/store.js.map +1 -1
- package/dist/sessions/types.d.ts +2 -2
- package/dist/sessions/types.d.ts.map +1 -1
- package/dist/sessions/types.js.map +1 -1
- package/dist/settings-mutation.d.ts +23 -0
- package/dist/settings-mutation.d.ts.map +1 -0
- package/dist/settings-mutation.js +42 -0
- package/dist/settings-mutation.js.map +1 -0
- package/dist/tools/event.d.ts.map +1 -1
- package/dist/tools/event.js +27 -46
- package/dist/tools/event.js.map +1 -1
- package/dist/tools/host-fn-tool.d.ts +21 -0
- package/dist/tools/host-fn-tool.d.ts.map +1 -0
- package/dist/tools/host-fn-tool.js +32 -0
- package/dist/tools/host-fn-tool.js.map +1 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +1 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/react.d.ts.map +1 -1
- package/dist/tools/react.js +6 -17
- package/dist/tools/react.js.map +1 -1
- package/dist/tools/read.d.ts.map +1 -1
- package/dist/tools/read.js +7 -26
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/sandbox.d.ts.map +1 -1
- package/dist/tools/sandbox.js +5 -2
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/subagent-slots.d.ts +28 -0
- package/dist/tools/subagent-slots.d.ts.map +1 -0
- package/dist/tools/subagent-slots.js +57 -0
- package/dist/tools/subagent-slots.js.map +1 -0
- package/dist/tools/subagent.d.ts +7 -2
- package/dist/tools/subagent.d.ts.map +1 -1
- package/dist/tools/subagent.js +160 -111
- package/dist/tools/subagent.js.map +1 -1
- package/dist/tools/types.d.ts +10 -9
- package/dist/tools/types.d.ts.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/types.d.ts +5 -24
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/date.d.ts +1 -1
- package/dist/utils/date.js +1 -1
- package/dist/utils/date.js.map +1 -1
- package/dist/vault/disabled.d.ts.map +1 -1
- package/dist/vault/disabled.js +0 -1
- package/dist/vault/disabled.js.map +1 -1
- package/dist/vault/index.d.ts +0 -2
- package/dist/vault/index.d.ts.map +1 -1
- package/dist/vault/index.js +0 -10
- package/dist/vault/index.js.map +1 -1
- package/dist/vault/injection.d.ts +20 -0
- package/dist/vault/injection.d.ts.map +1 -0
- package/dist/vault/injection.js +27 -0
- package/dist/vault/injection.js.map +1 -0
- package/dist/vault/types.d.ts +0 -2
- package/dist/vault/types.d.ts.map +1 -1
- package/dist/vault/types.js.map +1 -1
- package/dist/web/admin/portal.d.ts +3 -3
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +41 -39
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/admin/types.d.ts +3 -0
- package/dist/web/admin/types.d.ts.map +1 -1
- package/dist/web/admin/types.js.map +1 -1
- package/dist/web/agent-events/portal.d.ts.map +1 -1
- package/dist/web/agent-events/portal.js +2 -1
- package/dist/web/agent-events/portal.js.map +1 -1
- package/package.json +1 -1
- package/dist/sessions/agent-memory-file-manager.d.ts +0 -19
- package/dist/sessions/agent-memory-file-manager.d.ts.map +0 -1
- package/dist/sessions/agent-memory-file-manager.js.map +0 -1
- package/dist/vault/routing.d.ts +0 -4
- package/dist/vault/routing.d.ts.map +0 -1
- package/dist/vault/routing.js +0 -6
- package/dist/vault/routing.js.map +0 -1
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Single home for the scheduled-event file format (`events/*.json`, the
|
|
3
|
+
* workspace scheduling bus). Every reader and writer — the EventsWatcher
|
|
4
|
+
* scheduler, the agent `event` tool, and the extension schedule API — must go
|
|
5
|
+
* through this module: one schema, one payload union, one parser, one
|
|
6
|
+
* builder. Per-type field rules (`at` for one-shot, `schedule` + `timezone`
|
|
7
|
+
* for periodic) live here and nowhere else.
|
|
8
|
+
*/
|
|
9
|
+
export type EventConversationKind = "direct" | "shared";
|
|
10
|
+
export type EventType = "immediate" | "one-shot" | "periodic";
|
|
11
|
+
/** Typebox union for the `type` field, shared by the file schema and the event tool's parameters. */
|
|
12
|
+
export declare const EventTypeSchema: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"immediate">, import("@sinclair/typebox").TLiteral<"one-shot">, import("@sinclair/typebox").TLiteral<"periodic">]>;
|
|
13
|
+
interface EventPayloadBase {
|
|
14
|
+
/** Target platform; may be omitted when only one platform is running. */
|
|
15
|
+
platform?: string;
|
|
16
|
+
conversationId: string;
|
|
17
|
+
conversationKind?: EventConversationKind;
|
|
18
|
+
userId?: string;
|
|
19
|
+
/** Self-contained task text; event runs do not inherit conversation history. */
|
|
20
|
+
text: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ImmediateEventPayload extends EventPayloadBase {
|
|
23
|
+
type: "immediate";
|
|
24
|
+
}
|
|
25
|
+
export interface OneShotEventPayload extends EventPayloadBase {
|
|
26
|
+
type: "one-shot";
|
|
27
|
+
/** ISO 8601 timestamp with offset. */
|
|
28
|
+
at: string;
|
|
29
|
+
}
|
|
30
|
+
export interface PeriodicEventPayload extends EventPayloadBase {
|
|
31
|
+
type: "periodic";
|
|
32
|
+
/** Cron expression (croner syntax). */
|
|
33
|
+
schedule: string;
|
|
34
|
+
/** IANA timezone, e.g. "Asia/Taipei". */
|
|
35
|
+
timezone: string;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Wire shape of one event file. Platform defaulting and conversation-kind
|
|
39
|
+
* inference happen at read time (EventsWatcher), so both stay optional here.
|
|
40
|
+
*/
|
|
41
|
+
export type EventFilePayload = ImmediateEventPayload | OneShotEventPayload | PeriodicEventPayload;
|
|
42
|
+
/**
|
|
43
|
+
* Parse and validate one event file's content into the canonical payload.
|
|
44
|
+
* `filename` appears in error messages. Throws on malformed JSON, wrong
|
|
45
|
+
* field types, and missing required fields (common and per-type).
|
|
46
|
+
*/
|
|
47
|
+
export declare function parseEventPayload(content: string, filename: string): EventFilePayload;
|
|
48
|
+
export interface EventPayloadInput {
|
|
49
|
+
type: EventType;
|
|
50
|
+
platform?: string;
|
|
51
|
+
conversationId: string;
|
|
52
|
+
conversationKind?: EventConversationKind;
|
|
53
|
+
userId?: string;
|
|
54
|
+
text: string;
|
|
55
|
+
at?: string;
|
|
56
|
+
schedule?: string;
|
|
57
|
+
timezone?: string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Validate and assemble a new event payload for writing. Owns the per-type
|
|
61
|
+
* field rules; write-side *policy* beyond the format (e.g. the event tool's
|
|
62
|
+
* requirement that `at` lies in the future) stays with the writer.
|
|
63
|
+
*/
|
|
64
|
+
export declare function buildEventPayload(input: EventPayloadInput): EventFilePayload;
|
|
65
|
+
export {};
|
|
66
|
+
//# sourceMappingURL=event-format.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-format.d.ts","sourceRoot":"","sources":["../../src/harness/event-format.ts"],"names":[],"mappings":"AAGA;;;;;;;GAOG;AAEH,MAAM,MAAM,qBAAqB,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAExD,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG,UAAU,GAAG,UAAU,CAAC;AAE9D,qGAAqG;AACrG,eAAO,MAAM,eAAe,6LAI1B,CAAC;AAEH,UAAU,gBAAgB;IACxB,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,qBAAqB,CAAC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gFAAgF;IAChF,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;IAC7D,IAAI,EAAE,WAAW,CAAC;CACnB;AAED,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;IAC3D,IAAI,EAAE,UAAU,CAAC;IACjB,sCAAsC;IACtC,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,oBAAqB,SAAQ,gBAAgB;IAC5D,IAAI,EAAE,UAAU,CAAC;IACjB,uCAAuC;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,yCAAyC;IACzC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,qBAAqB,GAAG,mBAAmB,GAAG,oBAAoB,CAAC;AAoClG;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,gBAAgB,CAwCrF;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,qBAAqB,CAAC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,iBAAiB,GAAG,gBAAgB,CAgC5E"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import { parseJsonSchemaValue } from "../utils/file-guards.js";
|
|
3
|
+
/** Typebox union for the `type` field, shared by the file schema and the event tool's parameters. */
|
|
4
|
+
export const EventTypeSchema = Type.Union([
|
|
5
|
+
Type.Literal("immediate"),
|
|
6
|
+
Type.Literal("one-shot"),
|
|
7
|
+
Type.Literal("periodic"),
|
|
8
|
+
]);
|
|
9
|
+
/**
|
|
10
|
+
* Lenient file-reading schema: every field optional so shape problems surface
|
|
11
|
+
* as the specific missing-field messages below rather than typebox noise.
|
|
12
|
+
* `channelId` is the legacy alias for `conversationId`.
|
|
13
|
+
*/
|
|
14
|
+
const EventFileSchema = Type.Object({
|
|
15
|
+
type: Type.Optional(EventTypeSchema),
|
|
16
|
+
platform: Type.Optional(Type.String()),
|
|
17
|
+
conversationId: Type.Optional(Type.String()),
|
|
18
|
+
channelId: Type.Optional(Type.String()),
|
|
19
|
+
conversationKind: Type.Optional(Type.Union([Type.Literal("direct"), Type.Literal("shared")])),
|
|
20
|
+
userId: Type.Optional(Type.String()),
|
|
21
|
+
text: Type.Optional(Type.String()),
|
|
22
|
+
at: Type.Optional(Type.String()),
|
|
23
|
+
schedule: Type.Optional(Type.String()),
|
|
24
|
+
timezone: Type.Optional(Type.String()),
|
|
25
|
+
});
|
|
26
|
+
/**
|
|
27
|
+
* Resolve an event file's conversation id, honoring the legacy `channelId`
|
|
28
|
+
* alias. Alias knowledge is private to the format module: consumers always
|
|
29
|
+
* see `conversationId` on parsed payloads.
|
|
30
|
+
*/
|
|
31
|
+
function resolveEventConversationId(data) {
|
|
32
|
+
if (typeof data.conversationId === "string")
|
|
33
|
+
return data.conversationId;
|
|
34
|
+
if (typeof data.channelId === "string")
|
|
35
|
+
return data.channelId;
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Parse and validate one event file's content into the canonical payload.
|
|
40
|
+
* `filename` appears in error messages. Throws on malformed JSON, wrong
|
|
41
|
+
* field types, and missing required fields (common and per-type).
|
|
42
|
+
*/
|
|
43
|
+
export function parseEventPayload(content, filename) {
|
|
44
|
+
const data = parseJsonSchemaValue(content, EventFileSchema, (detail) => detail === "unexpected JSON shape"
|
|
45
|
+
? `Expected top-level JSON object in ${filename}`
|
|
46
|
+
: `Malformed event file ${filename}: ${detail}`);
|
|
47
|
+
const conversationId = resolveEventConversationId(data);
|
|
48
|
+
const { type, text } = data;
|
|
49
|
+
if (!type || !conversationId || !text) {
|
|
50
|
+
throw new Error(`Missing required fields (type, conversationId, text) in ${filename}`);
|
|
51
|
+
}
|
|
52
|
+
const base = {
|
|
53
|
+
...(data.platform !== undefined ? { platform: data.platform } : {}),
|
|
54
|
+
conversationId,
|
|
55
|
+
...(data.conversationKind !== undefined ? { conversationKind: data.conversationKind } : {}),
|
|
56
|
+
...(data.userId !== undefined ? { userId: data.userId } : {}),
|
|
57
|
+
text,
|
|
58
|
+
};
|
|
59
|
+
switch (type) {
|
|
60
|
+
case "immediate":
|
|
61
|
+
return { type, ...base };
|
|
62
|
+
case "one-shot":
|
|
63
|
+
if (typeof data.at !== "string" || data.at.length === 0) {
|
|
64
|
+
throw new Error(`Missing 'at' field for one-shot event in ${filename}`);
|
|
65
|
+
}
|
|
66
|
+
return { type, ...base, at: data.at };
|
|
67
|
+
case "periodic":
|
|
68
|
+
if (typeof data.schedule !== "string" || data.schedule.length === 0) {
|
|
69
|
+
throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);
|
|
70
|
+
}
|
|
71
|
+
if (typeof data.timezone !== "string" || data.timezone.length === 0) {
|
|
72
|
+
throw new Error(`Missing 'timezone' field for periodic event in ${filename}`);
|
|
73
|
+
}
|
|
74
|
+
return { type, ...base, schedule: data.schedule, timezone: data.timezone };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Validate and assemble a new event payload for writing. Owns the per-type
|
|
79
|
+
* field rules; write-side *policy* beyond the format (e.g. the event tool's
|
|
80
|
+
* requirement that `at` lies in the future) stays with the writer.
|
|
81
|
+
*/
|
|
82
|
+
export function buildEventPayload(input) {
|
|
83
|
+
const base = {
|
|
84
|
+
...(input.platform !== undefined ? { platform: input.platform } : {}),
|
|
85
|
+
conversationId: input.conversationId,
|
|
86
|
+
...(input.conversationKind !== undefined ? { conversationKind: input.conversationKind } : {}),
|
|
87
|
+
...(input.userId !== undefined ? { userId: input.userId } : {}),
|
|
88
|
+
text: input.text,
|
|
89
|
+
};
|
|
90
|
+
switch (input.type) {
|
|
91
|
+
case "immediate":
|
|
92
|
+
return { type: "immediate", ...base };
|
|
93
|
+
case "one-shot": {
|
|
94
|
+
if (!input.at) {
|
|
95
|
+
throw new Error("`at` is required for one-shot events");
|
|
96
|
+
}
|
|
97
|
+
if (Number.isNaN(new Date(input.at).getTime())) {
|
|
98
|
+
throw new Error("`at` must be a valid ISO 8601 timestamp with UTC offset");
|
|
99
|
+
}
|
|
100
|
+
return { type: "one-shot", ...base, at: input.at };
|
|
101
|
+
}
|
|
102
|
+
case "periodic":
|
|
103
|
+
if (!input.schedule) {
|
|
104
|
+
throw new Error("`schedule` is required for periodic events");
|
|
105
|
+
}
|
|
106
|
+
if (!input.timezone) {
|
|
107
|
+
throw new Error("`timezone` is required for periodic events");
|
|
108
|
+
}
|
|
109
|
+
return { type: "periodic", ...base, schedule: input.schedule, timezone: input.timezone };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
//# sourceMappingURL=event-format.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"event-format.js","sourceRoot":"","sources":["../../src/harness/event-format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAe,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAe/D,qGAAqG;AACrG,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,CAAC,KAAK,CAAC;IACxC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC;IACzB,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC;IACxB,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC;CACzB,CAAC,CAAC;AAoCH;;;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IAAI;KACjB,CAAC;IAEF,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,WAAW;YACd,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,EAAE,CAAC;QAExC,KAAK,UAAU,EAAE,CAAC;YAChB,IAAI,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC;gBACd,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;YAC1D,CAAC;YACD,IAAI,MAAM,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;gBAC/C,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;YAC7E,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QACrD,CAAC;QAED,KAAK,UAAU;YACb,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;gBACpB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAChE,CAAC;YACD,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;gBACpB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;YAChE,CAAC;YACD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;IAC7F,CAAC;AACH,CAAC","sourcesContent":["import { Type, type Static } from \"@sinclair/typebox\";\nimport { parseJsonSchemaValue } from \"../utils/file-guards.js\";\n\n/**\n * Single home for the scheduled-event file format (`events/*.json`, the\n * workspace scheduling bus). Every reader and writer — the EventsWatcher\n * scheduler, the agent `event` tool, and the extension schedule API — must go\n * through this module: one schema, one payload union, one parser, one\n * builder. Per-type field rules (`at` for one-shot, `schedule` + `timezone`\n * for periodic) live here and nowhere else.\n */\n\nexport type EventConversationKind = \"direct\" | \"shared\";\n\nexport type EventType = \"immediate\" | \"one-shot\" | \"periodic\";\n\n/** Typebox union for the `type` field, shared by the file schema and the event tool's parameters. */\nexport const EventTypeSchema = Type.Union([\n Type.Literal(\"immediate\"),\n Type.Literal(\"one-shot\"),\n Type.Literal(\"periodic\"),\n]);\n\ninterface EventPayloadBase {\n /** Target platform; may be omitted when only one platform is running. */\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n /** Self-contained task text; event runs do not inherit conversation history. */\n text: string;\n}\n\nexport interface ImmediateEventPayload extends EventPayloadBase {\n type: \"immediate\";\n}\n\nexport interface OneShotEventPayload extends EventPayloadBase {\n type: \"one-shot\";\n /** ISO 8601 timestamp with offset. */\n at: string;\n}\n\nexport interface PeriodicEventPayload extends EventPayloadBase {\n type: \"periodic\";\n /** Cron expression (croner syntax). */\n schedule: string;\n /** IANA timezone, e.g. \"Asia/Taipei\". */\n timezone: string;\n}\n\n/**\n * Wire shape of one event file. Platform defaulting and conversation-kind\n * inference happen at read time (EventsWatcher), so both stay optional here.\n */\nexport type EventFilePayload = ImmediateEventPayload | OneShotEventPayload | PeriodicEventPayload;\n\n/**\n * Lenient file-reading schema: every field optional so shape problems surface\n * as the specific missing-field messages below rather than typebox noise.\n * `channelId` is the legacy alias for `conversationId`.\n */\nconst EventFileSchema = Type.Object({\n type: Type.Optional(EventTypeSchema),\n platform: Type.Optional(Type.String()),\n conversationId: Type.Optional(Type.String()),\n channelId: Type.Optional(Type.String()),\n conversationKind: Type.Optional(Type.Union([Type.Literal(\"direct\"), Type.Literal(\"shared\")])),\n userId: Type.Optional(Type.String()),\n text: Type.Optional(Type.String()),\n at: Type.Optional(Type.String()),\n schedule: Type.Optional(Type.String()),\n timezone: Type.Optional(Type.String()),\n});\n\ntype EventFileData = Static<typeof EventFileSchema>;\n\n/**\n * Resolve an event file's conversation id, honoring the legacy `channelId`\n * alias. Alias knowledge is private to the format module: consumers always\n * see `conversationId` on parsed payloads.\n */\nfunction resolveEventConversationId(data: {\n conversationId?: unknown;\n channelId?: unknown;\n}): string | undefined {\n if (typeof data.conversationId === \"string\") return data.conversationId;\n if (typeof data.channelId === \"string\") return data.channelId;\n return undefined;\n}\n\n/**\n * Parse and validate one event file's content into the canonical payload.\n * `filename` appears in error messages. Throws on malformed JSON, wrong\n * field types, and missing required fields (common and per-type).\n */\nexport function parseEventPayload(content: string, filename: string): EventFilePayload {\n const data: EventFileData = parseJsonSchemaValue(content, EventFileSchema, (detail) =>\n detail === \"unexpected JSON shape\"\n ? `Expected top-level JSON object in ${filename}`\n : `Malformed event file ${filename}: ${detail}`,\n );\n const conversationId = resolveEventConversationId(data);\n const { type, text } = data;\n\n if (!type || !conversationId || !text) {\n throw new Error(`Missing required fields (type, conversationId, text) in ${filename}`);\n }\n\n const base = {\n ...(data.platform !== undefined ? { platform: data.platform } : {}),\n conversationId,\n ...(data.conversationKind !== undefined ? { conversationKind: data.conversationKind } : {}),\n ...(data.userId !== undefined ? { userId: data.userId } : {}),\n text,\n };\n\n switch (type) {\n case \"immediate\":\n return { type, ...base };\n\n case \"one-shot\":\n if (typeof data.at !== \"string\" || data.at.length === 0) {\n throw new Error(`Missing 'at' field for one-shot event in ${filename}`);\n }\n return { type, ...base, at: data.at };\n\n case \"periodic\":\n if (typeof data.schedule !== \"string\" || data.schedule.length === 0) {\n throw new Error(`Missing 'schedule' field for periodic event in ${filename}`);\n }\n if (typeof data.timezone !== \"string\" || data.timezone.length === 0) {\n throw new Error(`Missing 'timezone' field for periodic event in ${filename}`);\n }\n return { type, ...base, schedule: data.schedule, timezone: data.timezone };\n }\n}\n\nexport interface EventPayloadInput {\n type: EventType;\n platform?: string;\n conversationId: string;\n conversationKind?: EventConversationKind;\n userId?: string;\n text: string;\n at?: string;\n schedule?: string;\n timezone?: string;\n}\n\n/**\n * Validate and assemble a new event payload for writing. Owns the per-type\n * field rules; write-side *policy* beyond the format (e.g. the event tool's\n * requirement that `at` lies in the future) stays with the writer.\n */\nexport function buildEventPayload(input: EventPayloadInput): EventFilePayload {\n const base = {\n ...(input.platform !== undefined ? { platform: input.platform } : {}),\n conversationId: input.conversationId,\n ...(input.conversationKind !== undefined ? { conversationKind: input.conversationKind } : {}),\n ...(input.userId !== undefined ? { userId: input.userId } : {}),\n text: input.text,\n };\n\n switch (input.type) {\n case \"immediate\":\n return { type: \"immediate\", ...base };\n\n case \"one-shot\": {\n if (!input.at) {\n throw new Error(\"`at` is required for one-shot events\");\n }\n if (Number.isNaN(new Date(input.at).getTime())) {\n throw new Error(\"`at` must be a valid ISO 8601 timestamp with UTC offset\");\n }\n return { type: \"one-shot\", ...base, at: input.at };\n }\n\n case \"periodic\":\n if (!input.schedule) {\n throw new Error(\"`schedule` is required for periodic events\");\n }\n if (!input.timezone) {\n throw new Error(\"`timezone` is required for periodic events\");\n }\n return { type: \"periodic\", ...base, schedule: input.schedule, timezone: input.timezone };\n }\n}\n"]}
|
|
@@ -56,13 +56,16 @@ export interface LoadExtensionsResult {
|
|
|
56
56
|
dispose(): Promise<void>;
|
|
57
57
|
}
|
|
58
58
|
/**
|
|
59
|
-
* Filesystem-safe identifier for an extension, derived from its
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
59
|
+
* Filesystem-safe identifier for an extension, derived from its root (the
|
|
60
|
+
* install directory, or the file path for a bare-file extension). The slug
|
|
61
|
+
* keys the extension's data dir, secrets vault, and schedule ownership —
|
|
62
|
+
* installing the same extension globally and per-conversation shares one
|
|
63
|
+
* slug and therefore one shared data dir. This is the only slug derivation:
|
|
64
|
+
* a second one keyed off a different input (e.g. the entrypoint, which for
|
|
65
|
+
* package.json-form extensions can live under dist/) would silently split an
|
|
66
|
+
* extension's identity.
|
|
64
67
|
*/
|
|
65
|
-
export declare function extensionSlug(
|
|
68
|
+
export declare function extensionSlug(rootDir: string): string;
|
|
66
69
|
/** Load and activate all extensions found in the given directories. */
|
|
67
70
|
export declare function loadExtensions(options: LoadExtensionsOptions): Promise<LoadExtensionsResult>;
|
|
68
71
|
export interface ExtensionValidation {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/harness/extensions/loader.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAa,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../src/harness/extensions/loader.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAa,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EAAqB,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAGV,qBAAqB,EACrB,kBAAkB,EAKlB,eAAe,EAIhB,MAAM,YAAY,CAAC;AAiBpB;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,cAAc,EAAE,MAAM,EACtB,QAAQ,GAAE,MAAkC,GAC3C,MAAM,EAAE,CAKV;AAED,8EAA8E;AAC9E,MAAM,WAAW,sBAAsB;IACrC,6DAA6D;IAC7D,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,iDAAiD;IACjD,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,E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U,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAsDxF"}
|
|
@@ -24,9 +24,10 @@
|
|
|
24
24
|
*/
|
|
25
25
|
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "fs";
|
|
26
26
|
import { homedir } from "os";
|
|
27
|
-
import { basename,
|
|
27
|
+
import { basename, join } from "path";
|
|
28
28
|
import { createJiti } from "jiti";
|
|
29
29
|
import * as log from "../../log.js";
|
|
30
|
+
import { buildEventPayload } from "../event-format.js";
|
|
30
31
|
import { loadSkillsFromDir } from "../skills.js";
|
|
31
32
|
import { ExtensionRegistry } from "./registry.js";
|
|
32
33
|
const EXTENSION_FILE_PATTERN = /\.(mjs|js|ts|mts)$/;
|
|
@@ -64,7 +65,7 @@ export function listInstalledExtensions(dirs) {
|
|
|
64
65
|
const infos = [];
|
|
65
66
|
for (const dir of dirs) {
|
|
66
67
|
for (const { entrypoint, rootDir } of discoverExtensionEntrypoints(dir)) {
|
|
67
|
-
const slug =
|
|
68
|
+
const slug = extensionSlug(rootDir);
|
|
68
69
|
const manifest = readManifest(rootDir);
|
|
69
70
|
infos.push({
|
|
70
71
|
name: manifest.name ?? slug,
|
|
@@ -169,43 +170,35 @@ function readPackageJson(dir) {
|
|
|
169
170
|
function readMikanManifestEntrypoints(dir) {
|
|
170
171
|
return readPackageJson(dir)?.mikan?.extensions ?? [];
|
|
171
172
|
}
|
|
172
|
-
|
|
173
|
-
|
|
173
|
+
/** The one filesystem-safe segment sanitizer for extension identity and schedule names. */
|
|
174
|
+
function sanitizeSegment(value) {
|
|
175
|
+
return value
|
|
174
176
|
.toLowerCase()
|
|
175
177
|
.replace(/[^a-z0-9_-]+/g, "-")
|
|
176
178
|
.replace(/^-+|-+$/g, "")
|
|
177
179
|
.slice(0, 64);
|
|
178
|
-
|
|
180
|
+
}
|
|
181
|
+
function sanitizeSlug(base) {
|
|
182
|
+
return sanitizeSegment(base) || "extension";
|
|
179
183
|
}
|
|
180
184
|
/**
|
|
181
|
-
* Filesystem-safe identifier for an extension, derived from its
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
185
|
+
* Filesystem-safe identifier for an extension, derived from its root (the
|
|
186
|
+
* install directory, or the file path for a bare-file extension). The slug
|
|
187
|
+
* keys the extension's data dir, secrets vault, and schedule ownership —
|
|
188
|
+
* installing the same extension globally and per-conversation shares one
|
|
189
|
+
* slug and therefore one shared data dir. This is the only slug derivation:
|
|
190
|
+
* a second one keyed off a different input (e.g. the entrypoint, which for
|
|
191
|
+
* package.json-form extensions can live under dist/) would silently split an
|
|
192
|
+
* extension's identity.
|
|
186
193
|
*/
|
|
187
|
-
export function extensionSlug(
|
|
188
|
-
// Bare-file form (rootDir === entrypoint, a *.mjs/.ts file) → file basename.
|
|
189
|
-
// Directory form → directory name. Detect the directory form structurally:
|
|
190
|
-
// an entrypoint whose parent holds a package.json or is an index file.
|
|
191
|
-
if (INDEX_FILE_PATTERN.test(basename(entrypoint))) {
|
|
192
|
-
return sanitizeSlug(basename(dirname(entrypoint)));
|
|
193
|
-
}
|
|
194
|
-
return sanitizeSlug(basename(entrypoint).replace(EXTENSION_FILE_PATTERN, ""));
|
|
195
|
-
}
|
|
196
|
-
/** Slug from a discovered extension's root dir (directory or bare file path). */
|
|
197
|
-
function slugForRoot(rootDir) {
|
|
194
|
+
export function extensionSlug(rootDir) {
|
|
198
195
|
return EXTENSION_FILE_PATTERN.test(basename(rootDir))
|
|
199
196
|
? sanitizeSlug(basename(rootDir).replace(EXTENSION_FILE_PATTERN, ""))
|
|
200
197
|
: sanitizeSlug(basename(rootDir));
|
|
201
198
|
}
|
|
202
199
|
/** Sanitize an extension-chosen schedule name into a filename segment. */
|
|
203
200
|
function scheduleNameSegment(name) {
|
|
204
|
-
const segment = name
|
|
205
|
-
.toLowerCase()
|
|
206
|
-
.replace(/[^a-z0-9_-]+/g, "-")
|
|
207
|
-
.replace(/^-+|-+$/g, "")
|
|
208
|
-
.slice(0, 64);
|
|
201
|
+
const segment = sanitizeSegment(name);
|
|
209
202
|
if (!segment)
|
|
210
203
|
throw new Error(`Invalid schedule name: ${JSON.stringify(name)}`);
|
|
211
204
|
return segment;
|
|
@@ -274,42 +267,34 @@ function schedulePrefix(slug, conversationId) {
|
|
|
274
267
|
return `ext.${slug}.${scheduleNameSegment(conversationId)}.`;
|
|
275
268
|
}
|
|
276
269
|
function payloadFromSpec(spec, conversationId) {
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
return {
|
|
282
|
-
type: "periodic",
|
|
283
|
-
conversationId,
|
|
284
|
-
text: spec.text,
|
|
285
|
-
schedule: spec.schedule,
|
|
286
|
-
timezone: spec.timezone,
|
|
287
|
-
...(spec.platform ? { platform: spec.platform } : {}),
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
if (!spec.at)
|
|
291
|
-
throw new Error("one-shot schedule requires at");
|
|
292
|
-
return {
|
|
293
|
-
type: "one-shot",
|
|
270
|
+
// Per-type validation (schedule/timezone for periodic, at for one-shot)
|
|
271
|
+
// is owned by the event-format builder.
|
|
272
|
+
return buildEventPayload({
|
|
273
|
+
type: spec.type,
|
|
294
274
|
conversationId,
|
|
295
275
|
text: spec.text,
|
|
296
|
-
at: spec.at,
|
|
297
276
|
...(spec.platform ? { platform: spec.platform } : {}),
|
|
298
|
-
|
|
277
|
+
...(spec.type === "periodic"
|
|
278
|
+
? { schedule: spec.schedule, timezone: spec.timezone }
|
|
279
|
+
: { at: spec.at }),
|
|
280
|
+
});
|
|
299
281
|
}
|
|
300
282
|
function specFromPayload(payload) {
|
|
301
283
|
if (payload.type === "periodic") {
|
|
302
284
|
return {
|
|
303
285
|
type: "periodic",
|
|
304
|
-
schedule: payload.schedule
|
|
305
|
-
timezone: payload.timezone
|
|
286
|
+
schedule: payload.schedule,
|
|
287
|
+
timezone: payload.timezone,
|
|
306
288
|
text: payload.text,
|
|
307
289
|
...(payload.platform ? { platform: payload.platform } : {}),
|
|
308
290
|
};
|
|
309
291
|
}
|
|
292
|
+
// `immediate` payloads never appear under the schedules namespace (they
|
|
293
|
+
// live under "extrun."); tolerate them as an empty one-shot rather than
|
|
294
|
+
// widening the spec union.
|
|
310
295
|
return {
|
|
311
296
|
type: "one-shot",
|
|
312
|
-
at: payload.at
|
|
297
|
+
at: payload.type === "one-shot" ? payload.at : "",
|
|
313
298
|
text: payload.text,
|
|
314
299
|
...(payload.platform ? { platform: payload.platform } : {}),
|
|
315
300
|
};
|
|
@@ -458,7 +443,7 @@ export async function loadExtensions(options) {
|
|
|
458
443
|
});
|
|
459
444
|
continue;
|
|
460
445
|
}
|
|
461
|
-
const slug =
|
|
446
|
+
const slug = extensionSlug(rootDir);
|
|
462
447
|
const manifest = readManifest(rootDir);
|
|
463
448
|
const name = manifest.name ?? extension.name ?? slug;
|
|
464
449
|
const api = buildExtensionApi({
|
|
@@ -524,7 +509,7 @@ export async function validateExtension(sourcePath) {
|
|
|
524
509
|
else {
|
|
525
510
|
errors.push(`Not an extension file (expected .mjs/.js/.ts/.mts): ${rootDir}`);
|
|
526
511
|
}
|
|
527
|
-
const slug =
|
|
512
|
+
const slug = extensionSlug(rootDir);
|
|
528
513
|
const manifest = readManifest(rootDir);
|
|
529
514
|
const skillNames = loadExtensionSkills(rootDir, slug).map((skill) => skill.name);
|
|
530
515
|
if (entrypoint) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.js","sourceRoot":"","sources":["../../../src/harness/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAChF,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC/C,OAAO,EAAE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sourcesContent":["/**\n * Extension discovery and activation.\n *\n * Extension modules execute inside the mikan host process with its full\n * privileges (platform tokens, vault, host filesystem). They must therefore\n * only ever load from host-controlled directories: installing an extension\n * is an administrator action. In particular, extension directories must not\n * live under paths mounted into sandbox containers (workspace and\n * conversation dirs in image mode), or code written from inside the sandbox\n * would be imported into the host process — a sandbox escape.\n * {@link defaultExtensionDirs} returns the canonical host-only locations\n * under mikan's state dir.\n *\n * Directories are scanned in order; all discovered extensions activate.\n * Accepted layouts (entrypoint may be .mjs/.js/.ts/.mts — loaded via jiti):\n *\n * - `extensions/<name>.<ext>` (bare file)\n * - `extensions/<name>/index.<ext>` (directory + index)\n * - `extensions/<name>/package.json` (mikan.extensions entrypoint;\n * may carry npm dependencies in node_modules)\n *\n * Modules are imported with a fresh jiti instance (no cache) so edited\n * extensions are picked up when a new harness instance is created.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { basename, dirname, join } from \"path\";\nimport { createJiti } from \"jiti\";\nimport type { AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport * as log from \"../../log.js\";\nimport { loadSkillsFromDir, type MikanSkill } from \"../skills.js\";\nimport { ExtensionRegistry } from \"./registry.js\";\nimport type {\n ExtensionCommand,\n ExtensionDisposer,\n ExtensionHostServices,\n ExtensionLoadError,\n ExtensionManifest,\n ExtensionSchedulePayload,\n ExtensionScheduleInfo,\n ExtensionScheduleSpec,\n LoadedExtension,\n MikanExtensionActivate,\n MikanExtensionApi,\n MikanExtensionModule,\n} from \"./types.js\";\n\nconst EXTENSION_FILE_PATTERN = /\\.(mjs|js|ts|mts)$/;\nconst INDEX_FILE_PATTERN = /^index\\.(mjs|js|ts|mts)$/;\nconst INDEX_CANDIDATES = [\"index.mjs\", \"index.js\", \"index.ts\", \"index.mts\"];\n\n/**\n * Import an extension entrypoint through jiti so it can be TypeScript and can\n * use node_modules dependencies, transparently compiling on the fly. A fresh\n * jiti instance with caching disabled is used per load so edited extensions\n * are picked up when a new harness instance is created for a conversation.\n */\nasync function importExtensionModule(entrypoint: string): Promise<unknown> {\n const jiti = createJiti(import.meta.url, { moduleCache: false, fsCache: false });\n return jiti.import(entrypoint);\n}\n\n/**\n * Canonical host-only extension code directories for a conversation, in load\n * order: `<stateDir>/global/extensions` (all conversations) then\n * `<stateDir>/conversations/<conversationId>/extensions` (that conversation\n * only). `global` and `conversations` are the two sibling scopes; see\n * `LAYOUT.md`. Conversation ids are used verbatim (see LAYOUT.md § Casing).\n */\nexport function defaultExtensionDirs(\n conversationId: string,\n stateDir: string = join(homedir(), \".mikan\"),\n): string[] {\n return [\n join(stateDir, \"global\", \"extensions\"),\n join(stateDir, \"conversations\", conversationId, \"extensions\"),\n ];\n}\n\n/** Discovery-only view of an installed extension (module is not imported). */\nexport interface InstalledExtensionInfo {\n /** Display name: manifest name, falling back to the slug. */\n name: string;\n slug: string;\n path: string;\n /** Scan directory the extension was found in. */\n dir: string;\n version?: string;\n description?: string;\n /** Names of skills shipped in the extension's skills/ directory. */\n skillNames: string[];\n}\n\n/**\n * List installed extensions without importing or activating them — safe for\n * inventory surfaces (commands, portal). Activation side effects (schedule\n * upserts, tool registration) only happen in {@link loadExtensions}.\n */\nexport function listInstalledExtensions(dirs: string[]): InstalledExtensionInfo[] {\n const infos: InstalledExtensionInfo[] = [];\n for (const dir of dirs) {\n for (const { entrypoint, rootDir } of discoverExtensionEntrypoints(dir)) {\n const slug = slugForRoot(rootDir);\n const manifest = readManifest(rootDir);\n infos.push({\n name: manifest.name ?? slug,\n slug,\n path: entrypoint,\n dir,\n version: manifest.version,\n description: manifest.description,\n skillNames: loadExtensionSkills(rootDir, slug).map((skill) => skill.name),\n });\n }\n }\n return infos;\n}\n\nexport interface LoadExtensionsOptions {\n /** Directories to scan for extensions. Missing directories are skipped. */\n dirs: string[];\n context: {\n conversationId: string;\n workspaceDir: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n };\n /** Embedder-provided services backing the v2 api surface. */\n services?: ExtensionHostServices;\n}\n\nexport interface LoadExtensionsResult {\n registry: ExtensionRegistry;\n extensions: LoadedExtension[];\n errors: ExtensionLoadError[];\n /** Skills contributed by extensions (inline: bodies ride in the prompt). */\n skills: MikanSkill[];\n /**\n * Run extension disposers (from `api.onDispose` and `activate` return\n * values). Call when the harness instance owning these extensions is\n * discarded. Idempotent; disposer errors are logged, never thrown.\n */\n dispose(): Promise<void>;\n}\n\n/**\n * A discovered extension: its entrypoint (module to import) and root dir\n * (used for slug, manifest.json, and skills/ — which sit at the extension\n * root, not necessarily next to a nested entrypoint).\n */\ninterface DiscoveredExtension {\n entrypoint: string;\n rootDir: string;\n}\n\nfunction discoverExtensionEntrypoints(dir: string): DiscoveredExtension[] {\n if (!existsSync(dir)) return [];\n const found: DiscoveredExtension[] = [];\n for (const name of readdirSync(dir).toSorted()) {\n if (name.startsWith(\".\")) continue;\n if (INDEX_FILE_PATTERN.test(name)) {\n // An index file at the scan root means the extension's contents were\n // copied into the scope directory itself; the slug would degenerate to\n // the scope name (e.g. the conversation id), mis-keying its data dir,\n // secrets, and schedules. Require a named form instead.\n log.logWarning(\n `Ignoring extension index file at scope root: ${join(dir, name)}`,\n \"install into a named subdirectory (e.g. extensions/<scope>/my-ext/index.mjs)\",\n );\n continue;\n }\n const fullPath = join(dir, name);\n let stats;\n try {\n stats = statSync(fullPath);\n } catch {\n continue;\n }\n if (stats.isFile() && EXTENSION_FILE_PATTERN.test(name)) {\n // Bare-file form: the file is both entrypoint and (its own) root.\n found.push({ entrypoint: fullPath, rootDir: fullPath });\n continue;\n }\n if (stats.isDirectory()) {\n const entrypoint = resolveDirectoryEntrypoint(fullPath);\n if (entrypoint) found.push({ entrypoint, rootDir: fullPath });\n }\n }\n return found;\n}\n\n/**\n * Resolve a directory-form extension's entrypoint. A `package.json` with a\n * `mikan.extensions` array (first entry, relative to the dir) wins — this is\n * how an extension declares a TypeScript entry and pulls in npm dependencies.\n * Otherwise fall back to an `index.{mjs,js,ts,mts}` file. Returns undefined\n * when neither is present.\n */\nfunction resolveDirectoryEntrypoint(dir: string): string | undefined {\n const declared = readMikanManifestEntrypoints(dir)[0];\n if (declared) {\n const resolved = join(dir, declared);\n if (existsSync(resolved)) return resolved;\n log.logWarning(\n `Extension package.json declares a missing entrypoint: ${resolved}`,\n \"falling back to an index file\",\n );\n }\n for (const candidate of INDEX_CANDIDATES) {\n const indexPath = join(dir, candidate);\n if (existsSync(indexPath)) return indexPath;\n }\n return undefined;\n}\n\ninterface ExtensionPackageJson {\n name?: string;\n version?: string;\n description?: string;\n mikan?: { extensions?: string[]; displayName?: string };\n}\n\n/** Read and shape a directory's package.json; undefined when absent/malformed. */\nfunction readPackageJson(dir: string): ExtensionPackageJson | undefined {\n const packageJsonPath = join(dir, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n try {\n const parsed = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\") return undefined;\n const record = parsed as Record<string, unknown>;\n const mikanRaw = record.mikan as { extensions?: unknown; displayName?: unknown } | undefined;\n return {\n name: typeof record.name === \"string\" ? record.name : undefined,\n version: typeof record.version === \"string\" ? record.version : undefined,\n description: typeof record.description === \"string\" ? record.description : undefined,\n mikan: {\n extensions: Array.isArray(mikanRaw?.extensions)\n ? mikanRaw.extensions.filter((entry): entry is string => typeof entry === \"string\")\n : undefined,\n displayName: typeof mikanRaw?.displayName === \"string\" ? mikanRaw.displayName : undefined,\n },\n };\n } catch (err) {\n log.logWarning(`Ignoring malformed package.json: ${packageJsonPath}`, String(err));\n return undefined;\n }\n}\n\n/** Read the `mikan.extensions` entrypoint list from a directory's package.json. */\nfunction readMikanManifestEntrypoints(dir: string): string[] {\n return readPackageJson(dir)?.mikan?.extensions ?? [];\n}\n\nfunction sanitizeSlug(base: string): string {\n const slug = base\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64);\n return slug || \"extension\";\n}\n\n/**\n * Filesystem-safe identifier for an extension, derived from its install\n * location: the directory name for a directory-form extension, or the file\n * basename for a bare file. The slug keys the extension's data dir, secrets\n * vault, and schedule ownership — installing the same extension globally and\n * per-conversation shares one slug and therefore one shared data dir.\n */\nexport function extensionSlug(entrypoint: string): string {\n // Bare-file form (rootDir === entrypoint, a *.mjs/.ts file) → file basename.\n // Directory form → directory name. Detect the directory form structurally:\n // an entrypoint whose parent holds a package.json or is an index file.\n if (INDEX_FILE_PATTERN.test(basename(entrypoint))) {\n return sanitizeSlug(basename(dirname(entrypoint)));\n }\n return sanitizeSlug(basename(entrypoint).replace(EXTENSION_FILE_PATTERN, \"\"));\n}\n\n/** Slug from a discovered extension's root dir (directory or bare file path). */\nfunction slugForRoot(rootDir: string): string {\n return EXTENSION_FILE_PATTERN.test(basename(rootDir))\n ? sanitizeSlug(basename(rootDir).replace(EXTENSION_FILE_PATTERN, \"\"))\n : sanitizeSlug(basename(rootDir));\n}\n\n/** Sanitize an extension-chosen schedule name into a filename segment. */\nfunction scheduleNameSegment(name: string): string {\n const segment = name\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64);\n if (!segment) throw new Error(`Invalid schedule name: ${JSON.stringify(name)}`);\n return segment;\n}\n\n/**\n * Read display metadata (name/version/description) for a directory-form\n * extension. `package.json` is the primary source — its standard `name`,\n * `version`, `description`, plus an optional `mikan.displayName` that\n * overrides the npm name for the user-facing label (npm names are\n * lowercase/scoped; display names can be arbitrary). A `manifest.json` is a\n * fallback for extensions that ship no package.json.\n */\nfunction readManifest(rootDir: string): ExtensionManifest {\n // Bare-file extensions (rootDir is a *.mjs/.ts file) have no manifest.\n if (EXTENSION_FILE_PATTERN.test(basename(rootDir))) return {};\n\n const pkg = readPackageJson(rootDir);\n if (pkg && (pkg.mikan?.displayName ?? pkg.name ?? pkg.version ?? pkg.description)) {\n return {\n name: pkg.mikan?.displayName ?? pkg.name,\n version: pkg.version,\n description: pkg.description,\n };\n }\n\n const manifestPath = join(rootDir, \"manifest.json\");\n if (!existsSync(manifestPath)) return {};\n try {\n const parsed: unknown = JSON.parse(readFileSync(manifestPath, \"utf-8\"));\n if (!parsed || typeof parsed !== \"object\") return {};\n const record = parsed as Record<string, unknown>;\n return {\n name: typeof record.name === \"string\" ? record.name : undefined,\n version: typeof record.version === \"string\" ? record.version : undefined,\n description: typeof record.description === \"string\" ? record.description : undefined,\n };\n } catch (err) {\n log.logWarning(`Ignoring malformed extension manifest: ${manifestPath}`, String(err));\n return {};\n }\n}\n\n/**\n * Skills shipped inside a directory-form extension (`<dir>/skills/`).\n * Marked inline: extension files live under the host-only state dir, which\n * sandbox containers cannot read, so skill bodies must ride in the prompt.\n */\nfunction loadExtensionSkills(rootDir: string, slug: string): MikanSkill[] {\n // Bare-file extensions (rootDir is a *.mjs/.ts file) ship no skills.\n if (EXTENSION_FILE_PATTERN.test(basename(rootDir))) return [];\n const skillsDir = join(rootDir, \"skills\");\n if (!existsSync(skillsDir)) return [];\n const result = loadSkillsFromDir({ dir: skillsDir, source: `extension:${slug}` });\n for (const diagnostic of result.diagnostics) {\n log.logWarning(`Extension skill warning (${slug}): ${diagnostic.message}`, diagnostic.path);\n }\n for (const skill of result.skills) skill.inline = true;\n return result.skills;\n}\n\nconst SCHEDULE_FILE_SUFFIX = \".json\";\n\nfunction schedulePrefix(slug: string, conversationId: string): string {\n return `ext.${slug}.${scheduleNameSegment(conversationId)}.`;\n}\n\nfunction payloadFromSpec(\n spec: ExtensionScheduleSpec,\n conversationId: string,\n): ExtensionSchedulePayload {\n if (spec.type === \"periodic\") {\n if (!spec.schedule || !spec.timezone) {\n throw new Error(\"periodic schedule requires schedule and timezone\");\n }\n return {\n type: \"periodic\",\n conversationId,\n text: spec.text,\n schedule: spec.schedule,\n timezone: spec.timezone,\n ...(spec.platform ? { platform: spec.platform } : {}),\n };\n }\n if (!spec.at) throw new Error(\"one-shot schedule requires at\");\n return {\n type: \"one-shot\",\n conversationId,\n text: spec.text,\n at: spec.at,\n ...(spec.platform ? { platform: spec.platform } : {}),\n };\n}\n\nfunction specFromPayload(payload: ExtensionSchedulePayload): ExtensionScheduleSpec {\n if (payload.type === \"periodic\") {\n return {\n type: \"periodic\",\n schedule: payload.schedule ?? \"\",\n timezone: payload.timezone ?? \"\",\n text: payload.text,\n ...(payload.platform ? { platform: payload.platform } : {}),\n };\n }\n return {\n type: \"one-shot\",\n at: payload.at ?? \"\",\n text: payload.text,\n ...(payload.platform ? { platform: payload.platform } : {}),\n };\n}\n\n/** Build the v2 api surface for one extension over the injected services. */\nfunction buildExtensionApi(params: {\n name: string;\n slug: string;\n registry: ExtensionRegistry;\n context: LoadExtensionsOptions[\"context\"];\n services: ExtensionHostServices;\n}): MikanExtensionApi {\n const { name, slug, registry, context, services } = params;\n const stateDir = services.stateDir ?? join(homedir(), \".mikan\");\n const conversationId = context.conversationId;\n\n const requireScheduleStore = () => {\n if (!services.scheduleStore) {\n throw new Error(\"api.schedules is unavailable: this context provides no schedule store\");\n }\n return services.scheduleStore;\n };\n\n return {\n on: (hook, handler) => registry.register(name, hook, handler),\n registerTool: (tool: AgentTool) => registry.registerTool(tool),\n registerCommand: (command: ExtensionCommand) => registry.registerCommand(name, command),\n onDispose: (disposer: ExtensionDisposer) => registry.registerDisposer(name, disposer),\n log: (message: string) => log.logInfo(`[extension:${name}] ${message}`),\n context,\n paths: {\n get dataDir(): string {\n // This conversation's own data, co-located with the conversation's\n // other host-only assets; removed when the conversation is deleted.\n const dir = join(stateDir, \"conversations\", conversationId, \"extension-data\", slug);\n mkdirSync(dir, { recursive: true });\n return dir;\n },\n get sharedDataDir(): string {\n // Cross-conversation data under the sibling `global` scope.\n const dir = join(stateDir, \"global\", \"extension-data\", slug);\n mkdirSync(dir, { recursive: true });\n return dir;\n },\n },\n secrets: {\n get: (key: string) => services.resolveSecrets?.(slug)[key],\n list: () => Object.keys(services.resolveSecrets?.(slug) ?? {}),\n },\n schedules: {\n upsert: async (scheduleName, spec) => {\n const store = requireScheduleStore();\n const filename = `${schedulePrefix(slug, conversationId)}${scheduleNameSegment(scheduleName)}${SCHEDULE_FILE_SUFFIX}`;\n await store.write(filename, payloadFromSpec(spec, conversationId));\n },\n delete: async (scheduleName) => {\n const store = requireScheduleStore();\n const filename = `${schedulePrefix(slug, conversationId)}${scheduleNameSegment(scheduleName)}${SCHEDULE_FILE_SUFFIX}`;\n return store.delete(filename);\n },\n list: async () => {\n const store = requireScheduleStore();\n const prefix = schedulePrefix(slug, conversationId);\n const infos: ExtensionScheduleInfo[] = [];\n for (const entry of await store.list()) {\n if (!entry.filename.startsWith(prefix)) continue;\n if (!entry.filename.endsWith(SCHEDULE_FILE_SUFFIX)) continue;\n infos.push({\n name: entry.filename.slice(prefix.length, -SCHEDULE_FILE_SUFFIX.length),\n spec: specFromPayload(entry.payload),\n });\n }\n return infos;\n },\n },\n subagent: {\n run: async (request) => {\n if (!services.runSubagent) {\n throw new Error(\"api.subagent is unavailable: this context provides no subagent runner\");\n }\n return services.runSubagent(request, registry.getContributedTools());\n },\n },\n notify: async (text: string, options?: { conversationId?: string }) => {\n if (!services.postMessage) {\n throw new Error(\"api.notify is unavailable: this context provides no platform messaging\");\n }\n await services.postMessage(options?.conversationId ?? conversationId, text);\n },\n react: async (messageTs: string, emoji: string) => {\n if (!services.addReaction) {\n throw new Error(\"api.react is unavailable: this context provides no reaction support\");\n }\n await services.addReaction(conversationId, messageTs, emoji);\n },\n uploadFile: async (filePath: string, title?: string) => {\n if (!services.uploadFile) {\n throw new Error(\"api.uploadFile is unavailable: this context provides no file uploads\");\n }\n await services.uploadFile(conversationId, filePath, title);\n },\n triggerRun: async (text: string) => {\n const store = requireScheduleStore();\n // Distinct \"extrun.\" namespace: run files must never surface in\n // api.schedules.list(), whose ownership filter is the \"ext.\" prefix.\n // The embedder's watcher fires and deletes the file immediately.\n const filename = `extrun.${slug}.${scheduleNameSegment(conversationId)}.${Date.now()}-${runCounter++}${SCHEDULE_FILE_SUFFIX}`;\n await store.write(filename, { type: \"immediate\", conversationId, text });\n },\n };\n}\n\n/** Monotonic suffix so rapid triggerRun calls in one process never collide. */\nlet runCounter = 0;\n\nfunction resolveActivate(moduleExports: unknown): MikanExtensionModule | undefined {\n if (!moduleExports || typeof moduleExports !== \"object\") return undefined;\n const candidates: unknown[] = [(moduleExports as { default?: unknown }).default, moduleExports];\n for (const candidate of candidates) {\n if (typeof candidate === \"function\") {\n return { activate: candidate as MikanExtensionActivate };\n }\n if (candidate && typeof candidate === \"object\") {\n const activate = (candidate as { activate?: unknown }).activate;\n if (typeof activate === \"function\") {\n return {\n name:\n typeof (candidate as { name?: unknown }).name === \"string\"\n ? (candidate as { name: string }).name\n : undefined,\n activate: activate as MikanExtensionActivate,\n };\n }\n }\n }\n return undefined;\n}\n\n/** Load and activate all extensions found in the given directories. */\nexport async function loadExtensions(\n options: LoadExtensionsOptions,\n): Promise<LoadExtensionsResult> {\n const registry = new ExtensionRegistry();\n const extensions: LoadedExtension[] = [];\n const errors: ExtensionLoadError[] = [];\n const skills: MikanSkill[] = [];\n const services = options.services ?? {};\n\n for (const dir of options.dirs) {\n for (const { entrypoint, rootDir } of discoverExtensionEntrypoints(dir)) {\n try {\n const moduleExports: unknown = await importExtensionModule(entrypoint);\n const extension = resolveActivate(moduleExports);\n if (!extension) {\n errors.push({\n path: entrypoint,\n error: \"extension must export an activate function (default or named)\",\n });\n continue;\n }\n const slug = slugForRoot(rootDir);\n const manifest = readManifest(rootDir);\n const name = manifest.name ?? extension.name ?? slug;\n const api = buildExtensionApi({\n name,\n slug,\n registry,\n context: options.context,\n services,\n });\n const disposer = await extension.activate(api);\n if (typeof disposer === \"function\") registry.registerDisposer(name, disposer);\n const extensionSkills = loadExtensionSkills(rootDir, slug);\n skills.push(...extensionSkills);\n extensions.push({\n name,\n path: entrypoint,\n slug,\n version: manifest.version,\n description: manifest.description,\n skills: extensionSkills,\n });\n } catch (err) {\n errors.push({\n path: entrypoint,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n return { registry, extensions, errors, skills, dispose: () => registry.dispose() };\n}\n\nexport interface ExtensionValidation {\n ok: boolean;\n /** Slug the extension would install as (from the source dir/file name). */\n slug: string;\n /** Display name (manifest name, else slug). */\n name: string;\n version?: string;\n description?: string;\n /** Resolved entrypoint that would be imported. */\n entrypoint?: string;\n /** Skill names shipped alongside the extension. */\n skillNames: string[];\n errors: string[];\n warnings: string[];\n}\n\n/**\n * Validate an extension source path (a directory or a single file) WITHOUT\n * activating it: resolves the entrypoint (package.json `mikan.extensions`,\n * index file, or the file itself), imports it, and checks it exports an\n * `activate` function. Used by `mikan ext install` as a preflight and by\n * `mikan ext validate`. Importing runs top-level module code but not\n * `activate`, so there are no schedule/tool side effects.\n */\nexport async function validateExtension(sourcePath: string): Promise<ExtensionValidation> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const rootDir = sourcePath.replace(/[/\\\\]+$/, \"\");\n const base = basename(rootDir);\n\n if (INDEX_FILE_PATTERN.test(base)) {\n warnings.push(\n \"Entry is a bare index file; install into a named directory so the slug is stable.\",\n );\n }\n\n let entrypoint: string | undefined;\n if (!existsSync(rootDir)) {\n errors.push(`Path does not exist: ${rootDir}`);\n } else if (statSync(rootDir).isDirectory()) {\n entrypoint = resolveDirectoryEntrypoint(rootDir);\n if (!entrypoint) {\n errors.push(\n \"No entrypoint found: expected package.json with a mikan.extensions entry, or an index.{mjs,js,ts,mts}.\",\n );\n }\n } else if (EXTENSION_FILE_PATTERN.test(base)) {\n entrypoint = rootDir;\n } else {\n errors.push(`Not an extension file (expected .mjs/.js/.ts/.mts): ${rootDir}`);\n }\n\n const slug = slugForRoot(rootDir);\n const manifest = readManifest(rootDir);\n const skillNames = loadExtensionSkills(rootDir, slug).map((skill) => skill.name);\n\n if (entrypoint) {\n try {\n const moduleExports: unknown = await importExtensionModule(entrypoint);\n if (!resolveActivate(moduleExports)) {\n errors.push(\"Module does not export an activate function (default or named).\");\n }\n } catch (err) {\n errors.push(`Failed to import: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return {\n ok: errors.length === 0,\n slug,\n name: manifest.name ?? slug,\n version: manifest.version,\n description: manifest.description,\n entrypoint,\n skillNames,\n errors,\n warnings,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"loader.js","sourceRoot":"","sources":["../../../src/harness/extensions/loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AAChF,OAAO,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACtC,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAGlC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAmB,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAgBlD,MAAM,sBAAsB,GAAG,oBAAoB,CAAC;AACpD,MAAM,kBAAkB,GAAG,0BAA0B,CAAC;AACtD,MAAM,gBAAgB,GAAG,CAAC,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;AAE5E;;;;;GAKG;AACH,KAAK,UAAU,qBAAqB,CAAC,UAAkB;IACrD,MAAM,IAAI,GAAG,UAAU,CAAC,OAAO,IAAI,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;IACjF,OAAO,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;AACjC,CAA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AAC;SAAM,IAAI,sBAAsB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7C,UAAU,GAAG,OAAO,CAAC;IACvB,CAAC;SAAM,CAAC;QACN,MAAM,CAAC,IAAI,CAAC,uDAAuD,OAAO,EAAE,CAAC,CAAC;IAChF,CAAC;IAED,MAAM,IAAI,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IACpC,MAAM,QAAQ,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,UAAU,GAAG,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAEjF,IAAI,UAAU,EAAE,CAAC;QACf,IAAI,CAAC;YACH,MAAM,aAAa,GAAY,MAAM,qBAAqB,CAAC,UAAU,CAAC,CAAC;YACvE,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,EAAE,CAAC;gBACpC,MAAM,CAAC,IAAI,CAAC,iEAAiE,CAAC,CAAC;YACjF,CAAC;QACH,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,IAAI,CAAC,qBAAqB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACvF,CAAC;IACH,CAAC;IAED,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC;QACvB,IAAI;QACJ,IAAI,EAAE,QAAQ,CAAC,IAAI,IAAI,IAAI;QAC3B,OAAO,EAAE,QAAQ,CAAC,OAAO;QACzB,WAAW,EAAE,QAAQ,CAAC,WAAW;QACjC,UAAU;QACV,UAAU;QACV,MAAM;QACN,QAAQ;KACT,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Extension discovery and activation.\n *\n * Extension modules execute inside the mikan host process with its full\n * privileges (platform tokens, vault, host filesystem). They must therefore\n * only ever load from host-controlled directories: installing an extension\n * is an administrator action. In particular, extension directories must not\n * live under paths mounted into sandbox containers (workspace and\n * conversation dirs in image mode), or code written from inside the sandbox\n * would be imported into the host process — a sandbox escape.\n * {@link defaultExtensionDirs} returns the canonical host-only locations\n * under mikan's state dir.\n *\n * Directories are scanned in order; all discovered extensions activate.\n * Accepted layouts (entrypoint may be .mjs/.js/.ts/.mts — loaded via jiti):\n *\n * - `extensions/<name>.<ext>` (bare file)\n * - `extensions/<name>/index.<ext>` (directory + index)\n * - `extensions/<name>/package.json` (mikan.extensions entrypoint;\n * may carry npm dependencies in node_modules)\n *\n * Modules are imported with a fresh jiti instance (no cache) so edited\n * extensions are picked up when a new harness instance is created.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from \"fs\";\nimport { homedir } from \"os\";\nimport { basename, join } from \"path\";\nimport { createJiti } from \"jiti\";\nimport type { AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, Model } from \"@earendil-works/pi-ai\";\nimport * as log from \"../../log.js\";\nimport { buildEventPayload } from \"../event-format.js\";\nimport { loadSkillsFromDir, type MikanSkill } from \"../skills.js\";\nimport { ExtensionRegistry } from \"./registry.js\";\nimport type {\n ExtensionCommand,\n ExtensionDisposer,\n ExtensionHostServices,\n ExtensionLoadError,\n ExtensionManifest,\n ExtensionSchedulePayload,\n ExtensionScheduleInfo,\n ExtensionScheduleSpec,\n LoadedExtension,\n MikanExtensionActivate,\n MikanExtensionApi,\n MikanExtensionModule,\n} from \"./types.js\";\n\nconst EXTENSION_FILE_PATTERN = /\\.(mjs|js|ts|mts)$/;\nconst INDEX_FILE_PATTERN = /^index\\.(mjs|js|ts|mts)$/;\nconst INDEX_CANDIDATES = [\"index.mjs\", \"index.js\", \"index.ts\", \"index.mts\"];\n\n/**\n * Import an extension entrypoint through jiti so it can be TypeScript and can\n * use node_modules dependencies, transparently compiling on the fly. A fresh\n * jiti instance with caching disabled is used per load so edited extensions\n * are picked up when a new harness instance is created for a conversation.\n */\nasync function importExtensionModule(entrypoint: string): Promise<unknown> {\n const jiti = createJiti(import.meta.url, { moduleCache: false, fsCache: false });\n return jiti.import(entrypoint);\n}\n\n/**\n * Canonical host-only extension code directories for a conversation, in load\n * order: `<stateDir>/global/extensions` (all conversations) then\n * `<stateDir>/conversations/<conversationId>/extensions` (that conversation\n * only). `global` and `conversations` are the two sibling scopes; see\n * `LAYOUT.md`. Conversation ids are used verbatim (see LAYOUT.md § Casing).\n */\nexport function defaultExtensionDirs(\n conversationId: string,\n stateDir: string = join(homedir(), \".mikan\"),\n): string[] {\n return [\n join(stateDir, \"global\", \"extensions\"),\n join(stateDir, \"conversations\", conversationId, \"extensions\"),\n ];\n}\n\n/** Discovery-only view of an installed extension (module is not imported). */\nexport interface InstalledExtensionInfo {\n /** Display name: manifest name, falling back to the slug. */\n name: string;\n slug: string;\n path: string;\n /** Scan directory the extension was found in. */\n dir: string;\n version?: string;\n description?: string;\n /** Names of skills shipped in the extension's skills/ directory. */\n skillNames: string[];\n}\n\n/**\n * List installed extensions without importing or activating them — safe for\n * inventory surfaces (commands, portal). Activation side effects (schedule\n * upserts, tool registration) only happen in {@link loadExtensions}.\n */\nexport function listInstalledExtensions(dirs: string[]): InstalledExtensionInfo[] {\n const infos: InstalledExtensionInfo[] = [];\n for (const dir of dirs) {\n for (const { entrypoint, rootDir } of discoverExtensionEntrypoints(dir)) {\n const slug = extensionSlug(rootDir);\n const manifest = readManifest(rootDir);\n infos.push({\n name: manifest.name ?? slug,\n slug,\n path: entrypoint,\n dir,\n version: manifest.version,\n description: manifest.description,\n skillNames: loadExtensionSkills(rootDir, slug).map((skill) => skill.name),\n });\n }\n }\n return infos;\n}\n\nexport interface LoadExtensionsOptions {\n /** Directories to scan for extensions. Missing directories are skipped. */\n dirs: string[];\n context: {\n conversationId: string;\n workspaceDir: string;\n model: Model<Api>;\n thinkingLevel: ThinkingLevel;\n };\n /** Embedder-provided services backing the v2 api surface. */\n services?: ExtensionHostServices;\n}\n\nexport interface LoadExtensionsResult {\n registry: ExtensionRegistry;\n extensions: LoadedExtension[];\n errors: ExtensionLoadError[];\n /** Skills contributed by extensions (inline: bodies ride in the prompt). */\n skills: MikanSkill[];\n /**\n * Run extension disposers (from `api.onDispose` and `activate` return\n * values). Call when the harness instance owning these extensions is\n * discarded. Idempotent; disposer errors are logged, never thrown.\n */\n dispose(): Promise<void>;\n}\n\n/**\n * A discovered extension: its entrypoint (module to import) and root dir\n * (used for slug, manifest.json, and skills/ — which sit at the extension\n * root, not necessarily next to a nested entrypoint).\n */\ninterface DiscoveredExtension {\n entrypoint: string;\n rootDir: string;\n}\n\nfunction discoverExtensionEntrypoints(dir: string): DiscoveredExtension[] {\n if (!existsSync(dir)) return [];\n const found: DiscoveredExtension[] = [];\n for (const name of readdirSync(dir).toSorted()) {\n if (name.startsWith(\".\")) continue;\n if (INDEX_FILE_PATTERN.test(name)) {\n // An index file at the scan root means the extension's contents were\n // copied into the scope directory itself; the slug would degenerate to\n // the scope name (e.g. the conversation id), mis-keying its data dir,\n // secrets, and schedules. Require a named form instead.\n log.logWarning(\n `Ignoring extension index file at scope root: ${join(dir, name)}`,\n \"install into a named subdirectory (e.g. extensions/<scope>/my-ext/index.mjs)\",\n );\n continue;\n }\n const fullPath = join(dir, name);\n let stats;\n try {\n stats = statSync(fullPath);\n } catch {\n continue;\n }\n if (stats.isFile() && EXTENSION_FILE_PATTERN.test(name)) {\n // Bare-file form: the file is both entrypoint and (its own) root.\n found.push({ entrypoint: fullPath, rootDir: fullPath });\n continue;\n }\n if (stats.isDirectory()) {\n const entrypoint = resolveDirectoryEntrypoint(fullPath);\n if (entrypoint) found.push({ entrypoint, rootDir: fullPath });\n }\n }\n return found;\n}\n\n/**\n * Resolve a directory-form extension's entrypoint. A `package.json` with a\n * `mikan.extensions` array (first entry, relative to the dir) wins — this is\n * how an extension declares a TypeScript entry and pulls in npm dependencies.\n * Otherwise fall back to an `index.{mjs,js,ts,mts}` file. Returns undefined\n * when neither is present.\n */\nfunction resolveDirectoryEntrypoint(dir: string): string | undefined {\n const declared = readMikanManifestEntrypoints(dir)[0];\n if (declared) {\n const resolved = join(dir, declared);\n if (existsSync(resolved)) return resolved;\n log.logWarning(\n `Extension package.json declares a missing entrypoint: ${resolved}`,\n \"falling back to an index file\",\n );\n }\n for (const candidate of INDEX_CANDIDATES) {\n const indexPath = join(dir, candidate);\n if (existsSync(indexPath)) return indexPath;\n }\n return undefined;\n}\n\ninterface ExtensionPackageJson {\n name?: string;\n version?: string;\n description?: string;\n mikan?: { extensions?: string[]; displayName?: string };\n}\n\n/** Read and shape a directory's package.json; undefined when absent/malformed. */\nfunction readPackageJson(dir: string): ExtensionPackageJson | undefined {\n const packageJsonPath = join(dir, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n try {\n const parsed = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")) as unknown;\n if (!parsed || typeof parsed !== \"object\") return undefined;\n const record = parsed as Record<string, unknown>;\n const mikanRaw = record.mikan as { extensions?: unknown; displayName?: unknown } | undefined;\n return {\n name: typeof record.name === \"string\" ? record.name : undefined,\n version: typeof record.version === \"string\" ? record.version : undefined,\n description: typeof record.description === \"string\" ? record.description : undefined,\n mikan: {\n extensions: Array.isArray(mikanRaw?.extensions)\n ? mikanRaw.extensions.filter((entry): entry is string => typeof entry === \"string\")\n : undefined,\n displayName: typeof mikanRaw?.displayName === \"string\" ? mikanRaw.displayName : undefined,\n },\n };\n } catch (err) {\n log.logWarning(`Ignoring malformed package.json: ${packageJsonPath}`, String(err));\n return undefined;\n }\n}\n\n/** Read the `mikan.extensions` entrypoint list from a directory's package.json. */\nfunction readMikanManifestEntrypoints(dir: string): string[] {\n return readPackageJson(dir)?.mikan?.extensions ?? [];\n}\n\n/** The one filesystem-safe segment sanitizer for extension identity and schedule names. */\nfunction sanitizeSegment(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 64);\n}\n\nfunction sanitizeSlug(base: string): string {\n return sanitizeSegment(base) || \"extension\";\n}\n\n/**\n * Filesystem-safe identifier for an extension, derived from its root (the\n * install directory, or the file path for a bare-file extension). The slug\n * keys the extension's data dir, secrets vault, and schedule ownership —\n * installing the same extension globally and per-conversation shares one\n * slug and therefore one shared data dir. This is the only slug derivation:\n * a second one keyed off a different input (e.g. the entrypoint, which for\n * package.json-form extensions can live under dist/) would silently split an\n * extension's identity.\n */\nexport function extensionSlug(rootDir: string): string {\n return EXTENSION_FILE_PATTERN.test(basename(rootDir))\n ? sanitizeSlug(basename(rootDir).replace(EXTENSION_FILE_PATTERN, \"\"))\n : sanitizeSlug(basename(rootDir));\n}\n\n/** Sanitize an extension-chosen schedule name into a filename segment. */\nfunction scheduleNameSegment(name: string): string {\n const segment = sanitizeSegment(name);\n if (!segment) throw new Error(`Invalid schedule name: ${JSON.stringify(name)}`);\n return segment;\n}\n\n/**\n * Read display metadata (name/version/description) for a directory-form\n * extension. `package.json` is the primary source — its standard `name`,\n * `version`, `description`, plus an optional `mikan.displayName` that\n * overrides the npm name for the user-facing label (npm names are\n * lowercase/scoped; display names can be arbitrary). A `manifest.json` is a\n * fallback for extensions that ship no package.json.\n */\nfunction readManifest(rootDir: string): ExtensionManifest {\n // Bare-file extensions (rootDir is a *.mjs/.ts file) have no manifest.\n if (EXTENSION_FILE_PATTERN.test(basename(rootDir))) return {};\n\n const pkg = readPackageJson(rootDir);\n if (pkg && (pkg.mikan?.displayName ?? pkg.name ?? pkg.version ?? pkg.description)) {\n return {\n name: pkg.mikan?.displayName ?? pkg.name,\n version: pkg.version,\n description: pkg.description,\n };\n }\n\n const manifestPath = join(rootDir, \"manifest.json\");\n if (!existsSync(manifestPath)) return {};\n try {\n const parsed: unknown = JSON.parse(readFileSync(manifestPath, \"utf-8\"));\n if (!parsed || typeof parsed !== \"object\") return {};\n const record = parsed as Record<string, unknown>;\n return {\n name: typeof record.name === \"string\" ? record.name : undefined,\n version: typeof record.version === \"string\" ? record.version : undefined,\n description: typeof record.description === \"string\" ? record.description : undefined,\n };\n } catch (err) {\n log.logWarning(`Ignoring malformed extension manifest: ${manifestPath}`, String(err));\n return {};\n }\n}\n\n/**\n * Skills shipped inside a directory-form extension (`<dir>/skills/`).\n * Marked inline: extension files live under the host-only state dir, which\n * sandbox containers cannot read, so skill bodies must ride in the prompt.\n */\nfunction loadExtensionSkills(rootDir: string, slug: string): MikanSkill[] {\n // Bare-file extensions (rootDir is a *.mjs/.ts file) ship no skills.\n if (EXTENSION_FILE_PATTERN.test(basename(rootDir))) return [];\n const skillsDir = join(rootDir, \"skills\");\n if (!existsSync(skillsDir)) return [];\n const result = loadSkillsFromDir({ dir: skillsDir, source: `extension:${slug}` });\n for (const diagnostic of result.diagnostics) {\n log.logWarning(`Extension skill warning (${slug}): ${diagnostic.message}`, diagnostic.path);\n }\n for (const skill of result.skills) skill.inline = true;\n return result.skills;\n}\n\nconst SCHEDULE_FILE_SUFFIX = \".json\";\n\nfunction schedulePrefix(slug: string, conversationId: string): string {\n return `ext.${slug}.${scheduleNameSegment(conversationId)}.`;\n}\n\nfunction payloadFromSpec(\n spec: ExtensionScheduleSpec,\n conversationId: string,\n): ExtensionSchedulePayload {\n // Per-type validation (schedule/timezone for periodic, at for one-shot)\n // is owned by the event-format builder.\n return buildEventPayload({\n type: spec.type,\n conversationId,\n text: spec.text,\n ...(spec.platform ? { platform: spec.platform } : {}),\n ...(spec.type === \"periodic\"\n ? { schedule: spec.schedule, timezone: spec.timezone }\n : { at: spec.at }),\n });\n}\n\nfunction specFromPayload(payload: ExtensionSchedulePayload): ExtensionScheduleSpec {\n if (payload.type === \"periodic\") {\n return {\n type: \"periodic\",\n schedule: payload.schedule,\n timezone: payload.timezone,\n text: payload.text,\n ...(payload.platform ? { platform: payload.platform } : {}),\n };\n }\n // `immediate` payloads never appear under the schedules namespace (they\n // live under \"extrun.\"); tolerate them as an empty one-shot rather than\n // widening the spec union.\n return {\n type: \"one-shot\",\n at: payload.type === \"one-shot\" ? payload.at : \"\",\n text: payload.text,\n ...(payload.platform ? { platform: payload.platform } : {}),\n };\n}\n\n/** Build the v2 api surface for one extension over the injected services. */\nfunction buildExtensionApi(params: {\n name: string;\n slug: string;\n registry: ExtensionRegistry;\n context: LoadExtensionsOptions[\"context\"];\n services: ExtensionHostServices;\n}): MikanExtensionApi {\n const { name, slug, registry, context, services } = params;\n const stateDir = services.stateDir ?? join(homedir(), \".mikan\");\n const conversationId = context.conversationId;\n\n const requireScheduleStore = () => {\n if (!services.scheduleStore) {\n throw new Error(\"api.schedules is unavailable: this context provides no schedule store\");\n }\n return services.scheduleStore;\n };\n\n return {\n on: (hook, handler) => registry.register(name, hook, handler),\n registerTool: (tool: AgentTool) => registry.registerTool(tool),\n registerCommand: (command: ExtensionCommand) => registry.registerCommand(name, command),\n onDispose: (disposer: ExtensionDisposer) => registry.registerDisposer(name, disposer),\n log: (message: string) => log.logInfo(`[extension:${name}] ${message}`),\n context,\n paths: {\n get dataDir(): string {\n // This conversation's own data, co-located with the conversation's\n // other host-only assets; removed when the conversation is deleted.\n const dir = join(stateDir, \"conversations\", conversationId, \"extension-data\", slug);\n mkdirSync(dir, { recursive: true });\n return dir;\n },\n get sharedDataDir(): string {\n // Cross-conversation data under the sibling `global` scope.\n const dir = join(stateDir, \"global\", \"extension-data\", slug);\n mkdirSync(dir, { recursive: true });\n return dir;\n },\n },\n secrets: {\n get: (key: string) => services.resolveSecrets?.(slug)[key],\n list: () => Object.keys(services.resolveSecrets?.(slug) ?? {}),\n },\n schedules: {\n upsert: async (scheduleName, spec) => {\n const store = requireScheduleStore();\n const filename = `${schedulePrefix(slug, conversationId)}${scheduleNameSegment(scheduleName)}${SCHEDULE_FILE_SUFFIX}`;\n await store.write(filename, payloadFromSpec(spec, conversationId));\n },\n delete: async (scheduleName) => {\n const store = requireScheduleStore();\n const filename = `${schedulePrefix(slug, conversationId)}${scheduleNameSegment(scheduleName)}${SCHEDULE_FILE_SUFFIX}`;\n return store.delete(filename);\n },\n list: async () => {\n const store = requireScheduleStore();\n const prefix = schedulePrefix(slug, conversationId);\n const infos: ExtensionScheduleInfo[] = [];\n for (const entry of await store.list()) {\n if (!entry.filename.startsWith(prefix)) continue;\n if (!entry.filename.endsWith(SCHEDULE_FILE_SUFFIX)) continue;\n infos.push({\n name: entry.filename.slice(prefix.length, -SCHEDULE_FILE_SUFFIX.length),\n spec: specFromPayload(entry.payload),\n });\n }\n return infos;\n },\n },\n subagent: {\n run: async (request) => {\n if (!services.runSubagent) {\n throw new Error(\"api.subagent is unavailable: this context provides no subagent runner\");\n }\n return services.runSubagent(request, registry.getContributedTools());\n },\n },\n notify: async (text: string, options?: { conversationId?: string }) => {\n if (!services.postMessage) {\n throw new Error(\"api.notify is unavailable: this context provides no platform messaging\");\n }\n await services.postMessage(options?.conversationId ?? conversationId, text);\n },\n react: async (messageTs: string, emoji: string) => {\n if (!services.addReaction) {\n throw new Error(\"api.react is unavailable: this context provides no reaction support\");\n }\n await services.addReaction(conversationId, messageTs, emoji);\n },\n uploadFile: async (filePath: string, title?: string) => {\n if (!services.uploadFile) {\n throw new Error(\"api.uploadFile is unavailable: this context provides no file uploads\");\n }\n await services.uploadFile(conversationId, filePath, title);\n },\n triggerRun: async (text: string) => {\n const store = requireScheduleStore();\n // Distinct \"extrun.\" namespace: run files must never surface in\n // api.schedules.list(), whose ownership filter is the \"ext.\" prefix.\n // The embedder's watcher fires and deletes the file immediately.\n const filename = `extrun.${slug}.${scheduleNameSegment(conversationId)}.${Date.now()}-${runCounter++}${SCHEDULE_FILE_SUFFIX}`;\n await store.write(filename, { type: \"immediate\", conversationId, text });\n },\n };\n}\n\n/** Monotonic suffix so rapid triggerRun calls in one process never collide. */\nlet runCounter = 0;\n\nfunction resolveActivate(moduleExports: unknown): MikanExtensionModule | undefined {\n if (!moduleExports || typeof moduleExports !== \"object\") return undefined;\n const candidates: unknown[] = [(moduleExports as { default?: unknown }).default, moduleExports];\n for (const candidate of candidates) {\n if (typeof candidate === \"function\") {\n return { activate: candidate as MikanExtensionActivate };\n }\n if (candidate && typeof candidate === \"object\") {\n const activate = (candidate as { activate?: unknown }).activate;\n if (typeof activate === \"function\") {\n return {\n name:\n typeof (candidate as { name?: unknown }).name === \"string\"\n ? (candidate as { name: string }).name\n : undefined,\n activate: activate as MikanExtensionActivate,\n };\n }\n }\n }\n return undefined;\n}\n\n/** Load and activate all extensions found in the given directories. */\nexport async function loadExtensions(\n options: LoadExtensionsOptions,\n): Promise<LoadExtensionsResult> {\n const registry = new ExtensionRegistry();\n const extensions: LoadedExtension[] = [];\n const errors: ExtensionLoadError[] = [];\n const skills: MikanSkill[] = [];\n const services = options.services ?? {};\n\n for (const dir of options.dirs) {\n for (const { entrypoint, rootDir } of discoverExtensionEntrypoints(dir)) {\n try {\n const moduleExports: unknown = await importExtensionModule(entrypoint);\n const extension = resolveActivate(moduleExports);\n if (!extension) {\n errors.push({\n path: entrypoint,\n error: \"extension must export an activate function (default or named)\",\n });\n continue;\n }\n const slug = extensionSlug(rootDir);\n const manifest = readManifest(rootDir);\n const name = manifest.name ?? extension.name ?? slug;\n const api = buildExtensionApi({\n name,\n slug,\n registry,\n context: options.context,\n services,\n });\n const disposer = await extension.activate(api);\n if (typeof disposer === \"function\") registry.registerDisposer(name, disposer);\n const extensionSkills = loadExtensionSkills(rootDir, slug);\n skills.push(...extensionSkills);\n extensions.push({\n name,\n path: entrypoint,\n slug,\n version: manifest.version,\n description: manifest.description,\n skills: extensionSkills,\n });\n } catch (err) {\n errors.push({\n path: entrypoint,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n return { registry, extensions, errors, skills, dispose: () => registry.dispose() };\n}\n\nexport interface ExtensionValidation {\n ok: boolean;\n /** Slug the extension would install as (from the source dir/file name). */\n slug: string;\n /** Display name (manifest name, else slug). */\n name: string;\n version?: string;\n description?: string;\n /** Resolved entrypoint that would be imported. */\n entrypoint?: string;\n /** Skill names shipped alongside the extension. */\n skillNames: string[];\n errors: string[];\n warnings: string[];\n}\n\n/**\n * Validate an extension source path (a directory or a single file) WITHOUT\n * activating it: resolves the entrypoint (package.json `mikan.extensions`,\n * index file, or the file itself), imports it, and checks it exports an\n * `activate` function. Used by `mikan ext install` as a preflight and by\n * `mikan ext validate`. Importing runs top-level module code but not\n * `activate`, so there are no schedule/tool side effects.\n */\nexport async function validateExtension(sourcePath: string): Promise<ExtensionValidation> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const rootDir = sourcePath.replace(/[/\\\\]+$/, \"\");\n const base = basename(rootDir);\n\n if (INDEX_FILE_PATTERN.test(base)) {\n warnings.push(\n \"Entry is a bare index file; install into a named directory so the slug is stable.\",\n );\n }\n\n let entrypoint: string | undefined;\n if (!existsSync(rootDir)) {\n errors.push(`Path does not exist: ${rootDir}`);\n } else if (statSync(rootDir).isDirectory()) {\n entrypoint = resolveDirectoryEntrypoint(rootDir);\n if (!entrypoint) {\n errors.push(\n \"No entrypoint found: expected package.json with a mikan.extensions entry, or an index.{mjs,js,ts,mts}.\",\n );\n }\n } else if (EXTENSION_FILE_PATTERN.test(base)) {\n entrypoint = rootDir;\n } else {\n errors.push(`Not an extension file (expected .mjs/.js/.ts/.mts): ${rootDir}`);\n }\n\n const slug = extensionSlug(rootDir);\n const manifest = readManifest(rootDir);\n const skillNames = loadExtensionSkills(rootDir, slug).map((skill) => skill.name);\n\n if (entrypoint) {\n try {\n const moduleExports: unknown = await importExtensionModule(entrypoint);\n if (!resolveActivate(moduleExports)) {\n errors.push(\"Module does not export an activate function (default or named).\");\n }\n } catch (err) {\n errors.push(`Failed to import: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n return {\n ok: errors.length === 0,\n slug,\n name: manifest.name ?? slug,\n version: manifest.version,\n description: manifest.description,\n entrypoint,\n skillNames,\n errors,\n warnings,\n };\n}\n"]}
|