@moxxy/sdk 0.1.2 → 0.1.3

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 (96) hide show
  1. package/README.md +73 -73
  2. package/dist/compactor-helpers.d.ts +4 -1
  3. package/dist/compactor-helpers.d.ts.map +1 -1
  4. package/dist/compactor-helpers.js +50 -21
  5. package/dist/compactor-helpers.js.map +1 -1
  6. package/dist/define.d.ts +4 -0
  7. package/dist/define.d.ts.map +1 -1
  8. package/dist/define.js +6 -0
  9. package/dist/define.js.map +1 -1
  10. package/dist/embedding.d.ts +17 -0
  11. package/dist/embedding.d.ts.map +1 -1
  12. package/dist/errors.d.ts +1 -1
  13. package/dist/errors.d.ts.map +1 -1
  14. package/dist/errors.js.map +1 -1
  15. package/dist/fs-utils.d.ts +27 -0
  16. package/dist/fs-utils.d.ts.map +1 -0
  17. package/dist/fs-utils.js +44 -0
  18. package/dist/fs-utils.js.map +1 -0
  19. package/dist/http-utils.d.ts +16 -0
  20. package/dist/http-utils.d.ts.map +1 -0
  21. package/dist/http-utils.js +40 -0
  22. package/dist/http-utils.js.map +1 -0
  23. package/dist/index.d.ts +12 -6
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +9 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/mode-helpers.d.ts +58 -0
  28. package/dist/mode-helpers.d.ts.map +1 -1
  29. package/dist/mode-helpers.js +119 -0
  30. package/dist/mode-helpers.js.map +1 -1
  31. package/dist/mode.d.ts +8 -0
  32. package/dist/mode.d.ts.map +1 -1
  33. package/dist/mutex.d.ts +15 -0
  34. package/dist/mutex.d.ts.map +1 -0
  35. package/dist/mutex.js +15 -0
  36. package/dist/mutex.js.map +1 -0
  37. package/dist/plugin.d.ts +27 -1
  38. package/dist/plugin.d.ts.map +1 -1
  39. package/dist/provider-utils.d.ts +6 -0
  40. package/dist/provider-utils.d.ts.map +1 -1
  41. package/dist/provider-utils.js +8 -0
  42. package/dist/provider-utils.js.map +1 -1
  43. package/dist/resolvers.d.ts +52 -0
  44. package/dist/resolvers.d.ts.map +1 -0
  45. package/dist/resolvers.js +123 -0
  46. package/dist/resolvers.js.map +1 -0
  47. package/dist/schemas.d.ts +24 -24
  48. package/dist/session-like.d.ts +85 -1
  49. package/dist/session-like.d.ts.map +1 -1
  50. package/dist/voice.d.ts +36 -0
  51. package/dist/voice.d.ts.map +1 -0
  52. package/dist/voice.js +82 -0
  53. package/dist/voice.js.map +1 -0
  54. package/dist/workflow.d.ts +144 -0
  55. package/dist/workflow.d.ts.map +1 -0
  56. package/dist/workflow.js +14 -0
  57. package/dist/workflow.js.map +1 -0
  58. package/package.json +14 -14
  59. package/src/compactor-helpers.test.ts +41 -0
  60. package/src/compactor-helpers.ts +53 -19
  61. package/src/define.ts +10 -0
  62. package/src/embedding.ts +18 -0
  63. package/src/errors.ts +3 -0
  64. package/src/fs-utils.test.ts +61 -0
  65. package/src/fs-utils.ts +55 -0
  66. package/src/http-utils.test.ts +36 -0
  67. package/src/http-utils.ts +40 -0
  68. package/src/index.ts +58 -3
  69. package/src/mode-helpers.ts +169 -0
  70. package/src/mode.ts +8 -0
  71. package/src/mutex.test.ts +36 -0
  72. package/src/mutex.ts +31 -0
  73. package/src/plugin.ts +27 -1
  74. package/src/provider-utils.ts +9 -0
  75. package/src/resolvers.test.ts +45 -0
  76. package/src/resolvers.ts +164 -0
  77. package/src/session-like.ts +87 -1
  78. package/src/stuck-loop.test.ts +42 -0
  79. package/src/voice.ts +103 -0
  80. package/src/workflow.ts +165 -0
  81. package/dist/command-sync.d.ts +0 -23
  82. package/dist/command-sync.d.ts.map +0 -1
  83. package/dist/command-sync.js +0 -36
  84. package/dist/command-sync.js.map +0 -1
  85. package/dist/loop-helpers.d.ts +0 -68
  86. package/dist/loop-helpers.d.ts.map +0 -1
  87. package/dist/loop-helpers.js +0 -283
  88. package/dist/loop-helpers.js.map +0 -1
  89. package/dist/loop.d.ts +0 -106
  90. package/dist/loop.d.ts.map +0 -1
  91. package/dist/loop.js +0 -2
  92. package/dist/loop.js.map +0 -1
  93. package/dist/plugin-kind.d.ts +0 -10
  94. package/dist/plugin-kind.d.ts.map +0 -1
  95. package/dist/plugin-kind.js +0 -31
  96. package/dist/plugin-kind.js.map +0 -1
@@ -0,0 +1,164 @@
1
+ import type {
2
+ PendingToolCall,
3
+ PermissionContext,
4
+ PermissionDecision,
5
+ PermissionResolver,
6
+ PermissionRule,
7
+ } from './permission.js';
8
+
9
+ export const autoAllowResolver: PermissionResolver = {
10
+ name: 'auto-allow',
11
+ async check(): Promise<PermissionDecision> {
12
+ return { mode: 'allow', reason: 'auto-allow resolver (test mode)' };
13
+ },
14
+ };
15
+
16
+ export const denyByDefaultResolver: PermissionResolver = {
17
+ name: 'deny-by-default',
18
+ async check(): Promise<PermissionDecision> {
19
+ return { mode: 'deny', reason: 'No interactive resolver available in headless mode. Use --allow-tools or permissions.json.' };
20
+ },
21
+ };
22
+
23
+ export interface CallbackResolverOptions {
24
+ readonly name?: string;
25
+ readonly callback: (call: PendingToolCall, ctx: PermissionContext) => Promise<PermissionDecision>;
26
+ }
27
+
28
+ export function createCallbackResolver(opts: CallbackResolverOptions): PermissionResolver {
29
+ return {
30
+ name: opts.name ?? 'callback',
31
+ check: opts.callback,
32
+ };
33
+ }
34
+
35
+ export function createAllowListResolver(toolNames: ReadonlyArray<string>): PermissionResolver {
36
+ const allowed = new Set(toolNames);
37
+ return {
38
+ name: 'allow-list',
39
+ async check(call) {
40
+ if (allowed.has(call.name)) return { mode: 'allow_session', reason: 'allow-list' };
41
+ return { mode: 'deny', reason: `Tool '${call.name}' not in allow-list` };
42
+ },
43
+ };
44
+ }
45
+
46
+ export type PermissionPromptHandler = (
47
+ call: PendingToolCall,
48
+ ctx: PermissionContext,
49
+ ) => Promise<PermissionDecision>;
50
+
51
+ export interface DeferredPermissionResolverOptions {
52
+ readonly prompt: PermissionPromptHandler;
53
+ readonly name?: string;
54
+ readonly sessionAllows?: Set<string>;
55
+ }
56
+
57
+ export interface DeferredPermissionResolver extends PermissionResolver {
58
+ /**
59
+ * Resolve all in-flight prompts with `deny`. Call from a channel's `stop`
60
+ * so a pending permission prompt doesn't hang forever when the host UI
61
+ * unmounts (the TUI bug the audit flagged).
62
+ */
63
+ abortAll(reason?: string): void;
64
+ }
65
+
66
+ /**
67
+ * Resolver for channels that defer permission decisions to an external UI
68
+ * (Ink dialog, Telegram inline keyboard, web form). Wraps a `prompt`
69
+ * callback with:
70
+ * - sessionAllows shortcut — `allow_session` decisions skip subsequent
71
+ * prompts for the same tool name.
72
+ * - in-flight tracking — `abortAll()` resolves pending prompts with
73
+ * `deny`, so the channel can shut down cleanly without hangs.
74
+ */
75
+ export function createDeferredPermissionResolver(
76
+ opts: DeferredPermissionResolverOptions,
77
+ ): DeferredPermissionResolver {
78
+ const sessionAllows = opts.sessionAllows ?? new Set<string>();
79
+ const pending = new Set<(d: PermissionDecision) => void>();
80
+ return {
81
+ name: opts.name ?? 'deferred',
82
+ async check(call, ctx) {
83
+ if (sessionAllows.has(call.name)) {
84
+ return { mode: 'allow_session', reason: 'allow_session previously granted' };
85
+ }
86
+ const decision = await new Promise<PermissionDecision>((resolve) => {
87
+ pending.add(resolve);
88
+ opts.prompt(call, ctx).then(
89
+ (d) => {
90
+ pending.delete(resolve);
91
+ resolve(d);
92
+ },
93
+ (err) => {
94
+ pending.delete(resolve);
95
+ resolve({ mode: 'deny', reason: err instanceof Error ? err.message : String(err) });
96
+ },
97
+ );
98
+ });
99
+ // Both allow_session and allow_always should skip future prompts for
100
+ // the same tool within this resolver instance. allow_always
101
+ // additionally signals to the caller (via the decision flag) that
102
+ // the rule should be persisted to ~/.moxxy/permissions.json — but
103
+ // that persistence isn't our job; the channel does it when wiring
104
+ // up the dialog.
105
+ if (decision.mode === 'allow_session' || decision.mode === 'allow_always') {
106
+ sessionAllows.add(call.name);
107
+ }
108
+ return decision;
109
+ },
110
+ abortAll(reason = 'channel closed') {
111
+ for (const r of pending) r({ mode: 'deny', reason });
112
+ pending.clear();
113
+ },
114
+ };
115
+ }
116
+
117
+ /**
118
+ * Evaluate a tool's OWN declared {@link PermissionRule} against a call.
119
+ *
120
+ * Tools can ship a `permission` rule to express their author's policy — e.g.
121
+ * `reload_skills` / `load_tool` declare `{ action: 'allow' }` because they're
122
+ * safe, internal, idempotent operations that should never prompt. That rule
123
+ * was previously stored on the ToolDef but never consulted, so in headless
124
+ * runs (where the channel resolver denies by default) even these safe tools
125
+ * were blocked. The session resolver now consults this BETWEEN the user's
126
+ * `permissions.json` policy and the channel resolver, so:
127
+ *
128
+ * user policy (deny/allow) > tool-declared rule > channel resolver
129
+ *
130
+ * Returns a decision for a matching `allow`/`deny` rule, or `null` to defer
131
+ * (no rule, pattern didn't match, or `action: 'prompt'` — the interactive
132
+ * resolver should handle those).
133
+ */
134
+ export function evaluateToolRule(
135
+ rule: PermissionRule | undefined,
136
+ call: PendingToolCall,
137
+ ): PermissionDecision | null {
138
+ if (!rule || !toolRuleMatches(rule, call)) return null;
139
+ switch (rule.action) {
140
+ case 'allow':
141
+ return { mode: 'allow', reason: rule.reason ?? 'tool-declared allow' };
142
+ case 'deny':
143
+ return { mode: 'deny', reason: rule.reason ?? 'tool-declared deny' };
144
+ case 'prompt':
145
+ return null; // defer to the interactive resolver
146
+ }
147
+ }
148
+
149
+ function toolRuleMatches(rule: PermissionRule, call: PendingToolCall): boolean {
150
+ const p = rule.pattern;
151
+ if (!p) return true; // no pattern → applies to every call of this tool
152
+ if (p.name !== undefined && !patternMatch(p.name, call.name)) return false;
153
+ if (p.inputMatches) {
154
+ const input = (call.input ?? {}) as Record<string, unknown>;
155
+ for (const [key, matcher] of Object.entries(p.inputMatches)) {
156
+ if (!patternMatch(matcher, String(input[key] ?? ''))) return false;
157
+ }
158
+ }
159
+ return true;
160
+ }
161
+
162
+ function patternMatch(pattern: string | RegExp, candidate: string): boolean {
163
+ return pattern instanceof RegExp ? pattern.test(candidate) : pattern === candidate;
164
+ }
@@ -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. */
@@ -94,6 +107,64 @@ export interface SessionInfo {
94
107
  readonly activeTranscriber: string | null;
95
108
  }
96
109
 
110
+ /**
111
+ * Resolves a provider's stored credentials (vault tokens / API keys) into the
112
+ * config object `providers.setActive` needs. The host installs one on a local
113
+ * Session at boot; it is undefined across a `RemoteSession` transport (a closure
114
+ * can't cross the wire — the runner side resolves credentials there instead).
115
+ */
116
+ export type CredentialResolver = (providerName: string) => Promise<Record<string, unknown>>;
117
+
118
+ /** One server's status in {@link McpAdminView.listServers}. */
119
+ export interface McpServerStatusView {
120
+ readonly name: string;
121
+ readonly enabled: boolean;
122
+ readonly connected: boolean;
123
+ }
124
+
125
+ /**
126
+ * The slice of the MCP admin API a channel needs to drive the MCP picker and
127
+ * status line. Present on a local Session when the MCP admin plugin is wired;
128
+ * a `RemoteSession` leaves {@link SessionLike.mcpAdmin} undefined and the UI
129
+ * degrades gracefully.
130
+ */
131
+ export interface McpAdminView {
132
+ enableAndAttach(name: string): Promise<{ toolNames: ReadonlyArray<string> } | null>;
133
+ detach(name: string): Promise<boolean>;
134
+ listServers(): Promise<ReadonlyArray<McpServerStatusView>>;
135
+ }
136
+
137
+ /** One workflow's summary for the `/workflows` modal. */
138
+ export interface WorkflowSummaryView {
139
+ readonly name: string;
140
+ readonly description: string;
141
+ readonly enabled: boolean;
142
+ readonly scope: string;
143
+ readonly steps: number;
144
+ /** Human-readable trigger summary, e.g. `cron(0 8 * * *)` or `on-demand`. */
145
+ readonly triggers: string;
146
+ }
147
+
148
+ /** Result of running a workflow from the modal. */
149
+ export interface WorkflowRunView {
150
+ readonly ok: boolean;
151
+ readonly output: string;
152
+ readonly error?: string;
153
+ readonly steps: ReadonlyArray<{ readonly id: string; readonly status: string; readonly error?: string }>;
154
+ }
155
+
156
+ /**
157
+ * The slice of the workflows API a channel needs to drive the `/workflows`
158
+ * modal (list, enable/disable toggle, run). Present on a local Session when
159
+ * `@moxxy/plugin-workflows` is wired; a `RemoteSession` leaves
160
+ * {@link SessionLike.workflows} undefined and the UI degrades gracefully.
161
+ */
162
+ export interface WorkflowsView {
163
+ list(): Promise<ReadonlyArray<WorkflowSummaryView>>;
164
+ setEnabled(name: string, enabled: boolean): Promise<void>;
165
+ run(name: string): Promise<WorkflowRunView>;
166
+ }
167
+
97
168
  /**
98
169
  * The session surface a `Channel` depends on, decoupled from whether the
99
170
  * session runs in-process (`@moxxy/core`'s `Session`) or is a thin-client
@@ -115,4 +186,19 @@ export interface SessionLike {
115
186
  /** Wire-friendly registry snapshot for rendering. */
116
187
  getInfo(): SessionInfo;
117
188
  close(reason?: string): Promise<void>;
189
+
190
+ /**
191
+ * Live runtime capabilities present only on an in-process Session; a
192
+ * `RemoteSession` thin client leaves them undefined, so callers MUST guard.
193
+ * For plain display prefer the serializable {@link getInfo} snapshot — these
194
+ * are for the mutate/guard paths a channel drives (provider switch, MCP picker).
195
+ */
196
+ /** Providers whose credentials resolved this session (live, mutable). */
197
+ readyProviders?: Set<string>;
198
+ /** Re-resolves a provider's credentials before `providers.setActive`. */
199
+ credentialResolver?: CredentialResolver;
200
+ /** MCP admin slice backing the MCP picker / status line. */
201
+ mcpAdmin?: McpAdminView;
202
+ /** Workflows slice backing the `/workflows` modal. */
203
+ workflows?: WorkflowsView;
118
204
  }
@@ -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
+ });
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"}