@moxxy/sdk 0.1.0 → 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 (79) hide show
  1. package/README.md +239 -0
  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/session-like.d.ts +85 -1
  48. package/dist/session-like.d.ts.map +1 -1
  49. package/dist/voice.d.ts +36 -0
  50. package/dist/voice.d.ts.map +1 -0
  51. package/dist/voice.js +82 -0
  52. package/dist/voice.js.map +1 -0
  53. package/dist/workflow.d.ts +144 -0
  54. package/dist/workflow.d.ts.map +1 -0
  55. package/dist/workflow.js +14 -0
  56. package/dist/workflow.js.map +1 -0
  57. package/package.json +38 -2
  58. package/src/compactor-helpers.test.ts +41 -0
  59. package/src/compactor-helpers.ts +53 -19
  60. package/src/define.ts +10 -0
  61. package/src/embedding.ts +18 -0
  62. package/src/errors.ts +3 -0
  63. package/src/fs-utils.test.ts +61 -0
  64. package/src/fs-utils.ts +55 -0
  65. package/src/http-utils.test.ts +36 -0
  66. package/src/http-utils.ts +40 -0
  67. package/src/index.ts +58 -3
  68. package/src/mode-helpers.ts +169 -0
  69. package/src/mode.ts +8 -0
  70. package/src/mutex.test.ts +36 -0
  71. package/src/mutex.ts +31 -0
  72. package/src/plugin.ts +27 -1
  73. package/src/provider-utils.ts +9 -0
  74. package/src/resolvers.test.ts +45 -0
  75. package/src/resolvers.ts +164 -0
  76. package/src/session-like.ts +87 -1
  77. package/src/stuck-loop.test.ts +42 -0
  78. package/src/voice.ts +103 -0
  79. package/src/workflow.ts +165 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.d.ts","sourceRoot":"","sources":["../src/workflow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAErD,gFAAgF;AAChF,MAAM,WAAW,eAAe;IAC9B,6EAA6E;IAC7E,QAAQ,CAAC,Q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,QAAQ,CAAC,MAAM,EAAE,kBAAkB,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC;IAClD,mEAAmE;IACnE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;CAC5E"}
@@ -0,0 +1,14 @@
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
+ export {};
14
+ //# sourceMappingURL=workflow.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.js","sourceRoot":"","sources":["../src/workflow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG"}
package/package.json CHANGED
@@ -1,7 +1,42 @@
1
1
  {
2
2
  "name": "@moxxy/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "Typed public surface for the moxxy framework: event types, define* factories, lifecycle hook signatures.",
5
+ "keywords": [
6
+ "moxxy",
7
+ "agent",
8
+ "agents",
9
+ "agent-framework",
10
+ "ai",
11
+ "llm",
12
+ "anthropic",
13
+ "claude",
14
+ "openai",
15
+ "gpt",
16
+ "plugin",
17
+ "plugin-sdk",
18
+ "sdk",
19
+ "tools",
20
+ "tool-use",
21
+ "mcp",
22
+ "typescript",
23
+ "zero-deps"
24
+ ],
25
+ "homepage": "https://moxxy.ai",
26
+ "bugs": {
27
+ "url": "https://github.com/moxxy-ai/moxxy/issues"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/moxxy-ai/moxxy.git",
32
+ "directory": "packages/sdk"
33
+ },
34
+ "author": "Michal Makowski <michal.makowski97@gmail.com>",
35
+ "license": "MIT",
36
+ "engines": {
37
+ "node": ">=20.10.0"
38
+ },
39
+ "sideEffects": false,
5
40
  "type": "module",
6
41
  "main": "./dist/index.js",
7
42
  "types": "./dist/index.d.ts",
@@ -13,7 +48,8 @@
13
48
  },
14
49
  "files": [
15
50
  "dist",
16
- "src"
51
+ "src",
52
+ "README.md"
17
53
  ],
18
54
  "publishConfig": {
19
55
  "access": "public"
@@ -4,6 +4,7 @@ import {
4
4
  asSessionId,
5
5
  asTurnId,
6
6
  estimateContextTokens,
7
+ isContextOverflowError,
7
8
  runCompactionIfNeeded,
8
9
  type CompactorDef,
9
10
  type EmittedEvent,
@@ -129,6 +130,46 @@ describe('runCompactionIfNeeded', () => {
129
130
  expect(ctx.emitted).toHaveLength(1);
130
131
  expect(ctx.emitted[0]).toMatchObject({ type: 'error', kind: 'retryable' });
131
132
  });
133
+
134
+ it('force compacts even when shouldCompact returns false', async () => {
135
+ const compact = vi.fn(async () => ({
136
+ type: 'compaction' as const,
137
+ replacedRange: [0, 1] as [number, number],
138
+ summary: 'summary',
139
+ tokensSaved: 500,
140
+ }));
141
+ const compactor: CompactorDef = {
142
+ name: 'gated',
143
+ shouldCompact: () => false, // gate says no…
144
+ compact,
145
+ };
146
+ const ctx = makeCtx({ compactor });
147
+ const did = await runCompactionIfNeeded(ctx, { force: true }); // …but force overrides
148
+ expect(did).toBe(true);
149
+ expect(compact).toHaveBeenCalledOnce();
150
+ expect(ctx.emitted.some((e) => e.type === 'compaction')).toBe(true);
151
+ });
152
+ });
153
+
154
+ describe('isContextOverflowError', () => {
155
+ it('matches common provider context-overflow phrasings', () => {
156
+ for (const msg of [
157
+ 'input exceeds context window',
158
+ "This model's maximum context length is 200000 tokens",
159
+ 'context_length_exceeded',
160
+ 'prompt is too long: 250000 tokens > 200000 maximum',
161
+ 'Please reduce the length of the messages',
162
+ 'too many input tokens',
163
+ ]) {
164
+ expect(isContextOverflowError(msg)).toBe(true);
165
+ }
166
+ });
167
+
168
+ it('does not match unrelated errors', () => {
169
+ for (const msg of ['rate limit exceeded', 'network timeout', '500 internal server error', 'invalid api key']) {
170
+ expect(isContextOverflowError(msg)).toBe(false);
171
+ }
172
+ });
132
173
  });
133
174
 
134
175
  interface MakeCtxOpts {
@@ -96,19 +96,22 @@ function safeJsonLen(v: unknown): number {
96
96
  * compactor bug can't kill the turn. Failures emit a non-fatal
97
97
  * `error` event for observability.
98
98
  */
99
- export async function runCompactionIfNeeded(ctx: ModeContext): Promise<void> {
99
+ export async function runCompactionIfNeeded(
100
+ ctx: ModeContext,
101
+ opts: { readonly force?: boolean } = {},
102
+ ): Promise<boolean> {
100
103
  const compactor = ctx.compactor;
101
- if (!compactor) return;
104
+ if (!compactor) return false;
102
105
 
103
106
  // Resolve the active model's descriptor so we use the *real* context
104
107
  // window. `Number.MAX_SAFE_INTEGER` (the old /compact behavior) made
105
108
  // threshold-based compactors always look comfortable, even at 99%.
106
109
  const descriptor = ctx.provider.models.find((m) => m.id === ctx.model);
107
110
  const contextWindow = descriptor?.contextWindow;
108
- if (!contextWindow || contextWindow <= 0) return;
111
+ if (!contextWindow || contextWindow <= 0) return false;
109
112
 
110
113
  const events = ctx.log.slice();
111
- if (events.length === 0) return;
114
+ if (events.length === 0) return false;
112
115
 
113
116
  const budget = {
114
117
  contextWindow,
@@ -116,21 +119,27 @@ export async function runCompactionIfNeeded(ctx: ModeContext): Promise<void> {
116
119
  reserveForOutput: descriptor?.maxOutputTokens ?? 0,
117
120
  } as const;
118
121
 
119
- let shouldRun = false;
120
- try {
121
- shouldRun = compactor.shouldCompact(ctx.log, budget);
122
- } catch (err) {
123
- await ctx.emit({
124
- type: 'error',
125
- sessionId: ctx.sessionId,
126
- turnId: ctx.turnId,
127
- source: 'system',
128
- kind: 'retryable',
129
- message: `compactor.shouldCompact threw: ${err instanceof Error ? err.message : String(err)}`,
130
- });
131
- return;
122
+ // `force` skips the threshold gate — used reactively after the provider
123
+ // rejects a request for being over the context window (our estimate can
124
+ // lag the provider's real tokenizer), so we compact and retry rather than
125
+ // failing the turn.
126
+ if (!opts.force) {
127
+ let shouldRun = false;
128
+ try {
129
+ shouldRun = compactor.shouldCompact(ctx.log, budget);
130
+ } catch (err) {
131
+ await ctx.emit({
132
+ type: 'error',
133
+ sessionId: ctx.sessionId,
134
+ turnId: ctx.turnId,
135
+ source: 'system',
136
+ kind: 'retryable',
137
+ message: `compactor.shouldCompact threw: ${err instanceof Error ? err.message : String(err)}`,
138
+ });
139
+ return false;
140
+ }
141
+ if (!shouldRun) return false;
132
142
  }
133
- if (!shouldRun) return;
134
143
 
135
144
  try {
136
145
  const result = await compactor.compact(events, {
@@ -138,7 +147,7 @@ export async function runCompactionIfNeeded(ctx: ModeContext): Promise<void> {
138
147
  budget,
139
148
  signal: ctx.signal,
140
149
  });
141
- if (result.tokensSaved <= 0 || result.summary.trim().length === 0) return;
150
+ if (result.tokensSaved <= 0 || result.summary.trim().length === 0) return false;
142
151
  // `compactor.compact` declares `Omit<CompactionEvent, keyof EventBase>`,
143
152
  // but every shipped compactor (and the SDK examples) fills sessionId /
144
153
  // turnId / source. Defensive-fill from ctx so a compactor that obeyed
@@ -150,6 +159,7 @@ export async function runCompactionIfNeeded(ctx: ModeContext): Promise<void> {
150
159
  ...result,
151
160
  } as EmittedEvent;
152
161
  await ctx.emit(emittable);
162
+ return true;
153
163
  } catch (err) {
154
164
  await ctx.emit({
155
165
  type: 'error',
@@ -159,5 +169,29 @@ export async function runCompactionIfNeeded(ctx: ModeContext): Promise<void> {
159
169
  kind: 'retryable',
160
170
  message: `compactor.compact threw: ${err instanceof Error ? err.message : String(err)}`,
161
171
  });
172
+ return false;
162
173
  }
163
174
  }
175
+
176
+ /**
177
+ * Heuristic: does this provider error mean "the request was too big for the
178
+ * model's context window"? Providers phrase it many ways (OpenAI "maximum
179
+ * context length is N tokens", Anthropic "prompt is too long", the runner's
180
+ * own "input exceeds context window"), and it usually arrives as a
181
+ * non-retryable 400 — so the turn loop matches on it to compact + retry
182
+ * instead of dying.
183
+ */
184
+ const CONTEXT_OVERFLOW_PATTERNS: ReadonlyArray<RegExp> = [
185
+ /context[\s_-]{0,2}(window|length)/i,
186
+ /maximum context/i,
187
+ /context_length_exceeded/i,
188
+ /exceeds?\b[^.]{0,24}context/i,
189
+ /input[^.]{0,24}(exceeds|too long|too large|too many)/i,
190
+ /too many (input )?tokens/i,
191
+ /prompt is too long/i,
192
+ /reduce the length/i,
193
+ ];
194
+
195
+ export function isContextOverflowError(message: string): boolean {
196
+ return CONTEXT_OVERFLOW_PATTERNS.some((re) => re.test(message));
197
+ }
package/src/define.ts CHANGED
@@ -3,6 +3,7 @@ import type { CacheStrategyDef } from './cache-strategy.js';
3
3
  import type { ChannelDef } from './channel.js';
4
4
  import type { CommandDef } from './command.js';
5
5
  import type { CompactorDef } from './compactor.js';
6
+ import type { EmbedderDef } from './embedding.js';
6
7
  import type { ModeDef } from './mode.js';
7
8
  import type { PermissionRule } from './permission.js';
8
9
  import type { Plugin, PluginSpec } from './plugin.js';
@@ -13,6 +14,7 @@ import type { ToolIsolationSpec } from './isolation.js';
13
14
  import type { TranscriberDef } from './transcriber.js';
14
15
  import type { ViewRendererDef } from './view-renderer.js';
15
16
  import type { TunnelProviderDef } from './tunnel.js';
17
+ import type { WorkflowExecutorDef } from './workflow.js';
16
18
  import type { z } from 'zod';
17
19
 
18
20
  export function definePlugin(spec: PluginSpec): Plugin {
@@ -104,6 +106,10 @@ export function defineTranscriber(spec: TranscriberDef): TranscriberDef {
104
106
  return Object.freeze(spec);
105
107
  }
106
108
 
109
+ export function defineEmbedder(spec: EmbedderDef): EmbedderDef {
110
+ return Object.freeze(spec);
111
+ }
112
+
107
113
  export function defineCommand(spec: CommandDef): CommandDef {
108
114
  return Object.freeze(spec);
109
115
  }
@@ -111,3 +117,7 @@ export function defineCommand(spec: CommandDef): CommandDef {
111
117
  export function defineAgent(spec: AgentDef): AgentDef {
112
118
  return Object.freeze(spec);
113
119
  }
120
+
121
+ export function defineWorkflowExecutor(spec: WorkflowExecutorDef): WorkflowExecutorDef {
122
+ return Object.freeze(spec);
123
+ }
package/src/embedding.ts CHANGED
@@ -20,3 +20,21 @@ export interface EmbeddingProvider {
20
20
  /** Embed a batch of strings. Returns vectors in input order. */
21
21
  embed(texts: ReadonlyArray<string>): Promise<ReadonlyArray<ReadonlyArray<number>>>;
22
22
  }
23
+
24
+ /**
25
+ * Plugin-side definition of an embedder. Mirrors `TranscriberDef` / `ProviderDef`:
26
+ * a `createClient(config)` factory the `EmbedderRegistry` calls when the user
27
+ * activates this embedder by name. Plugins contribute these via
28
+ * `PluginSpec.embedders`, so a user can install a new embedder package and
29
+ * select it by config without forking the host.
30
+ *
31
+ * `createClient` MUST be cheap — defer heavy model loading (onnx, transformers,
32
+ * network clients) into the returned provider's `embed()` so that merely
33
+ * registering a discovered embedder plugin never pulls its runtime in.
34
+ */
35
+ export interface EmbedderDef {
36
+ readonly name: string;
37
+ /** Optional human-readable label for UI surfaces. */
38
+ readonly displayName?: string;
39
+ createClient(config: Record<string, unknown>): EmbeddingProvider;
40
+ }
package/src/errors.ts CHANGED
@@ -49,6 +49,9 @@ export type MoxxyErrorCode =
49
49
  | 'CONFIG_INVALID'
50
50
  | 'PLUGIN_LOAD_FAILED'
51
51
  | 'UNKNOWN_COMMAND'
52
+ // --- Tool / runtime ---
53
+ | 'TOOL_ERROR' // a tool handler failed (bad input, not-found, exec error)
54
+ | 'ABORTED' // operation cancelled — turn abort signal or timeout kill
52
55
  // --- Catch-all ---
53
56
  | 'INTERNAL';
54
57
 
@@ -0,0 +1,61 @@
1
+ import { mkdtemp, readFile, readdir, stat } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
5
+ import { moxxyHome, moxxyPath, writeFileAtomic } from './fs-utils.js';
6
+
7
+ describe('writeFileAtomic', () => {
8
+ let dir: string;
9
+ beforeEach(async () => {
10
+ dir = await mkdtemp(join(tmpdir(), 'moxxy-fs-'));
11
+ });
12
+
13
+ it('writes content and creates missing parent dirs', async () => {
14
+ const target = join(dir, 'nested', 'deep', 'file.json');
15
+ await writeFileAtomic(target, '{"a":1}');
16
+ expect(await readFile(target, 'utf8')).toBe('{"a":1}');
17
+ });
18
+
19
+ it('overwrites an existing file and leaves no temp file behind', async () => {
20
+ const target = join(dir, 'file.txt');
21
+ await writeFileAtomic(target, 'first');
22
+ await writeFileAtomic(target, 'second');
23
+ expect(await readFile(target, 'utf8')).toBe('second');
24
+ const leftovers = (await readdir(dir)).filter((n) => n.includes('.tmp'));
25
+ expect(leftovers).toEqual([]);
26
+ });
27
+
28
+ it('enforces the requested mode past umask', async () => {
29
+ const target = join(dir, 'secret.json');
30
+ await writeFileAtomic(target, 'shh', { mode: 0o600 });
31
+ const mode = (await stat(target)).mode & 0o777;
32
+ expect(mode).toBe(0o600);
33
+ });
34
+
35
+ it('writes binary data unchanged', async () => {
36
+ const target = join(dir, 'bytes.bin');
37
+ const bytes = new Uint8Array([0, 1, 2, 255]);
38
+ await writeFileAtomic(target, bytes);
39
+ const read = await readFile(target);
40
+ expect(Array.from(read)).toEqual([0, 1, 2, 255]);
41
+ });
42
+ });
43
+
44
+ describe('moxxyHome / moxxyPath', () => {
45
+ const original = process.env.MOXXY_HOME;
46
+ afterEach(() => {
47
+ if (original === undefined) delete process.env.MOXXY_HOME;
48
+ else process.env.MOXXY_HOME = original;
49
+ });
50
+
51
+ it('honors MOXXY_HOME when set', () => {
52
+ process.env.MOXXY_HOME = '/custom/moxxy';
53
+ expect(moxxyHome()).toBe('/custom/moxxy');
54
+ expect(moxxyPath('vault.json')).toBe('/custom/moxxy/vault.json');
55
+ });
56
+
57
+ it('falls back to ~/.moxxy when unset', () => {
58
+ delete process.env.MOXXY_HOME;
59
+ expect(moxxyHome().endsWith('/.moxxy')).toBe(true);
60
+ });
61
+ });
@@ -0,0 +1,55 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+
6
+ export interface WriteFileAtomicOptions {
7
+ /** Mode for the final file, e.g. `0o600` for secrets. Enforced past umask. */
8
+ readonly mode?: number;
9
+ /** Encoding when `data` is a string. Defaults to `'utf8'`. Ignored for bytes. */
10
+ readonly encoding?: BufferEncoding;
11
+ }
12
+
13
+ /**
14
+ * Crash-atomic file write: write a unique sibling temp file, then `rename` it
15
+ * over the target. POSIX `rename` is atomic on the same filesystem, so a crash
16
+ * (or full disk) mid-write leaves the previous file intact rather than a
17
+ * truncated one. The temp name carries pid + a random UUID so concurrent
18
+ * writers to the same target never collide on the temp path.
19
+ *
20
+ * This is the single home for the framework's "persist atomically" invariant —
21
+ * every file-state writer (vault, memory, permissions, sessions, the Write/Edit
22
+ * tools) should call this instead of hand-rolling tmp+rename or writing in place.
23
+ */
24
+ export async function writeFileAtomic(
25
+ target: string,
26
+ data: string | Uint8Array,
27
+ opts: WriteFileAtomicOptions = {},
28
+ ): Promise<void> {
29
+ await mkdir(dirname(target), { recursive: true });
30
+ const tmp = `${target}.${process.pid}.${randomUUID()}.tmp`;
31
+ try {
32
+ await writeFile(tmp, data, { encoding: opts.encoding ?? 'utf8' });
33
+ // chmod explicitly: writeFile's mode option is masked by umask, but a
34
+ // 0o600 secret file must be exactly 0o600 regardless of the host umask.
35
+ if (opts.mode != null) await chmod(tmp, opts.mode);
36
+ await rename(tmp, target);
37
+ } catch (err) {
38
+ await rm(tmp, { force: true }).catch(() => {});
39
+ throw err;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * The moxxy home directory: `$MOXXY_HOME` when set, else `~/.moxxy`. Single
45
+ * source of truth so the env override is honored uniformly — previously half
46
+ * the plugins inlined `~/.moxxy` and ignored `MOXXY_HOME`.
47
+ */
48
+ export function moxxyHome(): string {
49
+ return process.env.MOXXY_HOME ?? join(homedir(), '.moxxy');
50
+ }
51
+
52
+ /** Join path segments under {@link moxxyHome}. */
53
+ export function moxxyPath(...segments: string[]): string {
54
+ return join(moxxyHome(), ...segments);
55
+ }
@@ -0,0 +1,36 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { Readable } from 'node:stream';
3
+ import { describe, expect, it } from 'vitest';
4
+ import { bearerTokenMatches, readRequestBody } from './http-utils.js';
5
+
6
+ function fakeReq(body: string | Buffer): IncomingMessage {
7
+ return Readable.from([Buffer.from(body)]) as unknown as IncomingMessage;
8
+ }
9
+
10
+ describe('bearerTokenMatches', () => {
11
+ it('matches an identical token', () => {
12
+ expect(bearerTokenMatches('s3cret', 's3cret')).toBe(true);
13
+ });
14
+ it('rejects a different token of equal length', () => {
15
+ expect(bearerTokenMatches('aaaaaa', 'bbbbbb')).toBe(false);
16
+ });
17
+ it('rejects a length mismatch without throwing', () => {
18
+ expect(bearerTokenMatches('short', 'longer-token')).toBe(false);
19
+ });
20
+ it('rejects empty/missing presented tokens', () => {
21
+ expect(bearerTokenMatches(undefined, 'x')).toBe(false);
22
+ expect(bearerTokenMatches(null, 'x')).toBe(false);
23
+ expect(bearerTokenMatches('', 'x')).toBe(false);
24
+ });
25
+ });
26
+
27
+ describe('readRequestBody', () => {
28
+ it('reads the full body', async () => {
29
+ const buf = await readRequestBody(fakeReq('hello world'), 1024);
30
+ expect(buf.toString('utf8')).toBe('hello world');
31
+ });
32
+
33
+ it('rejects when the body exceeds maxBytes', async () => {
34
+ await expect(readRequestBody(fakeReq('x'.repeat(100)), 10)).rejects.toThrow(/exceeds 10 bytes/);
35
+ });
36
+ });
@@ -0,0 +1,40 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import type { IncomingMessage } from 'node:http';
3
+
4
+ /**
5
+ * Read a request body into a Buffer, rejecting (and destroying the socket) once
6
+ * `maxBytes` is exceeded. Bounds in-memory buffering so a malicious or runaway
7
+ * client can't exhaust the host's memory. Shared by every HTTP channel/listener.
8
+ */
9
+ export async function readRequestBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {
10
+ return new Promise<Buffer>((resolve, reject) => {
11
+ const chunks: Buffer[] = [];
12
+ let size = 0;
13
+ req.on('data', (chunk: Buffer) => {
14
+ size += chunk.length;
15
+ if (size > maxBytes) {
16
+ reject(new Error(`request body exceeds ${maxBytes} bytes`));
17
+ req.destroy();
18
+ return;
19
+ }
20
+ chunks.push(chunk);
21
+ });
22
+ req.on('end', () => resolve(Buffer.concat(chunks)));
23
+ req.on('error', reject);
24
+ });
25
+ }
26
+
27
+ /**
28
+ * Constant-time comparison of a presented bearer token against the expected
29
+ * value. A length mismatch returns false WITHOUT calling `timingSafeEqual`
30
+ * (which throws on unequal lengths and would leak the length); equal-length
31
+ * inputs are compared in constant time so an attacker can't recover the token
32
+ * byte-by-byte via response timing.
33
+ */
34
+ export function bearerTokenMatches(presented: string | undefined | null, expected: string): boolean {
35
+ if (!presented) return false;
36
+ const a = Buffer.from(presented);
37
+ const b = Buffer.from(expected);
38
+ if (a.length !== b.length) return false;
39
+ return timingSafeEqual(a, b);
40
+ }
package/src/index.ts CHANGED
@@ -47,6 +47,12 @@ export type {
47
47
  ToolInfo,
48
48
  SkillInfo,
49
49
  CommandInfo,
50
+ CredentialResolver,
51
+ McpAdminView,
52
+ McpServerStatusView,
53
+ WorkflowsView,
54
+ WorkflowSummaryView,
55
+ WorkflowRunView,
50
56
  } from './session-like.js';
51
57
 
52
58
  export type {
@@ -135,7 +141,22 @@ export type {
135
141
  } from './view-renderer.js';
136
142
  export { VIEW_PRIMITIVES, VIEW_COMPONENTS, DEFAULT_VIEW_TAGS } from './view-renderer.js';
137
143
  export type { TunnelProviderDef, TunnelHandle, TunnelOpenOptions } from './tunnel.js';
138
- export { isRetryableError, toFriendlyError, zodToJsonSchema, type StopReason } from './provider-utils.js';
144
+ export { isRetryableError, toFriendlyError, zodToJsonSchema, estimateTextTokens, type StopReason } from './provider-utils.js';
145
+ export { writeFileAtomic, moxxyHome, moxxyPath, type WriteFileAtomicOptions } from './fs-utils.js';
146
+ export { createMutex, type Mutex } from './mutex.js';
147
+ export { readRequestBody, bearerTokenMatches } from './http-utils.js';
148
+ export {
149
+ autoAllowResolver,
150
+ denyByDefaultResolver,
151
+ createCallbackResolver,
152
+ createAllowListResolver,
153
+ createDeferredPermissionResolver,
154
+ evaluateToolRule,
155
+ type CallbackResolverOptions,
156
+ type PermissionPromptHandler,
157
+ type DeferredPermissionResolver,
158
+ type DeferredPermissionResolverOptions,
159
+ } from './resolvers.js';
139
160
  export {
140
161
  MoxxyError,
141
162
  classifyHttpStatus,
@@ -145,18 +166,27 @@ export {
145
166
  } from './errors.js';
146
167
  export {
147
168
  collectProviderStream,
169
+ runSingleShotTurn,
148
170
  projectMessagesFromLog,
149
171
  projectMessages,
150
172
  buildSystemPromptWithSkills,
173
+ createStuckLoopDetector,
174
+ stableHash,
151
175
  type CollectedToolUse,
152
176
  type StreamResult,
153
177
  type ProjectMessagesOptions,
154
178
  type ProjectedMessages,
179
+ type StuckLoopDetector,
180
+ type StuckSignal,
155
181
  } from './mode-helpers.js';
156
182
  export { dispatchToolCall } from './tool-dispatch.js';
157
183
 
158
184
  export type { TokenBudget, CompactContext, CompactorDef } from './compactor.js';
159
- export { estimateContextTokens, runCompactionIfNeeded } from './compactor-helpers.js';
185
+ export {
186
+ estimateContextTokens,
187
+ runCompactionIfNeeded,
188
+ isContextOverflowError,
189
+ } from './compactor-helpers.js';
160
190
  export {
161
191
  runElisionIfNeeded,
162
192
  resolveElisionSettings,
@@ -192,6 +222,23 @@ export {
192
222
 
193
223
  export type { Skill, SkillDef, SkillFrontmatter, SkillScope, SkillSchedule } from './skill.js';
194
224
 
225
+ export type {
226
+ Workflow,
227
+ WorkflowStep,
228
+ WorkflowTrigger,
229
+ WorkflowStepErrorMode,
230
+ WorkflowInputSpec,
231
+ WorkflowDelivery,
232
+ WorkflowToolRunner,
233
+ WorkflowLookup,
234
+ WorkflowEventSubtype,
235
+ WorkflowRunDeps,
236
+ WorkflowStepStatus,
237
+ WorkflowStepResult,
238
+ WorkflowRunResult,
239
+ WorkflowExecutorDef,
240
+ } from './workflow.js';
241
+
195
242
  export type { AgentDef } from './agent.js';
196
243
 
197
244
  export type {
@@ -245,7 +292,7 @@ export type {
245
292
  ChannelSubcommandContext,
246
293
  ChannelCommandArgs,
247
294
  } from './channel.js';
248
- export type { EmbeddingProvider } from './embedding.js';
295
+ export type { EmbeddingProvider, EmbedderDef } from './embedding.js';
249
296
  export { CachedEmbeddingProvider } from './embedding-cache.js';
250
297
 
251
298
  export type {
@@ -281,8 +328,10 @@ export {
281
328
  definePermission,
282
329
  defineSkill,
283
330
  defineTranscriber,
331
+ defineEmbedder,
284
332
  defineCommand,
285
333
  defineAgent,
334
+ defineWorkflowExecutor,
286
335
  } from './define.js';
287
336
 
288
337
  export {
@@ -301,4 +350,10 @@ export {
301
350
  type InstallTarget,
302
351
  } from './install-hints.js';
303
352
 
353
+ export {
354
+ checkTranscriberReady,
355
+ pickFirstAvailableTranscriber,
356
+ resolveTranscriber,
357
+ } from './voice.js';
358
+
304
359
  export { z } from 'zod';