@moxxy/sdk 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +73 -73
  2. package/dist/client-session.d.ts +10 -0
  3. package/dist/client-session.d.ts.map +1 -1
  4. package/dist/compactor-helpers.d.ts +4 -1
  5. package/dist/compactor-helpers.d.ts.map +1 -1
  6. package/dist/compactor-helpers.js +50 -21
  7. package/dist/compactor-helpers.js.map +1 -1
  8. package/dist/define.d.ts +6 -0
  9. package/dist/define.d.ts.map +1 -1
  10. package/dist/define.js +9 -0
  11. package/dist/define.js.map +1 -1
  12. package/dist/embedding.d.ts +17 -0
  13. package/dist/embedding.d.ts.map +1 -1
  14. package/dist/errors.d.ts +1 -1
  15. package/dist/errors.d.ts.map +1 -1
  16. package/dist/errors.js.map +1 -1
  17. package/dist/fs-utils.d.ts +27 -0
  18. package/dist/fs-utils.d.ts.map +1 -0
  19. package/dist/fs-utils.js +44 -0
  20. package/dist/fs-utils.js.map +1 -0
  21. package/dist/http-utils.d.ts +16 -0
  22. package/dist/http-utils.d.ts.map +1 -0
  23. package/dist/http-utils.js +40 -0
  24. package/dist/http-utils.js.map +1 -0
  25. package/dist/index.d.ts +15 -8
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +9 -4
  28. package/dist/index.js.map +1 -1
  29. package/dist/mode-helpers.d.ts +58 -0
  30. package/dist/mode-helpers.d.ts.map +1 -1
  31. package/dist/mode-helpers.js +119 -0
  32. package/dist/mode-helpers.js.map +1 -1
  33. package/dist/mode.d.ts +34 -0
  34. package/dist/mode.d.ts.map +1 -1
  35. package/dist/mutex.d.ts +15 -0
  36. package/dist/mutex.d.ts.map +1 -0
  37. package/dist/mutex.js +15 -0
  38. package/dist/mutex.js.map +1 -0
  39. package/dist/plugin.d.ts +36 -1
  40. package/dist/plugin.d.ts.map +1 -1
  41. package/dist/provider-utils.d.ts +6 -0
  42. package/dist/provider-utils.d.ts.map +1 -1
  43. package/dist/provider-utils.js +8 -0
  44. package/dist/provider-utils.js.map +1 -1
  45. package/dist/requirements.d.ts +1 -1
  46. package/dist/requirements.d.ts.map +1 -1
  47. package/dist/resolvers.d.ts +52 -0
  48. package/dist/resolvers.d.ts.map +1 -0
  49. package/dist/resolvers.js +123 -0
  50. package/dist/resolvers.js.map +1 -0
  51. package/dist/schemas.d.ts +28 -28
  52. package/dist/schemas.d.ts.map +1 -1
  53. package/dist/schemas.js +2 -0
  54. package/dist/schemas.js.map +1 -1
  55. package/dist/session-like.d.ts +98 -2
  56. package/dist/session-like.d.ts.map +1 -1
  57. package/dist/synthesizer.d.ts +63 -0
  58. package/dist/synthesizer.d.ts.map +1 -0
  59. package/dist/synthesizer.js +21 -0
  60. package/dist/synthesizer.js.map +1 -0
  61. package/dist/tool.d.ts +13 -0
  62. package/dist/tool.d.ts.map +1 -1
  63. package/dist/voice.d.ts +36 -0
  64. package/dist/voice.d.ts.map +1 -0
  65. package/dist/voice.js +82 -0
  66. package/dist/voice.js.map +1 -0
  67. package/dist/workflow.d.ts +144 -0
  68. package/dist/workflow.d.ts.map +1 -0
  69. package/dist/workflow.js +14 -0
  70. package/dist/workflow.js.map +1 -0
  71. package/package.json +14 -14
  72. package/src/client-session.ts +11 -0
  73. package/src/compactor-helpers.test.ts +41 -0
  74. package/src/compactor-helpers.ts +53 -19
  75. package/src/define.ts +15 -0
  76. package/src/embedding.ts +18 -0
  77. package/src/errors.ts +3 -0
  78. package/src/fs-utils.test.ts +61 -0
  79. package/src/fs-utils.ts +55 -0
  80. package/src/http-utils.test.ts +36 -0
  81. package/src/http-utils.ts +40 -0
  82. package/src/index.ts +69 -3
  83. package/src/mode-helpers.ts +169 -0
  84. package/src/mode.ts +35 -0
  85. package/src/mutex.test.ts +36 -0
  86. package/src/mutex.ts +31 -0
  87. package/src/plugin.ts +36 -1
  88. package/src/provider-utils.ts +9 -0
  89. package/src/requirements.ts +1 -0
  90. package/src/resolvers.test.ts +45 -0
  91. package/src/resolvers.ts +164 -0
  92. package/src/schemas.ts +2 -0
  93. package/src/session-like.ts +100 -2
  94. package/src/stuck-loop.test.ts +42 -0
  95. package/src/synthesizer.ts +67 -0
  96. package/src/tool.ts +13 -0
  97. package/src/voice.ts +103 -0
  98. package/src/workflow.ts +165 -0
  99. package/dist/command-sync.d.ts +0 -23
  100. package/dist/command-sync.d.ts.map +0 -1
  101. package/dist/command-sync.js +0 -36
  102. package/dist/command-sync.js.map +0 -1
  103. package/dist/loop-helpers.d.ts +0 -68
  104. package/dist/loop-helpers.d.ts.map +0 -1
  105. package/dist/loop-helpers.js +0 -283
  106. package/dist/loop-helpers.js.map +0 -1
  107. package/dist/loop.d.ts +0 -106
  108. package/dist/loop.d.ts.map +0 -1
  109. package/dist/loop.js +0 -2
  110. package/dist/loop.js.map +0 -1
  111. package/dist/plugin-kind.d.ts +0 -10
  112. package/dist/plugin-kind.d.ts.map +0 -1
  113. package/dist/plugin-kind.js +0 -31
  114. package/dist/plugin-kind.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import type { MoxxyEvent, UserPromptAttachment } from './events.js';
2
2
  import type { SessionId, TurnId } from './ids.js';
3
3
  import type { EventLogReader } from './log.js';
4
- import type { ApprovalResolver } from './mode.js';
4
+ import type { ApprovalResolver, ModeBadge } from './mode.js';
5
5
  import type { PermissionResolver } from './permission.js';
6
6
  import type { ModelDescriptor } from './provider.js';
7
7
  import type { ToolCompactPresentation } from './tool.js';
@@ -40,10 +40,23 @@ export interface SessionLogReader extends EventLogReader {
40
40
  subscribe(fn: (event: MoxxyEvent) => void | Promise<void>): () => void;
41
41
  }
42
42
 
43
- /** Serializable provider metadata (models + context windows) for display. */
43
+ /** How a provider authenticates. UIs use this to decide whether to
44
+ * show an API-key field or kick off an OAuth flow. */
45
+ export type ProviderAuthKind = 'api-key' | 'oauth';
46
+
47
+ /** Serializable provider metadata (models + context windows + auth)
48
+ * for display. */
44
49
  export interface ProviderInfo {
45
50
  readonly name: string;
46
51
  readonly models: ReadonlyArray<ModelDescriptor>;
52
+ /** 'oauth' when the provider declares an oauth login on its plugin
53
+ * definition, 'api-key' otherwise. Defaults to 'api-key' for
54
+ * providers that don't declare. */
55
+ readonly authKind: ProviderAuthKind;
56
+ /** True when the provider's plugin can list its models live (e.g.
57
+ * via /v1/models). Lets the desktop's model picker show a
58
+ * "Fetch live" affordance only where it makes sense. */
59
+ readonly supportsLiveModelDiscovery: boolean;
47
60
  }
48
61
 
49
62
  /** Serializable tool metadata for status lines / slash menus / compact rendering. */
@@ -83,6 +96,13 @@ export interface SessionInfo {
83
96
  readonly activeProvider: string | null;
84
97
  readonly providers: ReadonlyArray<ProviderInfo>;
85
98
  readonly activeMode: string | null;
99
+ /**
100
+ * Presentation hint for the active mode, when it advertises one (see
101
+ * {@link ModeBadge}). Lets channels render a persistent accent badge for
102
+ * autonomous modes like goal mode. `null` when no mode is active or the
103
+ * active mode declares no badge.
104
+ */
105
+ readonly activeModeBadge: ModeBadge | null;
86
106
  readonly modes: ReadonlyArray<string>;
87
107
  readonly tools: ReadonlyArray<ToolInfo>;
88
108
  readonly skills: ReadonlyArray<SkillInfo>;
@@ -92,6 +112,69 @@ export interface SessionInfo {
92
112
  readonly hasTranscriber: boolean;
93
113
  /** Name of the active transcriber, or null. Lets a thin client proxy STT. */
94
114
  readonly activeTranscriber: string | null;
115
+ /** Whether any text-to-speech backend is registered. */
116
+ readonly hasSynthesizer: boolean;
117
+ /** Name of the active synthesizer, or null. Lets a thin client proxy TTS
118
+ * (the desktop routes "Read aloud" through it; null → OS voice fallback). */
119
+ readonly activeSynthesizer: string | null;
120
+ }
121
+
122
+ /**
123
+ * Resolves a provider's stored credentials (vault tokens / API keys) into the
124
+ * config object `providers.setActive` needs. The host installs one on a local
125
+ * Session at boot; it is undefined across a `RemoteSession` transport (a closure
126
+ * can't cross the wire — the runner side resolves credentials there instead).
127
+ */
128
+ export type CredentialResolver = (providerName: string) => Promise<Record<string, unknown>>;
129
+
130
+ /** One server's status in {@link McpAdminView.listServers}. */
131
+ export interface McpServerStatusView {
132
+ readonly name: string;
133
+ readonly enabled: boolean;
134
+ readonly connected: boolean;
135
+ }
136
+
137
+ /**
138
+ * The slice of the MCP admin API a channel needs to drive the MCP picker and
139
+ * status line. Present on a local Session when the MCP admin plugin is wired;
140
+ * a `RemoteSession` leaves {@link SessionLike.mcpAdmin} undefined and the UI
141
+ * degrades gracefully.
142
+ */
143
+ export interface McpAdminView {
144
+ enableAndAttach(name: string): Promise<{ toolNames: ReadonlyArray<string> } | null>;
145
+ detach(name: string): Promise<boolean>;
146
+ listServers(): Promise<ReadonlyArray<McpServerStatusView>>;
147
+ }
148
+
149
+ /** One workflow's summary for the `/workflows` modal. */
150
+ export interface WorkflowSummaryView {
151
+ readonly name: string;
152
+ readonly description: string;
153
+ readonly enabled: boolean;
154
+ readonly scope: string;
155
+ readonly steps: number;
156
+ /** Human-readable trigger summary, e.g. `cron(0 8 * * *)` or `on-demand`. */
157
+ readonly triggers: string;
158
+ }
159
+
160
+ /** Result of running a workflow from the modal. */
161
+ export interface WorkflowRunView {
162
+ readonly ok: boolean;
163
+ readonly output: string;
164
+ readonly error?: string;
165
+ readonly steps: ReadonlyArray<{ readonly id: string; readonly status: string; readonly error?: string }>;
166
+ }
167
+
168
+ /**
169
+ * The slice of the workflows API a channel needs to drive the `/workflows`
170
+ * modal (list, enable/disable toggle, run). Present on a local Session when
171
+ * `@moxxy/plugin-workflows` is wired; a `RemoteSession` leaves
172
+ * {@link SessionLike.workflows} undefined and the UI degrades gracefully.
173
+ */
174
+ export interface WorkflowsView {
175
+ list(): Promise<ReadonlyArray<WorkflowSummaryView>>;
176
+ setEnabled(name: string, enabled: boolean): Promise<void>;
177
+ run(name: string): Promise<WorkflowRunView>;
95
178
  }
96
179
 
97
180
  /**
@@ -115,4 +198,19 @@ export interface SessionLike {
115
198
  /** Wire-friendly registry snapshot for rendering. */
116
199
  getInfo(): SessionInfo;
117
200
  close(reason?: string): Promise<void>;
201
+
202
+ /**
203
+ * Live runtime capabilities present only on an in-process Session; a
204
+ * `RemoteSession` thin client leaves them undefined, so callers MUST guard.
205
+ * For plain display prefer the serializable {@link getInfo} snapshot — these
206
+ * are for the mutate/guard paths a channel drives (provider switch, MCP picker).
207
+ */
208
+ /** Providers whose credentials resolved this session (live, mutable). */
209
+ readyProviders?: Set<string>;
210
+ /** Re-resolves a provider's credentials before `providers.setActive`. */
211
+ credentialResolver?: CredentialResolver;
212
+ /** MCP admin slice backing the MCP picker / status line. */
213
+ mcpAdmin?: McpAdminView;
214
+ /** Workflows slice backing the `/workflows` modal. */
215
+ workflows?: WorkflowsView;
118
216
  }
@@ -0,0 +1,42 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createStuckLoopDetector } from './mode-helpers.js';
3
+
4
+ describe('createStuckLoopDetector', () => {
5
+ it('trips on exact-input repeats at repeatThreshold', () => {
6
+ const d = createStuckLoopDetector(); // repeatThreshold 3
7
+ const input = { x: 1 };
8
+ expect(d.record('Read', input).stuck).toBe(false);
9
+ expect(d.record('Read', input).stuck).toBe(false);
10
+ const sig = d.record('Read', input);
11
+ expect(sig).toMatchObject({ stuck: true, count: 3, kind: 'exact' });
12
+ });
13
+
14
+ it('trips on same-target near-dups even when volatile args vary', () => {
15
+ const d = createStuckLoopDetector(); // nearThreshold 5
16
+ const url = 'https://example.com/big';
17
+ // Same url, different maxBytes each time — exact check never fires.
18
+ for (let i = 0; i < 4; i++) {
19
+ expect(d.record('web_fetch', { url, maxBytes: 1000 * (i + 1) }).stuck).toBe(false);
20
+ }
21
+ const sig = d.record('web_fetch', { url, maxBytes: 99_000 });
22
+ expect(sig).toMatchObject({ stuck: true, kind: 'near' });
23
+ expect(sig.count).toBeGreaterThanOrEqual(5);
24
+ });
25
+
26
+ it('does NOT trip on distinct targets (legit multi-source fetching)', () => {
27
+ const d = createStuckLoopDetector();
28
+ for (let i = 0; i < 7; i++) {
29
+ const sig = d.record('web_fetch', { url: `https://example.com/page-${i}`, maxBytes: 8000 });
30
+ expect(sig.stuck).toBe(false);
31
+ }
32
+ });
33
+
34
+ it('ignores near-dups for tools with no identity arg', () => {
35
+ const d = createStuckLoopDetector();
36
+ // No url/path/command field — near tracking is skipped; only exact applies.
37
+ for (let i = 0; i < 6; i++) {
38
+ const sig = d.record('think', { note: `step ${i}` });
39
+ expect(sig.stuck).toBe(false);
40
+ }
41
+ });
42
+ });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Synthesizers convert text into spoken audio (text-to-speech). They are the
3
+ * symmetric counterpart to {@link Transcriber} (speech-to-text): a separate,
4
+ * swappable capability so a user can pair any text provider with a dedicated
5
+ * TTS backend (the OS voice, ElevenLabs, OpenAI, a local engine, …).
6
+ *
7
+ * Plugins register a `SynthesizerDef` via `PluginSpec.synthesizers`. The core
8
+ * `SynthesizerRegistry` holds them; surfaces that read aloud (the desktop's
9
+ * "Read aloud" button, a future voice channel) call
10
+ * `session.synthesizers.getActive()` (or `tryGetActive()`) to turn text into
11
+ * audio. There is at most one *active* synthesizer at a time; when none is
12
+ * active the caller degrades gracefully (the desktop falls back to the
13
+ * browser/OS `speechSynthesis`).
14
+ *
15
+ * The user swaps the active synthesizer by asking the agent ("use ElevenLabs
16
+ * for read-aloud") — there is no settings UI. The agent activates a registered
17
+ * synthesizer (a plugin it authored/installed self-activates in `onInit`, or it
18
+ * calls a set-active tool); switching back to the OS voice deactivates it.
19
+ */
20
+
21
+ export interface SynthesizeOptions {
22
+ /** Preferred voice id/name, when the backend supports selection. */
23
+ readonly voice?: string;
24
+ /** BCP-47 language hint (e.g. `en`, `pl`). */
25
+ readonly language?: string;
26
+ /** Speaking rate multiplier (1.0 = normal), when supported. */
27
+ readonly rate?: number;
28
+ /** Cancellation signal — callers propagate a stop/abort here. */
29
+ readonly signal?: AbortSignal;
30
+ }
31
+
32
+ export interface SynthesisResult {
33
+ /** Encoded audio bytes ready to play (e.g. an mp3/wav/ogg payload). */
34
+ readonly audio: Uint8Array;
35
+ /** MIME type of {@link audio}, e.g. `audio/mpeg`, `audio/wav`, `audio/ogg`. */
36
+ readonly mimeType: string;
37
+ }
38
+
39
+ export interface Synthesizer {
40
+ /** Short stable name, e.g. `elevenlabs`. */
41
+ readonly name: string;
42
+ synthesize(text: string, opts?: SynthesizeOptions): Promise<SynthesisResult>;
43
+ }
44
+
45
+ /**
46
+ * Context handed to {@link SynthesizerDef.create} when the registry activates a
47
+ * synthesizer. `getSecret` reads a vault secret (the API key) the same way a
48
+ * tool handler does via `ctx.getSecret` — so an authored TTS plugin never has
49
+ * to touch `process.env`, and the key never enters the model's context.
50
+ */
51
+ export interface SynthesizerCreateContext {
52
+ /** Per-synthesizer config (e.g. from `session.synthesizers.setActive(name, config)`). */
53
+ readonly config: Record<string, unknown>;
54
+ /** Read a named vault secret, or null if unset / no vault is wired. */
55
+ readonly getSecret?: (name: string) => Promise<string | null>;
56
+ }
57
+
58
+ /**
59
+ * Plugin-side definition. Mirrors `TranscriberDef`: a `create(ctx)` factory the
60
+ * registry calls when this synthesizer is activated.
61
+ */
62
+ export interface SynthesizerDef {
63
+ readonly name: string;
64
+ /** Optional human-readable label for UI surfaces. */
65
+ readonly displayName?: string;
66
+ create(ctx: SynthesizerCreateContext): Synthesizer;
67
+ }
package/src/tool.ts CHANGED
@@ -127,6 +127,19 @@ export interface ToolContext {
127
127
  * `caps.subprocess` + optional `caps.commands` allowlist.
128
128
  */
129
129
  readonly exec?: BrokeredExec;
130
+ /**
131
+ * Read a named secret from the host's secret store (the vault) at call
132
+ * time. Present when the session is wired with a vault-backed resolver
133
+ * (the CLI/runner does this). Returns the plaintext value, or `null` if
134
+ * no such secret exists.
135
+ *
136
+ * This is the blessed way for a tool/plugin to consume an API key or
137
+ * token: the plaintext only ever reaches the handler that asks for it —
138
+ * it is never placed in the model's context or in `process.env`. Store
139
+ * the secret once via `/vault set NAME …` (or the desktop Secrets UI),
140
+ * then read it here, e.g. `const key = await ctx.getSecret('ELEVENLABS_API_KEY')`.
141
+ */
142
+ readonly getSecret?: (name: string) => Promise<string | null>;
130
143
  }
131
144
 
132
145
  /**
package/src/voice.ts ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Voice / transcription helpers shared across surfaces.
3
+ *
4
+ * The TUI's voice-input infrastructure used to inline the same logic
5
+ * with a `Codex`-specific name baked in. Pulled out here as
6
+ * *agnostic* helpers that take a transcriber name as input, so the
7
+ * desktop, TUI, and any future channel can mirror the same flow:
8
+ *
9
+ * - Is the session ready to transcribe? Check via the requirements
10
+ * API for a named transcriber. (`checkTranscriberReady`)
11
+ * - Activate any registered transcriber lazily. Returns the active
12
+ * transcriber instance. (`resolveTranscriber`)
13
+ * - "Just give me whatever works" — try a list of candidates in
14
+ * order, or fall back to the first registered one. (`pickFirstAvailableTranscriber`)
15
+ */
16
+
17
+ import type { ClientSession } from './client-session.js';
18
+ import type {
19
+ MoxxyRequirement,
20
+ RequirementCheck,
21
+ RequirementIssue,
22
+ } from './requirements.js';
23
+ import type { Transcriber } from './transcriber.js';
24
+
25
+ /** Probe whether a *named* transcriber is ready: registered, with any
26
+ * declared upstream requirements satisfied. The optional `requires`
27
+ * list lets channels gate on additional provider / auth runtimes
28
+ * (the Codex transcriber e.g. depends on the `openai-codex` provider
29
+ * + its OAuth runtime). */
30
+ export function checkTranscriberReady(
31
+ session: ClientSession,
32
+ transcriberName: string,
33
+ requires: ReadonlyArray<MoxxyRequirement> = [],
34
+ ): RequirementCheck {
35
+ const baseline: ReadonlyArray<MoxxyRequirement> = [
36
+ { kind: 'transcriber', name: transcriberName },
37
+ ...requires,
38
+ ];
39
+ const check = session.requirements.check(baseline);
40
+ const activeName = session.transcribers.getActiveName();
41
+ if (!activeName || activeName === transcriberName) return check;
42
+
43
+ const conflict: RequirementIssue = {
44
+ requirement: {
45
+ kind: 'transcriber',
46
+ name: transcriberName,
47
+ state: 'active',
48
+ hint: `Switch active transcriber to ${transcriberName}.`,
49
+ },
50
+ code: 'inactive',
51
+ message: `Required active transcriber ${transcriberName}; active is ${activeName}`,
52
+ hint: `Switch active transcriber to ${transcriberName}.`,
53
+ };
54
+ return { ready: false, issues: [conflict, ...check.issues] };
55
+ }
56
+
57
+ /** Activate a transcriber by name, lazily. Returns the active instance
58
+ * ready to `.transcribe(...)`. Throws if no such transcriber is
59
+ * registered, or a *different* one is already active. */
60
+ export function resolveTranscriber(
61
+ session: ClientSession,
62
+ transcriberName: string,
63
+ ): Transcriber {
64
+ const activeName = session.transcribers.getActiveName();
65
+ if (activeName && activeName !== transcriberName) {
66
+ throw new Error(
67
+ `Another transcriber is already active: ${activeName}.`,
68
+ );
69
+ }
70
+ if (activeName === transcriberName) return session.transcribers.getActive();
71
+ if (session.transcribers.has(transcriberName)) {
72
+ return session.transcribers.setActive(transcriberName);
73
+ }
74
+ throw new Error(
75
+ `No transcriber registered as ${transcriberName}. Configure one via your moxxy plugins.`,
76
+ );
77
+ }
78
+
79
+ /** "Just pick a transcriber that works."
80
+ *
81
+ * Tries each name in `candidates` in order — first one that can be
82
+ * activated wins. Returns null if none can be activated, so callers
83
+ * can degrade gracefully (hide their mic button, show a "no voice
84
+ * configured" tip, …) instead of throwing. */
85
+ export function pickFirstAvailableTranscriber(
86
+ session: ClientSession,
87
+ candidates: ReadonlyArray<string>,
88
+ ): Transcriber | null {
89
+ // If something's already active, just hand that back — never fight
90
+ // a user-chosen activation.
91
+ const existing = session.transcribers.tryGetActive();
92
+ if (existing) return existing;
93
+ for (const name of candidates) {
94
+ try {
95
+ return resolveTranscriber(session, name);
96
+ } catch {
97
+ // Wrong-active errors don't apply here (we just returned early),
98
+ // so any throw is "this candidate isn't registered" — keep
99
+ // trying.
100
+ }
101
+ }
102
+ return null;
103
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Workflows — saved, parameterized, schedulable/event-triggered DAGs whose
3
+ * steps run a skill, a free-form prompt, a tool, or a nested workflow, piping
4
+ * each step's output into the next. A workflow is an *artifact* (authored like
5
+ * a skill, discovered from disk); the strategy that *executes* it is a
6
+ * swappable block — {@link WorkflowExecutorDef} — registered into the
7
+ * `WorkflowExecutorRegistry` and selected by name, mirroring modes/compactors.
8
+ *
9
+ * These are the shared structural types. The zod schema that validates
10
+ * on-disk YAML lives in `@moxxy/plugin-workflows`; its parsed output is
11
+ * assignable to {@link Workflow}.
12
+ */
13
+
14
+ import type { Skill } from './skill.js';
15
+ import type { SubagentSpawner } from './subagent.js';
16
+
17
+ /** What fires a workflow. Omit `on` entirely for an on-demand-only workflow. */
18
+ export interface WorkflowTrigger {
19
+ /** Cron / one-shot time trigger, dispatched by `@moxxy/plugin-scheduler`. */
20
+ readonly schedule?: {
21
+ readonly cron?: string;
22
+ readonly runAt?: number | string;
23
+ readonly timeZone?: string;
24
+ };
25
+ /** Run when the named workflow(s) complete successfully (EventLog-driven). */
26
+ readonly afterWorkflow?: string | ReadonlyArray<string>;
27
+ /** Run when files matching the glob(s) under cwd change (fs.watch-driven). */
28
+ readonly fileChanged?: string | ReadonlyArray<string>;
29
+ /** Named webhook provider whose delivery fires this workflow. */
30
+ readonly webhook?: string;
31
+ }
32
+
33
+ /** How a failed step is handled: abort the workflow, skip past it, or retry. */
34
+ export type WorkflowStepErrorMode = 'fail' | 'continue' | 'retry';
35
+
36
+ /**
37
+ * One node in the DAG. Exactly one *action* key is set
38
+ * (`skill` | `prompt` | `tool` | `workflow`). `input` is the templated prompt
39
+ * for skill/prompt actions; `args` are the templated arguments for
40
+ * tool/workflow actions. `needs` are the upstream step ids this step depends on.
41
+ */
42
+ export interface WorkflowStep {
43
+ readonly id: string;
44
+ readonly skill?: string;
45
+ readonly prompt?: string;
46
+ readonly tool?: string;
47
+ readonly workflow?: string;
48
+ readonly input?: string;
49
+ readonly args?: Record<string, unknown>;
50
+ readonly needs: ReadonlyArray<string>;
51
+ /** Condition DSL; when it evaluates false the step is skipped. */
52
+ readonly when?: string;
53
+ readonly onError: WorkflowStepErrorMode;
54
+ readonly retries: number;
55
+ readonly label?: string;
56
+ }
57
+
58
+ export interface WorkflowInputSpec {
59
+ readonly default?: unknown;
60
+ readonly description?: string;
61
+ }
62
+
63
+ export interface WorkflowDelivery {
64
+ /** Soft hint for delivery target — e.g. "telegram", "inbox". */
65
+ readonly channel?: string;
66
+ /** Also drop the final output into `~/.moxxy/inbox/`. Default true. */
67
+ readonly inbox: boolean;
68
+ }
69
+
70
+ export interface Workflow {
71
+ readonly name: string;
72
+ readonly description: string;
73
+ readonly version: number;
74
+ /**
75
+ * When false the workflow is inert: triggers (schedule/event) never fire it
76
+ * and it is excluded from auto-runs, but it stays listable and can still be
77
+ * run explicitly. Toggled from the `/workflows` command.
78
+ */
79
+ readonly enabled: boolean;
80
+ readonly inputs: Record<string, WorkflowInputSpec>;
81
+ readonly on?: WorkflowTrigger;
82
+ readonly delivery?: WorkflowDelivery;
83
+ /** Max steps to run concurrently in one ready-set round. */
84
+ readonly concurrency: number;
85
+ readonly steps: ReadonlyArray<WorkflowStep>;
86
+ }
87
+
88
+ /** Minimal tool surface a step needs — structurally a subset of `ToolRegistry`. */
89
+ export interface WorkflowToolRunner {
90
+ get(name: string): unknown | undefined;
91
+ execute(name: string, input: unknown, signal: AbortSignal): Promise<unknown>;
92
+ }
93
+
94
+ /** Look up sibling artifacts by name during a run. */
95
+ export interface WorkflowLookup {
96
+ skill(name: string): Skill | undefined;
97
+ workflow(name: string): Workflow | undefined;
98
+ }
99
+
100
+ /** Lifecycle subtypes an executor emits as `plugin_event`s (mirrors plan_*). */
101
+ export type WorkflowEventSubtype =
102
+ | 'workflow_started'
103
+ | 'workflow_step_started'
104
+ | 'workflow_step_completed'
105
+ | 'workflow_step_skipped'
106
+ | 'workflow_step_failed'
107
+ | 'workflow_completed'
108
+ | 'workflow_failed';
109
+
110
+ /**
111
+ * Everything an executor needs to run a workflow, supplied by the caller.
112
+ * The in-turn `workflow_run` tool wires `spawner` from `ctx.subagents`; the
113
+ * autonomous runner builds one from an isolated session. Kept free of core
114
+ * imports so the executor stays in a plugin.
115
+ */
116
+ export interface WorkflowRunDeps {
117
+ readonly spawner: SubagentSpawner;
118
+ readonly tools: WorkflowToolRunner;
119
+ readonly lookup: WorkflowLookup;
120
+ readonly signal: AbortSignal;
121
+ /** Resolved input values (defaults already applied) for this run. */
122
+ readonly inputs?: Record<string, unknown>;
123
+ /** Free-form description of what fired the run (for `{{ trigger }}`). */
124
+ readonly trigger?: string;
125
+ /** Wall-clock source. Injected so tests are deterministic. */
126
+ readonly now?: () => number;
127
+ /** Emit a workflow lifecycle event. No-op when omitted. */
128
+ readonly emit?: (subtype: WorkflowEventSubtype, payload: unknown) => void | Promise<void>;
129
+ readonly logger?: {
130
+ warn?(msg: string, meta?: Record<string, unknown>): void;
131
+ info?(msg: string, meta?: Record<string, unknown>): void;
132
+ };
133
+ /** Nested-workflow recursion depth; executors guard against runaway nesting. */
134
+ readonly depth?: number;
135
+ }
136
+
137
+ export type WorkflowStepStatus = 'completed' | 'skipped' | 'failed';
138
+
139
+ export interface WorkflowStepResult {
140
+ readonly id: string;
141
+ readonly status: WorkflowStepStatus;
142
+ readonly output: string;
143
+ readonly error?: string;
144
+ readonly startedAt: number;
145
+ readonly endedAt: number;
146
+ }
147
+
148
+ export interface WorkflowRunResult {
149
+ readonly ok: boolean;
150
+ readonly steps: ReadonlyArray<WorkflowStepResult>;
151
+ /** Output of the terminal (sink) step(s) — what delivery sends. */
152
+ readonly output: string;
153
+ readonly error?: string;
154
+ }
155
+
156
+ /**
157
+ * A swappable workflow-execution strategy. v1 ships one (`dag`); a plugin can
158
+ * register alternatives (parallel-heavy, dry-run, …) and the active one is
159
+ * selected by name via `session.workflowExecutors.setActive(name)`.
160
+ */
161
+ export interface WorkflowExecutorDef {
162
+ readonly name: string;
163
+ readonly description?: string;
164
+ run(workflow: Workflow, deps: WorkflowRunDeps): Promise<WorkflowRunResult>;
165
+ }
@@ -1,23 +0,0 @@
1
- export declare const COMMAND_SESSION_ACTION_SUBTYPE: "command.session_action";
2
- export declare const COMMAND_STATE_CHANGED_SUBTYPE: "command.state_changed";
3
- export type CommandOriginChannel = 'tui' | 'office' | (string & {});
4
- export type CommandTarget = 'session';
5
- export interface CommandSyncBasePayload {
6
- readonly command: string;
7
- readonly target: CommandTarget;
8
- readonly origin_channel: CommandOriginChannel;
9
- readonly origin_id: string;
10
- readonly notice?: string;
11
- }
12
- export interface CommandSessionActionPayload extends CommandSyncBasePayload {
13
- readonly action: 'new';
14
- }
15
- export interface CommandStateChangedPayload extends CommandSyncBasePayload {
16
- readonly action: 'model_changed' | 'loop_changed';
17
- readonly provider?: string;
18
- readonly model?: string;
19
- readonly loop?: string;
20
- }
21
- export declare function isCommandSessionActionPayload(value: unknown): value is CommandSessionActionPayload;
22
- export declare function isCommandStateChangedPayload(value: unknown): value is CommandStateChangedPayload;
23
- //# sourceMappingURL=command-sync.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"command-sync.d.ts","sourceRoot":"","sources":["../src/command-sync.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,8BAA8B,EAAG,wBAAiC,CAAC;AAChF,eAAO,MAAM,6BAA6B,EAAG,uBAAgC,CAAC;AAE9E,MAAM,MAAM,oBAAoB,GAAG,KAAK,GAAG,QAAQ,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AACpE,MAAM,MAAM,aAAa,GAAG,SAAS,CAAC;AAEtC,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,cAAc,EAAE,oBAAoB,CAAC;IAC9C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IACzE,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;CACxB;AAED,MAAM,WAAW,0BAA2B,SAAQ,sBAAsB;IACxE,QAAQ,CAAC,MAAM,EAAE,eAAe,GAAG,cAAc,CAAC;IAClD,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AAqBD,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,2BAA2B,CAGtC;AAED,wBAAgB,4BAA4B,CAC1C,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,0BAA0B,CAcrC"}
@@ -1,36 +0,0 @@
1
- export const COMMAND_SESSION_ACTION_SUBTYPE = 'command.session_action';
2
- export const COMMAND_STATE_CHANGED_SUBTYPE = 'command.state_changed';
3
- function asRecord(value) {
4
- return value && typeof value === 'object' && !Array.isArray(value)
5
- ? value
6
- : null;
7
- }
8
- function hasBasePayload(value) {
9
- return (typeof value.command === 'string' &&
10
- value.command.trim().length > 0 &&
11
- value.target === 'session' &&
12
- typeof value.origin_channel === 'string' &&
13
- value.origin_channel.trim().length > 0 &&
14
- typeof value.origin_id === 'string' &&
15
- value.origin_id.trim().length > 0 &&
16
- (value.notice === undefined || typeof value.notice === 'string'));
17
- }
18
- export function isCommandSessionActionPayload(value) {
19
- const record = asRecord(value);
20
- return Boolean(record && hasBasePayload(record) && record.action === 'new');
21
- }
22
- export function isCommandStateChangedPayload(value) {
23
- const record = asRecord(value);
24
- if (!record || !hasBasePayload(record))
25
- return false;
26
- if (record.action === 'model_changed') {
27
- return ((record.provider === undefined || typeof record.provider === 'string') &&
28
- typeof record.model === 'string' &&
29
- record.model.trim().length > 0);
30
- }
31
- if (record.action === 'loop_changed') {
32
- return typeof record.loop === 'string' && record.loop.trim().length > 0;
33
- }
34
- return false;
35
- }
36
- //# sourceMappingURL=command-sync.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"command-sync.js","sourceRoot":"","sources":["../src/command-sync.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,8BAA8B,GAAG,wBAAiC,CAAC;AAChF,MAAM,CAAC,MAAM,6BAA6B,GAAG,uBAAgC,CAAC;AAwB9E,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAChE,CAAC,CAAC,KAAgC;QAClC,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,SAAS,cAAc,CAAC,KAA8B;IACpD,OAAO,CACL,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;QACjC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QAC/B,KAAK,CAAC,MAAM,KAAK,SAAS;QAC1B,OAAO,KAAK,CAAC,cAAc,KAAK,QAAQ;QACxC,KAAK,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QACtC,OAAO,KAAK,CAAC,SAAS,KAAK,QAAQ;QACnC,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC;QACjC,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC,CACjE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,KAAc;IAEd,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/B,OAAO,OAAO,CAAC,MAAM,IAAI,cAAc,CAAC,MAAM,CAAC,IAAI,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,KAAc;IAEd,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC/B,IAAI,CAAC,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IACrD,IAAI,MAAM,CAAC,MAAM,KAAK,eAAe,EAAE,CAAC;QACtC,OAAO,CACL,CAAC,MAAM,CAAC,QAAQ,KAAK,SAAS,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC;YACtE,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ;YAChC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAC/B,CAAC;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,cAAc,EAAE,CAAC;QACrC,OAAO,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -1,68 +0,0 @@
1
- import type { ProviderMessage } from './provider.js';
2
- import type { LoopContext } from './loop.js';
3
- import type { StopReason } from './provider-utils.js';
4
- import type { Skill } from './skill.js';
5
- /**
6
- * Shared bits used by every loop strategy: a typed tool-use struct and a
7
- * common stream-collection helper that runs `onBeforeProviderCall` hooks
8
- * and reduces a provider stream down to `{text, toolUses, stopReason}`.
9
- *
10
- * Lives in core (not in each loop package) so a new loop strategy stays
11
- * consistent — and so behavioral fixes here propagate. Previously
12
- * loop-plan-execute had its own copy that skipped the hook (audit bug).
13
- */
14
- export interface CollectedToolUse {
15
- readonly id: string;
16
- readonly name: string;
17
- readonly input: unknown;
18
- }
19
- /**
20
- * Compose a model-facing system prompt that includes any base prompt
21
- * plus a COMPACT skill index (name + description + triggers only).
22
- *
23
- * Lazy-loading design: the body is intentionally NOT inlined. The model
24
- * matches user intent against the description/triggers, then calls the
25
- * `load_skill` tool to fetch the body of the skill it picked. This keeps
26
- * the system prompt small even with many skills installed and avoids
27
- * paying for skill bodies the model never actually follows.
28
- */
29
- export declare function buildSystemPromptWithSkills(baseSystemPrompt: string | undefined, skills: ReadonlyArray<Skill>): string | undefined;
30
- export interface ProjectMessagesOptions {
31
- /** Optional system prompt; emitted as the first message when set. */
32
- readonly systemPrompt?: string;
33
- /** Optional trailing user message — useful for plan-execute's "Focus on this step now: X". */
34
- readonly trailingUserText?: string;
35
- }
36
- /**
37
- * Project the session's event log to a flat list of ProviderMessages
38
- * suitable for handing to `provider.stream`. Used by every loop strategy.
39
- *
40
- * Handles user_prompt, assistant_message, tool_call_requested (grouped
41
- * into a single assistant message of tool_use blocks), and tool_result.
42
- * Other event types are passed through as a no-op.
43
- *
44
- * Note: this is the minimal projection used by loop strategies. Core's
45
- * `selectMessages` is a richer variant that also honors compaction events
46
- * and attachments; the simpler form here lives in the SDK so loop plugins
47
- * stay independent of core.
48
- */
49
- export declare function projectMessagesFromLog(ctx: Pick<LoopContext, 'log'>, opts?: ProjectMessagesOptions): ProviderMessage[];
50
- export interface StreamResult {
51
- readonly text: string;
52
- readonly toolUses: ReadonlyArray<CollectedToolUse>;
53
- readonly stopReason: StopReason;
54
- readonly error: {
55
- readonly message: string;
56
- readonly retryable: boolean;
57
- } | null;
58
- }
59
- /**
60
- * Pulls a provider stream, emits `assistant_chunk` events for text deltas,
61
- * collects tool_use blocks, and returns the final `{text, toolUses, stopReason}`.
62
- * Runs `onBeforeProviderCall` lifecycle hooks before the call.
63
- */
64
- export declare function collectProviderStream(ctx: LoopContext, messages: ReadonlyArray<ProviderMessage>, opts?: {
65
- iteration?: number;
66
- includeTools?: boolean;
67
- }): Promise<StreamResult>;
68
- //# sourceMappingURL=loop-helpers.d.ts.map