@pact-harness/dsh 0.0.0-stage → 0.1.5

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.
@@ -0,0 +1,21 @@
1
+ # PACT for DeepSeek Harness.
2
+ #
3
+ # mode is one global switch:
4
+ # off - register nothing; the plugin loads inert
5
+ # shadow - run every gate, enforce only the gates named in enforceGates
6
+ # enforce - act on every verdict
7
+ #
8
+ # The default enforces exactly two gates. Both read tool_input.command, which
9
+ # DSH's bash tool supplies under the identical key, so no name or argument
10
+ # mapping sits between the gate and its input. Every other refusing gate stays
11
+ # in shadow until the M2 conformance run proves its mapping; a mapping bug in
12
+ # enforce mode would otherwise interrupt a user's work while looking like PACT
13
+ # misbehaving.
14
+ - insert:
15
+ - id: pact-dsh
16
+ name: '@pact-harness/dsh'
17
+ config:
18
+ mode: shadow
19
+ enforceGates:
20
+ - merge_guard_pre
21
+ - git_commit_check
package/index.js ADDED
@@ -0,0 +1,635 @@
1
+ /**
2
+ * PACT for DeepSeek Harness.
3
+ *
4
+ * The plugin is a bridge, not a port. It maps DSH's extension points onto
5
+ * pact.event.v1, asks the harness what PACT decided, and renders that answer
6
+ * back into DSH's own decision types. All of PACT's policy lives in the
7
+ * vendored Python; nothing in this file reimplements a gate.
8
+ *
9
+ * Failure policy. If the harness cannot be reached, shadow mode allows the
10
+ * call and logs loudly, because a broken bridge must not wedge an editor.
11
+ * Enforce mode denies instead, because silently allowing while claiming
12
+ * enforcement is the one failure the harness exists to prevent.
13
+ */
14
+
15
+ import { writeFileSync, mkdirSync, readFileSync } from 'node:fs';
16
+ import { randomUUID } from 'node:crypto';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+
20
+ import * as decisions from './lib/decisions.js';
21
+ import * as events from './lib/events.js';
22
+ import { HarnessWorker } from './lib/worker.js';
23
+
24
+ export const name = 'pact-dsh';
25
+
26
+ /** Modes the bridge accepts. */
27
+ export const MODES = Object.freeze(['off', 'shadow', 'enforce']);
28
+
29
+ /** The gates enforced when a fresh install runs in shadow mode. */
30
+ export const DEFAULT_ENFORCE_GATES = Object.freeze(['merge_guard_pre', 'git_commit_check']);
31
+
32
+ const DEFAULTS = Object.freeze({
33
+ mode: 'shadow',
34
+ enforceGates: DEFAULT_ENFORCE_GATES,
35
+ timeoutMs: 60000,
36
+ });
37
+
38
+ /** Validate and fill in a plugin config. */
39
+ export function normalizeConfig(config = {}, env = process.env) {
40
+ const merged = { ...DEFAULTS, ...config };
41
+ if (!MODES.includes(merged.mode)) {
42
+ throw new TypeError(
43
+ `pact-dsh: mode must be one of ${MODES.join(', ')}, got ${JSON.stringify(merged.mode)}`,
44
+ );
45
+ }
46
+ if (!Array.isArray(merged.enforceGates) || merged.enforceGates.some((gate) => typeof gate !== 'string')) {
47
+ throw new TypeError('pact-dsh: enforceGates must be an array of gate names');
48
+ }
49
+ if (merged.timeoutMs !== undefined && (!Number.isFinite(merged.timeoutMs) || merged.timeoutMs <= 0)) {
50
+ throw new TypeError('pact-dsh: timeoutMs must be a positive number');
51
+ }
52
+ return {
53
+ ...merged,
54
+ python: config.python ?? env.PACT_DSH_PYTHON ?? env.PACT_PYTHON ?? 'python3',
55
+ pluginRoot: config.pluginRoot ?? env.PACT_PLUGIN_ROOT ?? undefined,
56
+ // The same default the Python side resolves: a DSH install keeps its state
57
+ // under ~/.pact, separate from Claude Code's ~/.claude. A record written to
58
+ // the temporary directory instead would be invisible to pact doctor.
59
+ stateRoot: config.stateRoot ?? env.PACT_HOME ?? path.join(os.homedir(), '.pact'),
60
+ playbook: config.playbook ?? env.PACT_DSH_PLAYBOOK ?? undefined,
61
+ subagentProvider: config.subagentProvider ?? 'spawn',
62
+ socketPath: config.socketPath,
63
+ };
64
+ }
65
+
66
+ /** Build the context-message factory, preferring the host's own helper. */
67
+ export async function loadMessageFactory(logger) {
68
+ try {
69
+ const llm = await import('@deepseek-ai/dsh-llm');
70
+ if (typeof llm.createUserMessage === 'function') {
71
+ return (text) =>
72
+ llm.createUserMessage({
73
+ content: [{ type: 'text', text }],
74
+ source: { kind: 'pact-dsh' },
75
+ });
76
+ }
77
+ } catch (error) {
78
+ logger?.warn?.(`pact-dsh: using plain context messages: ${error?.message ?? error}`);
79
+ }
80
+ // The fallback is a real message, not a stub: DSH's inbox requires every
81
+ // pending message to carry a unique id, and two un-identified messages
82
+ // (which session start injects) trip "message \"undefined\" is already
83
+ // pending". The host helper is preferred because it also freezes the object.
84
+ return (text) => ({
85
+ id: randomUUID(),
86
+ role: 'user',
87
+ content: [{ type: 'text', text }],
88
+ source: { kind: 'pact-dsh' },
89
+ });
90
+ }
91
+
92
+ /** Read the compiled playbook the installer wrote, or null when absent. */
93
+ export function loadPlaybook(playbookPath) {
94
+ if (!playbookPath) return null;
95
+ const document = JSON.parse(readFileSync(playbookPath, 'utf8'));
96
+ if (!document || typeof document !== 'object' || Array.isArray(document)) {
97
+ throw new Error('playbook is not an object');
98
+ }
99
+ return document;
100
+ }
101
+
102
+ /** Read an optional service without tripping cordis's inject requirement. */
103
+ export function safeService(ctx, name) {
104
+ try {
105
+ if (typeof ctx?.get === 'function') return ctx.get(name);
106
+ return ctx?.[name];
107
+ } catch {
108
+ return undefined;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Register the orchestrator persona as a system prompt section.
114
+ *
115
+ * This is the closest DSH analogue of Claude Code's --agent: the persona joins
116
+ * the assembly at order 0, the deployment-persona convention. It is not
117
+ * editable by the user and not loaded from the workspace, because PACT's own
118
+ * threat model depends on the persona being authoritative rather than guidance.
119
+ */
120
+ export function registerPersona(ctx, settings, logger) {
121
+ if (!settings.playbook) {
122
+ logger?.info?.('pact-dsh: no playbook configured; the orchestrator persona is not registered');
123
+ return null;
124
+ }
125
+ let playbook;
126
+ try {
127
+ playbook = loadPlaybook(settings.playbook);
128
+ } catch (error) {
129
+ logger?.warn?.(`pact-dsh: cannot read the playbook: ${error?.message ?? error}`);
130
+ return null;
131
+ }
132
+ const systemPrompt = safeService(ctx, 'systemPrompt');
133
+ if (!systemPrompt || typeof systemPrompt.section !== 'function') {
134
+ logger?.warn?.('pact-dsh: system prompt service unavailable; the orchestrator persona is not registered');
135
+ return null;
136
+ }
137
+ const personas = Array.isArray(playbook.personas) ? playbook.personas : [];
138
+ const orchestrator = personas.find((persona) => persona?.name === 'pact-orchestrator');
139
+ if (!orchestrator || typeof orchestrator.body !== 'string') {
140
+ logger?.warn?.('pact-dsh: the playbook has no orchestrator persona');
141
+ return null;
142
+ }
143
+ const notes = typeof playbook.platform_notes === 'string' ? playbook.platform_notes : '';
144
+ const text = `${orchestrator.body}\n\n${notes}`.trim();
145
+ const dispose = systemPrompt.section({ name: 'pact:orchestrator', order: 0, text });
146
+ if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
147
+ ctx.effect(() => dispose);
148
+ }
149
+ logger?.info?.(`pact-dsh: registered the orchestrator persona (${text.length} bytes)`);
150
+ return text;
151
+ }
152
+
153
+ /**
154
+ * Register PACT's commands from the compiled playbook.
155
+ *
156
+ * A DSH command handler returns UI text; it does not talk to the model. The
157
+ * handler therefore injects the command body as a follow-up message, with the
158
+ * user's text substituted for the platform placeholder, and returns a short
159
+ * receipt. Returning the body as the result text instead would show it to the
160
+ * human and leave the agent with nothing to act on.
161
+ */
162
+ export function registerCommands(ctx, settings, deps, logger) {
163
+ if (!settings.playbook) {
164
+ logger?.info?.('pact-dsh: no playbook configured; commands are not registered');
165
+ return 0;
166
+ }
167
+ let playbook;
168
+ try {
169
+ playbook = loadPlaybook(settings.playbook);
170
+ } catch (error) {
171
+ logger?.warn?.(`pact-dsh: cannot read the playbook: ${error?.message ?? error}`);
172
+ return 0;
173
+ }
174
+ const service = safeService(ctx, 'commands');
175
+ if (!service || typeof service.register !== 'function') {
176
+ logger?.warn?.('pact-dsh: command service unavailable; commands are not registered');
177
+ return 0;
178
+ }
179
+ const commands = Array.isArray(playbook.commands) ? playbook.commands : [];
180
+ let registered = 0;
181
+ for (const command of commands) {
182
+ if (!command || typeof command.name !== 'string' || typeof command.body !== 'string') continue;
183
+ const definition = {
184
+ definitionId: 'pact-harness',
185
+ name: command.name,
186
+ description: command.description || command.name,
187
+ input: { hint: command.argument_hint || '' },
188
+ handler: async (invocation) => {
189
+ const supplied = String(invocation?.rawInput ?? '').trim();
190
+ const body = command.body.split('{arguments}').join(supplied);
191
+ invocation?.agent?.followup?.(deps.makeMessage(body));
192
+ return { kind: 'success', text: `PACT ${command.name} delivered` };
193
+ },
194
+ };
195
+ const dispose = service.register(definition);
196
+ if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
197
+ ctx.effect(() => dispose);
198
+ }
199
+ registered += 1;
200
+ }
201
+ logger?.info?.(`pact-dsh: registered ${registered} commands`);
202
+ return registered;
203
+ }
204
+
205
+ /**
206
+ * Register pact_agent: delegation that takes a PACT persona name.
207
+ *
208
+ * DSH's own subagent tool has no type parameter, so PACT's instruction
209
+ * Agent(subagent_type="pact-architect", name="architect") cannot be followed
210
+ * literally. This tool accepts that shape, resolves the persona name into a
211
+ * child label, and starts an activation through the subagent service. The child
212
+ * then receives its persona from the agent/created injection, matched by name.
213
+ *
214
+ * It is registered only when both services exist, and the tool DSL is loaded
215
+ * dynamically so a profile without dsh-tools degrades to a log line rather than
216
+ * a failed activation.
217
+ */
218
+ export async function registerPactAgent(ctx, settings, logger, deps = {}) {
219
+ const tools = safeService(ctx, 'tools');
220
+ const subagents = safeService(ctx, 'subagents');
221
+ if (
222
+ !tools ||
223
+ typeof tools.register !== 'function' ||
224
+ !subagents ||
225
+ typeof subagents.startActivation !== 'function'
226
+ ) {
227
+ logger?.info?.('pact-dsh: tools or subagents service unavailable; pact_agent is not registered');
228
+ return 0;
229
+ }
230
+ let defineTool = deps.defineTool;
231
+ if (!defineTool) {
232
+ try {
233
+ ({ defineTool } = await import('@deepseek-ai/dsh-tools'));
234
+ } catch (error) {
235
+ logger?.warn?.(`pact-dsh: tool DSL unavailable; pact_agent is not registered: ${error?.message ?? error}`);
236
+ return 0;
237
+ }
238
+ }
239
+ const provider = settings.subagentProvider ?? 'spawn';
240
+ const definition = defineTool({
241
+ name: 'pact_agent',
242
+ description:
243
+ 'Delegate to a PACT specialist. Use this when PACT instructions say ' +
244
+ 'Agent(subagent_type=<persona>, name=<short>, prompt=<task>). The child ' +
245
+ 'receives that persona automatically.',
246
+ parameters: {
247
+ subagent_type: {
248
+ type: 'string',
249
+ required: true,
250
+ description: 'PACT persona name, for example pact-architect.',
251
+ },
252
+ prompt: {
253
+ type: 'string',
254
+ required: true,
255
+ description: 'The complete task for the specialist.',
256
+ },
257
+ name: {
258
+ type: 'string',
259
+ description: 'Short child name; defaults to the persona without its pact- prefix.',
260
+ },
261
+ description: {
262
+ type: 'string',
263
+ description: 'Short description for display.',
264
+ },
265
+ },
266
+ output: {
267
+ schema: {
268
+ type: 'object',
269
+ properties: {
270
+ name: { type: 'string' },
271
+ child_id: { type: 'string' },
272
+ },
273
+ additionalProperties: false,
274
+ },
275
+ render: (args, value) => [{ type: 'text', text: `started ${value.name}` }],
276
+ },
277
+ isConcurrencySafe: () => false,
278
+ async execute(args, exec) {
279
+ const persona = String(args.subagent_type ?? '').trim();
280
+ if (!persona) throw new Error('pact_agent: subagent_type is required');
281
+ if (!exec?.agent) throw new Error('pact_agent: no calling agent to parent the child');
282
+ const label = String(args.name || persona.replace(/^pact-/, '') || 'specialist').slice(0, 32);
283
+ const activation = await subagents.startActivation({
284
+ provider,
285
+ label,
286
+ name: label,
287
+ prompt: [{ type: 'text', text: String(args.prompt ?? '') }],
288
+ parent: exec.agent,
289
+ signal: exec.signal,
290
+ delivery: 'parent',
291
+ });
292
+ return { name: String(activation?.name ?? label), child_id: String(activation?.childId ?? '') };
293
+ },
294
+ });
295
+ const dispose = tools.register(definition);
296
+ if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
297
+ ctx.effect(() => dispose);
298
+ }
299
+ logger?.info?.(`pact-dsh: registered pact_agent (provider ${provider})`);
300
+ return 1;
301
+ }
302
+
303
+ /** Remove a leading YAML frontmatter block from a skill body. */
304
+ export function stripFrontmatter(text) {
305
+ if (typeof text !== 'string') return '';
306
+ if (!text.startsWith('---\n')) return text;
307
+ const closing = text.indexOf('\n---\n', 4);
308
+ if (closing === -1) return text;
309
+ return text.slice(closing + 5);
310
+ }
311
+
312
+ /**
313
+ * Find the specialist persona for an agent name.
314
+ *
315
+ * DSH names a child agent with the short label the caller supplied ("architect"),
316
+ * while PACT's personas are named "pact-architect". Matching on the prefixed
317
+ * form first and then the bare form covers both spellings without guessing.
318
+ */
319
+ export function findPersona(playbook, name) {
320
+ const personas = Array.isArray(playbook?.personas) ? playbook.personas : [];
321
+ if (!name) return undefined;
322
+ const forms = new Set([name, `pact-${name}`, String(name).replace(/^pact-/, '')]);
323
+ for (const form of forms) {
324
+ const found = personas.find(
325
+ (persona) => persona?.name === form || persona?.name === `pact-${form}`,
326
+ );
327
+ if (found) return found;
328
+ }
329
+ return undefined;
330
+ }
331
+
332
+ /**
333
+ * Register PACT's skills over the vendored tree.
334
+ *
335
+ * Zero-copy: each skill is read from the path the compiler recorded, so a
336
+ * skill edit is visible on the next load without reinstalling anything. The
337
+ * provider ranks below project skills so a repository can override one, and
338
+ * carries its directory as a resource base so relative references resolve.
339
+ */
340
+ export function registerSkills(ctx, settings, logger) {
341
+ if (!settings.playbook) {
342
+ logger?.info?.('pact-dsh: no playbook configured; skills are not registered');
343
+ return 0;
344
+ }
345
+ let playbook;
346
+ try {
347
+ playbook = loadPlaybook(settings.playbook);
348
+ } catch (error) {
349
+ logger?.warn?.(`pact-dsh: cannot read the playbook: ${error?.message ?? error}`);
350
+ return 0;
351
+ }
352
+ const service = safeService(ctx, 'skills');
353
+ if (!service || typeof service.registerProvider !== 'function') {
354
+ logger?.warn?.('pact-dsh: skill service unavailable; skills are not registered');
355
+ return 0;
356
+ }
357
+ const skills = (Array.isArray(playbook.skills) ? playbook.skills : []).filter(
358
+ (skill) => skill && typeof skill.name === 'string' && typeof skill.path === 'string',
359
+ );
360
+ if (!skills.length) {
361
+ logger?.info?.('pact-dsh: the playbook has no skills');
362
+ return 0;
363
+ }
364
+ const provider = {
365
+ name: 'pact',
366
+ async list() {
367
+ return skills.map((skill) => ({
368
+ name: skill.name,
369
+ description: skill.description ?? skill.name,
370
+ path: skill.path,
371
+ invocation: { modelInvocable: true, userInvocable: true },
372
+ source: 'custom',
373
+ provider: 'pact',
374
+ rank: 300,
375
+ locator: { path: skill.path },
376
+ resourceBase: { kind: 'directory', path: skill.path },
377
+ }));
378
+ },
379
+ async get(candidate) {
380
+ const directory = candidate?.locator?.path ?? candidate?.path;
381
+ if (typeof directory !== 'string') return undefined;
382
+ const raw = readFileSync(path.join(directory, 'SKILL.md'), 'utf8');
383
+ return {
384
+ name: candidate.name,
385
+ description: candidate.description,
386
+ path: candidate.path,
387
+ invocation: candidate.invocation,
388
+ source: candidate.source,
389
+ provider: 'pact',
390
+ resourceBase: candidate.resourceBase,
391
+ content: stripFrontmatter(raw),
392
+ };
393
+ },
394
+ };
395
+ const dispose = service.registerProvider(() => provider);
396
+ if (typeof dispose === 'function' && typeof ctx.effect === 'function') {
397
+ ctx.effect(() => dispose);
398
+ }
399
+ logger?.info?.(`pact-dsh: registered ${skills.length} skills`);
400
+ return skills.length;
401
+ }
402
+
403
+ /** Write a startup record so a boot can be proven without a model. */
404
+ export function recordActivation(settings, extra = {}) {
405
+ const root = settings.stateRoot ?? path.join(os.homedir(), '.pact');
406
+ const directory = path.join(String(root), 'pact-harness');
407
+ mkdirSync(directory, { recursive: true });
408
+ const record = {
409
+ schemaVersion: 1,
410
+ activatedAt: new Date().toISOString(),
411
+ pid: process.pid,
412
+ mode: settings.mode,
413
+ enforceGates: [...settings.enforceGates],
414
+ ...extra,
415
+ };
416
+ writeFileSync(path.join(directory, 'dsh-activation.json'), JSON.stringify(record, null, 2));
417
+ return record;
418
+ }
419
+
420
+ /** The bridge's dependency surface, injectable so it can be tested. */
421
+ export function dependenciesFor(ctx, worker) {
422
+ const logger = ctx?.logger ?? {};
423
+ return {
424
+ logger,
425
+ evaluate: (event) => worker.evaluate(event),
426
+ // DSH's inbox rejects two pending messages that share an id, and an
427
+ // un-identified message is id `undefined` -- injecting two at once (which
428
+ // session start does) trips that invariant. Every injection gets its own
429
+ // identity.
430
+ makeMessage: (text) => ({
431
+ id: randomUUID(),
432
+ role: 'user',
433
+ content: [{ type: 'text', text }],
434
+ source: { kind: 'pact-dsh' },
435
+ }),
436
+ };
437
+ }
438
+
439
+ /** Ask the harness, converting an infrastructure failure into a policy answer. */
440
+ async function ask(deps, settings, event) {
441
+ try {
442
+ return await deps.evaluate(event);
443
+ } catch (error) {
444
+ const message = `PACT harness unavailable: ${error?.message ?? error}`;
445
+ deps.logger?.warn?.(`pact-dsh: ${message}`);
446
+ if (settings.mode === 'enforce') {
447
+ return { v: 1, directives: [{ kind: 'deny', reason: message, rule: 'pact-harness' }] };
448
+ }
449
+ return { v: 1, directives: [{ kind: 'notify', level: 'warning', text: message }] };
450
+ }
451
+ }
452
+
453
+ /** Register the bridge's listeners against a cordis context. */
454
+ export function wire(ctx, settings, deps) {
455
+ if (!ctx || typeof ctx.on !== 'function') {
456
+ throw new TypeError('pact-dsh: a cordis context with on() is required');
457
+ }
458
+ if (settings.mode === 'off') return;
459
+
460
+ ctx.on('tools/pre-execute', async (exec, next) => {
461
+ const event = events.toolEvent('tool.pre', exec, ctx);
462
+ const envelope = await ask(deps, settings, event);
463
+ const { decision, shadowed } = decisions.decidePre(envelope.directives ?? [], settings);
464
+ if (shadowed) deps.logger?.warn?.(`pact-dsh: ${shadowed}`);
465
+ return decision ?? next();
466
+ });
467
+
468
+ ctx.on('tools/post-execute', async (exec, result, next) => {
469
+ const event = events.toolEvent(result?.isError ? 'tool.fail' : 'tool.post', exec, ctx, result);
470
+ const envelope = await ask(deps, settings, event);
471
+ const directives = envelope.directives ?? [];
472
+ const block = decisions.blockOf(directives);
473
+ const messages = decisions
474
+ .injectionsOf(directives)
475
+ .concat(decisions.noticesOf(directives))
476
+ .map((directive) => deps.makeMessage(directive.text));
477
+ if (block) {
478
+ return {
479
+ kind: 'block',
480
+ feedback: [{ type: 'text', text: block.reason }],
481
+ additionalContexts: messages,
482
+ };
483
+ }
484
+ if (messages.length) return { kind: 'accept', additionalContexts: messages };
485
+ return next();
486
+ });
487
+
488
+ ctx.on('agent/pre-step', async (payload, next) => {
489
+ const event = events.promptEvent(payload, ctx);
490
+ const envelope = await ask(deps, settings, event);
491
+ const directives = envelope.directives ?? [];
492
+ const refusal = decisions.refusalOf(directives);
493
+ if (refusal && decisions.shouldEnforce(refusal.rule, settings)) {
494
+ return { kind: 'reject' };
495
+ }
496
+ if (refusal) {
497
+ deps.logger?.warn?.(
498
+ `pact-dsh: PACT would have rejected the step (${refusal.rule ?? 'unknown gate'}): ${refusal.reason}`,
499
+ );
500
+ }
501
+ const messages = decisions
502
+ .injectionsOf(directives)
503
+ .concat(decisions.noticesOf(directives))
504
+ .map((directive) => deps.makeMessage(directive.text));
505
+ if (messages.length) {
506
+ const base = Array.isArray(payload?.messages) ? payload.messages : [];
507
+ return { kind: 'enter', messages: [...base, ...messages] };
508
+ }
509
+ return next();
510
+ });
511
+
512
+ ctx.on('agent/created', async (payload) => {
513
+ const event = events.lifecycleEvent('session.start', payload?.agent, ctx, {
514
+ source: payload?.source,
515
+ });
516
+ const envelope = await ask(deps, settings, event);
517
+ const directives = envelope.directives ?? [];
518
+ const messages = decisions
519
+ .injectionsOf(directives)
520
+ .concat(decisions.noticesOf(directives))
521
+ .map((directive) => deps.makeMessage(directive.text));
522
+
523
+ // A teammate gets its specialist persona on creation. This is the DSH
524
+ // analogue of Claude Code loading the agent file named by subagent_type:
525
+ // the child starts with the role it was spawned as, not with a generic one.
526
+ const agent = payload?.agent;
527
+ if (agent && events.roleOf(ctx, agent) === 'teammate') {
528
+ const persona = findPersona(deps.playbook, agent.name);
529
+ if (persona && typeof persona.body === 'string' && persona.body) {
530
+ messages.unshift(deps.makeMessage(`PACT ROLE (${persona.name}):\n\n${persona.body}`));
531
+ }
532
+ }
533
+ for (const message of messages) {
534
+ agent?.inject?.(message);
535
+ }
536
+ });
537
+
538
+ ctx.on('agent/turn-stopping', async (payload) => {
539
+ const event = events.lifecycleEvent('turn.stop', payload?.agent, ctx);
540
+ const envelope = await ask(deps, settings, event);
541
+ const block = decisions.blockOf(envelope.directives ?? []);
542
+ if (block && settings.mode !== 'shadow') {
543
+ payload?.agent?.steer?.(deps.makeMessage(block.reason));
544
+ } else if (block) {
545
+ deps.logger?.warn?.(`pact-dsh: PACT would have refused the turn end: ${block.reason}`);
546
+ }
547
+ });
548
+
549
+ ctx.on('agent/status', async (payload) => {
550
+ if (payload?.status !== 'idle') return;
551
+ const event = events.lifecycleEvent('agent.idle', payload?.agent, ctx);
552
+ await ask(deps, settings, event);
553
+ });
554
+
555
+ ctx.on('session/disposed', async (session) => {
556
+ await ask(deps, settings, events.sessionEndEvent(session, ctx));
557
+ });
558
+
559
+ ctx.on('subagent/start', async (info) => {
560
+ const event = {
561
+ v: 1,
562
+ id: events.eventId(`${info?.id}:agent.start`),
563
+ kind: 'agent.start',
564
+ at: new Date().toISOString(),
565
+ adapter: 'dsh',
566
+ session: { id: events.sanitizeId(info?.parentSessionId, 'session'), cwd: process.cwd() },
567
+ actor: { role: 'unknown' },
568
+ payload: { provider: info?.provider, runId: String(info?.runId ?? '') },
569
+ };
570
+ await ask(deps, settings, event);
571
+ });
572
+
573
+ ctx.on('subagent/end', async (info) => {
574
+ const event = {
575
+ v: 1,
576
+ id: events.eventId(`${info?.id}:agent.stop`),
577
+ kind: 'agent.stop',
578
+ at: new Date().toISOString(),
579
+ adapter: 'dsh',
580
+ session: { id: events.sanitizeId(info?.parentSessionId, 'session'), cwd: process.cwd() },
581
+ actor: { role: 'unknown' },
582
+ payload: { provider: info?.provider, stopReason: String(info?.stopReason ?? '') },
583
+ };
584
+ await ask(deps, settings, event);
585
+ });
586
+ }
587
+
588
+ /** Cordis entry point. */
589
+ export function apply(ctx, config = {}) {
590
+ const settings = normalizeConfig(config);
591
+ if (settings.mode === 'off') {
592
+ ctx.logger?.info?.('pact-dsh: off');
593
+ return;
594
+ }
595
+ const worker = new HarnessWorker({
596
+ python: settings.python,
597
+ pluginRoot: settings.pluginRoot,
598
+ stateRoot: settings.stateRoot,
599
+ socketPath: settings.socketPath,
600
+ timeoutMs: settings.timeoutMs,
601
+ logger: ctx.logger,
602
+ });
603
+ if (typeof ctx.effect === 'function') {
604
+ ctx.effect(() => () => worker.stop(), 'pact-dsh worker');
605
+ }
606
+ const deps = dependenciesFor(ctx, worker);
607
+ try {
608
+ deps.playbook = loadPlaybook(settings.playbook);
609
+ } catch (error) {
610
+ deps.playbook = null;
611
+ ctx.logger?.warn?.(`pact-dsh: cannot read the playbook: ${error?.message ?? error}`);
612
+ }
613
+ loadMessageFactory(ctx.logger)
614
+ .then((makeMessage) => {
615
+ deps.makeMessage = makeMessage;
616
+ })
617
+ .catch(() => undefined);
618
+ try {
619
+ recordActivation(settings, {
620
+ pluginRoot: settings.pluginRoot ?? null,
621
+ python: settings.python,
622
+ playbook: settings.playbook ?? null,
623
+ });
624
+ ctx.logger?.info?.(`pact-dsh: ${settings.mode} mode, enforcing ${settings.enforceGates.join(', ') || 'nothing'}`);
625
+ } catch (error) {
626
+ ctx.logger?.warn?.(`pact-dsh: could not write the activation record: ${error?.message ?? error}`);
627
+ }
628
+ wire(ctx, settings, deps);
629
+ registerPersona(ctx, settings, ctx.logger);
630
+ registerCommands(ctx, settings, deps, ctx.logger);
631
+ registerSkills(ctx, settings, ctx.logger);
632
+ registerPactAgent(ctx, settings, ctx.logger).catch((error) => {
633
+ ctx.logger?.warn?.(`pact-dsh: pact_agent registration failed: ${error?.message ?? error}`);
634
+ });
635
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Rendering directives into DSH decisions.
3
+ *
4
+ * The bridge never invents a verdict; it renders what the harness decided and
5
+ * applies the configured enforcement policy. In shadow mode a deny from a gate
6
+ * that is not on the enforce list becomes an allow plus a logged notice, so the
7
+ * verdict is observable without interrupting work.
8
+ */
9
+
10
+ /** Whether a refusal should actually refuse. */
11
+ export function shouldEnforce(rule, settings) {
12
+ if (settings.mode === 'enforce') return true;
13
+ if (settings.mode !== 'shadow') return false;
14
+ return settings.enforceGates.includes(rule);
15
+ }
16
+
17
+ /** The first refusal in a directive list, if any. */
18
+ export function refusalOf(directives) {
19
+ return directives.find((directive) => directive.kind === 'deny');
20
+ }
21
+
22
+ /** The first approval request in a directive list, if any. */
23
+ export function askOf(directives) {
24
+ return directives.find((directive) => directive.kind === 'ask');
25
+ }
26
+
27
+ /** The first turn refusal in a directive list, if any. */
28
+ export function blockOf(directives) {
29
+ return directives.find((directive) => directive.kind === 'block');
30
+ }
31
+
32
+ /** The first cancel in a directive list, if any. */
33
+ export function cancelOf(directives) {
34
+ return directives.find((directive) => directive.kind === 'cancel');
35
+ }
36
+
37
+ /** Every context injection in a directive list. */
38
+ export function injectionsOf(directives) {
39
+ return directives.filter((directive) => directive.kind === 'inject');
40
+ }
41
+
42
+ /** Every user-facing notice in a directive list. */
43
+ export function noticesOf(directives) {
44
+ return directives.filter((directive) => directive.kind === 'notify');
45
+ }
46
+
47
+ /**
48
+ * Decide a pre-dispatch outcome.
49
+ *
50
+ * Returns either a DSH PreToolDecision or null, where null means "call next()".
51
+ * Shadowed refusals are reported through `shadowed` so the caller can log them.
52
+ */
53
+ export function decidePre(directives, settings) {
54
+ const refusal = refusalOf(directives);
55
+ if (refusal) {
56
+ if (shouldEnforce(refusal.rule, settings)) {
57
+ return { decision: { kind: 'deny', reason: refusal.reason }, shadowed: null };
58
+ }
59
+ return {
60
+ decision: null,
61
+ shadowed: `PACT would have denied (${refusal.rule ?? 'unknown gate'}): ${refusal.reason}`,
62
+ };
63
+ }
64
+ const ask = askOf(directives);
65
+ if (ask) return { decision: { kind: 'ask', reason: ask.reason }, shadowed: null };
66
+ const cancel = cancelOf(directives);
67
+ if (cancel) return { decision: { kind: 'cancel' }, shadowed: null };
68
+ return { decision: null, shadowed: null };
69
+ }
70
+
71
+ /** Build the text blocks a turn-end steering message carries. */
72
+ export function turnEndMessage(reason) {
73
+ return reason;
74
+ }
package/lib/events.js ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Normalising DSH extension-point payloads into pact.event.v1.
3
+ *
4
+ * Every field here is named deliberately. A platform that is not Claude Code
5
+ * has no inherited frame, so a field this module forgets is a field the
6
+ * vendored hooks will not see -- which is how a gate quietly stops applying.
7
+ */
8
+
9
+ import { createHash } from 'node:crypto';
10
+
11
+ import { canonicalize, normalizeArguments } from './tools.js';
12
+
13
+ const ID_ALLOWED = /[^A-Za-z0-9_-]/g;
14
+
15
+ /** Force any identifier into the contract's id alphabet. */
16
+ export function sanitizeId(value, fallback = 'unknown') {
17
+ const text = String(value ?? '').replace(ID_ALLOWED, '_').slice(0, 64);
18
+ if (!text) return fallback;
19
+ return /[A-Za-z0-9]/.test(text[0]) ? text : 'x' + text;
20
+ }
21
+
22
+ /** A deterministic event id from a seed. */
23
+ export function eventId(seed) {
24
+ const digest = createHash('sha256').update(String(seed)).digest('hex').slice(0, 16);
25
+ return `evt_${digest}`;
26
+ }
27
+
28
+ /** The session id a DSH agent carries. */
29
+ export function sessionIdOf(agent, fallback = 'session') {
30
+ // The session is agent.session, and its id is inside it: an earlier version of
31
+ // this bridge read agent.sessionId, which does not exist on a DSH Agent, and
32
+ // the resulting undefined silently disabled every session-scoped behaviour.
33
+ const id = agent?.session?.id ?? agent?.sessionId;
34
+ return sanitizeId(id, fallback);
35
+ }
36
+
37
+ /** The working directory a DSH agent carries. */
38
+ export function cwdOf(agent, fallback = process.cwd()) {
39
+ return agent?.session?.header?.cwd ?? agent?.cwd ?? fallback;
40
+ }
41
+
42
+ /** Whether this agent is the tree root, and therefore the team lead. */
43
+ export function roleOf(ctx, agent) {
44
+ if (!agent) return 'unknown';
45
+ // Read the service through ctx.get rather than the property: a cordis
46
+ // context throws on a property read for a service the plugin did not
47
+ // declare, and the team service is optional. The property path exists only
48
+ // for plain objects in tests.
49
+ let subagents;
50
+ try {
51
+ subagents = typeof ctx?.get === 'function' ? ctx.get('subagents') : ctx?.subagents;
52
+ } catch {
53
+ subagents = undefined;
54
+ }
55
+ if (subagents && typeof subagents.rootOf === 'function') {
56
+ try {
57
+ return subagents.rootOf(agent) === agent ? 'lead' : 'teammate';
58
+ } catch {
59
+ // Fall through to the structural answer rather than guessing at runtime.
60
+ }
61
+ }
62
+ return agent?.parentSession || agent?.parentSessionId ? 'teammate' : 'lead';
63
+ }
64
+
65
+ /** The actor block for one event. */
66
+ export function actorOf(ctx, agent) {
67
+ const role = roleOf(ctx, agent);
68
+ const name = agent?.name;
69
+ const actor = { role };
70
+ if (name) actor.name = sanitizeId(name, 'agent');
71
+ if (role === 'lead') actor.type = 'pact-orchestrator';
72
+ else if (role === 'teammate') actor.type = name ? sanitizeId(name, 'agent') : 'pact-teammate';
73
+ return actor;
74
+ }
75
+
76
+ /** The session block for one event. */
77
+ export function sessionOf(agent, extra = {}) {
78
+ const session = { id: sessionIdOf(agent), cwd: cwdOf(agent) };
79
+ if (extra.project_dir) session.project_dir = String(extra.project_dir);
80
+ if (extra.transcript_path) session.transcript_path = String(extra.transcript_path);
81
+ return session;
82
+ }
83
+
84
+ /** Extract plain text from a list of DSH content blocks. */
85
+ export function textOfContent(content) {
86
+ if (!Array.isArray(content)) return '';
87
+ return content
88
+ .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
89
+ .map((block) => block.text)
90
+ .join('\n');
91
+ }
92
+
93
+ /**
94
+ * Build a tool event.
95
+ *
96
+ * A call to the delegation tool is reported as agent.spawn.pre rather than
97
+ * tool.pre: the gates distinguish "delegate to a specialist" from "run a tool",
98
+ * and collapsing them would apply tool gates to delegation.
99
+ */
100
+ export function toolEvent(kind, exec, ctx, result) {
101
+ const native = typeof exec?.name === 'string' ? exec.name : 'Unknown';
102
+ const canonical = canonicalize(native);
103
+ const args = normalizeArguments(canonical, exec?.arguments);
104
+ const agent = exec?.agent;
105
+ const spawn = canonical === 'Agent';
106
+ const event = {
107
+ v: 1,
108
+ id: eventId(`${sessionIdOf(agent)}:${kind}:${exec?.callId ?? ''}:${native}`),
109
+ kind: spawn && kind === 'tool.pre' ? 'agent.spawn.pre' : kind,
110
+ at: new Date().toISOString(),
111
+ adapter: 'dsh',
112
+ session: sessionOf(agent, { project_dir: cwdOf(agent) }),
113
+ actor: actorOf(ctx, agent),
114
+ };
115
+ if (spawn && event.kind === 'agent.spawn.pre') {
116
+ event.payload = {
117
+ subagent_type: args.subagent_type ?? args.type,
118
+ name: args.name,
119
+ prompt: args.prompt,
120
+ description: args.description,
121
+ run_in_background: args.run_in_background,
122
+ };
123
+ for (const key of Object.keys(event.payload)) {
124
+ if (event.payload[key] === undefined) delete event.payload[key];
125
+ }
126
+ } else {
127
+ const tool = {
128
+ canonical,
129
+ native,
130
+ input: args,
131
+ call_id: exec?.callId ? sanitizeId(exec.callId) : undefined,
132
+ parent_call_id: exec?.parent?.callId ? sanitizeId(exec.parent.callId) : undefined,
133
+ is_sub_dispatch: Boolean(exec?.parent),
134
+ };
135
+ if (result) {
136
+ if (result.isError) tool.error = { message: String(result.error?.message ?? result.error ?? '') };
137
+ else if (result.value !== undefined) tool.result = { value: result.value };
138
+ }
139
+ for (const key of Object.keys(tool)) if (tool[key] === undefined) delete tool[key];
140
+ event.tool = tool;
141
+ }
142
+ return event;
143
+ }
144
+
145
+ /** Build a prompt event from an agent/pre-step payload. */
146
+ export function promptEvent(payload, ctx) {
147
+ const agent = payload?.agent;
148
+ const messages = Array.isArray(payload?.messages) ? payload.messages : [];
149
+ const prompt = messages
150
+ .map((message) => textOfContent(message?.content))
151
+ .filter(Boolean)
152
+ .join('\n');
153
+ return {
154
+ v: 1,
155
+ id: eventId(`${sessionIdOf(agent)}:prompt:${payload?.turn ?? 0}:${payload?.step ?? 0}`),
156
+ kind: 'prompt.submit',
157
+ at: new Date().toISOString(),
158
+ adapter: 'dsh',
159
+ session: sessionOf(agent, { project_dir: cwdOf(agent) }),
160
+ actor: actorOf(ctx, agent),
161
+ payload: prompt ? { prompt } : {},
162
+ };
163
+ }
164
+
165
+ /** Build a lifecycle event. */
166
+ export function lifecycleEvent(kind, agent, ctx, payload = {}) {
167
+ const event = {
168
+ v: 1,
169
+ id: eventId(`${sessionIdOf(agent)}:${kind}:${payload.source ?? ''}`),
170
+ kind,
171
+ at: new Date().toISOString(),
172
+ adapter: 'dsh',
173
+ session: sessionOf(agent, { project_dir: cwdOf(agent) }),
174
+ actor: actorOf(ctx, agent),
175
+ };
176
+ if (Object.keys(payload).length) event.payload = payload;
177
+ return event;
178
+ }
179
+
180
+ /** Build a session-end event from a disposed session. */
181
+ export function sessionEndEvent(session, ctx) {
182
+ return {
183
+ v: 1,
184
+ id: eventId(`${sanitizeId(session?.id)}:session.end`),
185
+ kind: 'session.end',
186
+ at: new Date().toISOString(),
187
+ adapter: 'dsh',
188
+ session: {
189
+ id: sanitizeId(session?.id),
190
+ cwd: session?.header?.cwd ?? process.cwd(),
191
+ },
192
+ actor: { role: 'unknown' },
193
+ };
194
+ }
195
+
196
+ /** Build a task-completed event from a team task projection. */
197
+ export function taskEvent(task, ctx) {
198
+ return {
199
+ v: 1,
200
+ id: eventId(`${task?.id}:task.completed:${task?.revision ?? 0}`),
201
+ kind: 'task.completed',
202
+ at: new Date().toISOString(),
203
+ adapter: 'dsh',
204
+ session: { id: 'team-task', cwd: process.cwd() },
205
+ actor: { role: 'unknown' },
206
+ task: {
207
+ id: sanitizeId(task?.id),
208
+ subject: task?.subject,
209
+ team_name: task?.teamName,
210
+ teammate_name: task?.ownerName ?? task?.owner,
211
+ status: task?.status,
212
+ },
213
+ };
214
+ }
package/lib/tools.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The canonical tool vocabulary.
3
+ *
4
+ * PACT's gates are written against Claude Code's tool names and argument
5
+ * shapes, so the canonical vocabulary is Claude Code's. An unmapped name is
6
+ * passed through unchanged rather than dropped: the gates treat an unknown
7
+ * name as unclassified, and `pact doctor` is where that gets reported. A name
8
+ * silently dropped here would be a gate silently not running.
9
+ */
10
+
11
+ export const CANONICAL_TOOLS = Object.freeze({
12
+ bash: 'Bash',
13
+ pwsh: 'Bash',
14
+ read: 'Read',
15
+ read_image: 'Read',
16
+ write: 'Write',
17
+ edit: 'Edit',
18
+ str_replace_editor: 'Edit',
19
+ apply_patch: 'Edit',
20
+ glob: 'Glob',
21
+ grep: 'Grep',
22
+ subagent: 'Agent',
23
+ subagent_fork: 'Agent',
24
+ spawn_teammate: 'Agent',
25
+ pact_agent: 'Agent',
26
+ team_task_create: 'TaskCreate',
27
+ team_task_update: 'TaskUpdate',
28
+ team_task_list: 'TaskList',
29
+ team_task_get: 'TaskGet',
30
+ send_message: 'SendMessage',
31
+ skill: 'Skill',
32
+ ask_user_question: 'AskUserQuestion',
33
+ todo_write: 'TodoWrite',
34
+ exit_plan_mode: 'ExitPlanMode',
35
+ run_code: 'RunCode',
36
+ });
37
+
38
+ /** Translate one DSH tool name into the canonical vocabulary. */
39
+ export function canonicalize(name) {
40
+ if (typeof name !== 'string' || name === '') return 'Unknown';
41
+ return CANONICAL_TOOLS[name] ?? name;
42
+ }
43
+
44
+ /** Tools whose target is a single file. */
45
+ const FILE_TOOLS = new Set(['Edit', 'Read', 'Write']);
46
+
47
+ /**
48
+ * Normalise call arguments so a gate always finds tool_input.file_path.
49
+ *
50
+ * DSH's file tools do not agree on the key: edit/write/read use file_path and
51
+ * str_replace_editor uses path. A gate that reads only one spelling declines to
52
+ * fire on the other, which is indistinguishable from the gate passing.
53
+ */
54
+ export function normalizeArguments(canonical, rawArgs) {
55
+ const args = rawArgs && typeof rawArgs === 'object' ? { ...rawArgs } : {};
56
+ if (FILE_TOOLS.has(canonical) && typeof args.file_path !== 'string') {
57
+ if (typeof args.path === 'string') args.file_path = args.path;
58
+ }
59
+ return args;
60
+ }
61
+
62
+ /** The single file a call targets, when it targets exactly one. */
63
+ export function filePathOf(args) {
64
+ return args && typeof args.file_path === 'string' ? args.file_path : undefined;
65
+ }
package/lib/worker.js ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The bridge's client for the warm harness worker.
3
+ *
4
+ * One worker serves the whole session: it imports PACT's shared tree once and
5
+ * forks a child per hook, so a tool call pays a socket round trip and a fork
6
+ * instead of a fresh interpreter start per hook. The bridge starts it lazily
7
+ * and stops it when the plugin is disposed.
8
+ */
9
+
10
+ import { spawn } from 'node:child_process';
11
+ import { connect } from 'node:net';
12
+ import { mkdirSync } from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+
16
+ const START_TIMEOUT_MS = 20000;
17
+ const DEFAULT_TIMEOUT_MS = 60000;
18
+
19
+ let socketCounter = 0;
20
+
21
+ /** A per-process socket path short enough for a unix socket. */
22
+ export function socketPathFor(stateRoot, pid = process.pid) {
23
+ socketCounter += 1;
24
+ const stem = `dsh-${pid}-${socketCounter}.sock`;
25
+ if (stateRoot) return path.join(String(stateRoot), 'pact-harness', stem);
26
+ return path.join(os.tmpdir(), 'pact-harness', stem);
27
+ }
28
+
29
+ /** Send one JSON request over a unix socket and read one JSON response. */
30
+ export function requestOverSocket(socketPath, payload, timeoutMs = DEFAULT_TIMEOUT_MS) {
31
+ return new Promise((resolve, reject) => {
32
+ const client = connect(socketPath);
33
+ let buffer = '';
34
+ let settled = false;
35
+ const finish = (error, value) => {
36
+ if (settled) return;
37
+ settled = true;
38
+ client.destroy();
39
+ if (error) reject(error);
40
+ else resolve(value);
41
+ };
42
+ client.setEncoding('utf8');
43
+ client.setTimeout(timeoutMs);
44
+ client.on('connect', () => client.write(JSON.stringify(payload) + '\n'));
45
+ client.on('data', (chunk) => {
46
+ buffer += chunk;
47
+ const newline = buffer.indexOf('\n');
48
+ if (newline === -1) return;
49
+ try {
50
+ finish(null, JSON.parse(buffer.slice(0, newline)));
51
+ } catch (error) {
52
+ finish(new Error(`unreadable worker response: ${error.message}`));
53
+ }
54
+ });
55
+ client.on('timeout', () => finish(new Error('worker request timed out')));
56
+ client.on('error', (error) => finish(error));
57
+ client.on('close', () => {
58
+ if (!settled) finish(new Error('worker closed the connection without a response'));
59
+ });
60
+ });
61
+ }
62
+
63
+ export class HarnessWorker {
64
+ constructor(options = {}) {
65
+ this.python = options.python ?? 'python3';
66
+ this.pluginRoot = options.pluginRoot;
67
+ this.stateRoot = options.stateRoot;
68
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
69
+ this.env = options.env ?? process.env;
70
+ this.logger = options.logger;
71
+ this.socketPath = options.socketPath ?? socketPathFor(this.stateRoot);
72
+ this.child = null;
73
+ this.starting = null;
74
+ }
75
+
76
+ /** Start the worker, or return the in-flight start. */
77
+ start() {
78
+ if (this.starting) return this.starting;
79
+ this.starting = this.#start();
80
+ return this.starting;
81
+ }
82
+
83
+ async #start() {
84
+ mkdirSync(path.dirname(this.socketPath), { recursive: true });
85
+ const args = ['-m', 'pact_harness', 'serve', '--socket', this.socketPath];
86
+ if (this.pluginRoot) args.push('--plugin-root', String(this.pluginRoot));
87
+ const child = spawn(this.python, args, {
88
+ env: { ...this.env },
89
+ stdio: ['ignore', 'ignore', 'pipe'],
90
+ });
91
+ this.child = child;
92
+ let stderr = '';
93
+ child.stderr?.setEncoding?.('utf8');
94
+ child.stderr?.on?.('data', (chunk) => {
95
+ stderr += String(chunk);
96
+ });
97
+ let exited = false;
98
+ child.once('exit', (code) => {
99
+ exited = true;
100
+ if (code !== 0 && this.logger?.warn) {
101
+ this.logger.warn(`pact-dsh: worker exited with ${code}: ${stderr.trim()}`);
102
+ }
103
+ });
104
+
105
+ const deadline = Date.now() + START_TIMEOUT_MS;
106
+ while (Date.now() < deadline) {
107
+ if (exited) throw new Error(`worker exited during startup: ${stderr.trim()}`);
108
+ try {
109
+ await requestOverSocket(this.socketPath, { type: 'ping' }, 500);
110
+ return this;
111
+ } catch {
112
+ await new Promise((resolve) => setTimeout(resolve, 50));
113
+ }
114
+ }
115
+ this.stop();
116
+ throw new Error('worker did not accept a connection in time');
117
+ }
118
+
119
+ /** Evaluate one normalised event. */
120
+ async evaluate(event) {
121
+ await this.start();
122
+ const response = await requestOverSocket(
123
+ this.socketPath,
124
+ {
125
+ type: 'evaluate',
126
+ event,
127
+ state_root: this.stateRoot,
128
+ timeout_s: Math.max(1, Math.floor(this.timeoutMs / 1000)),
129
+ },
130
+ this.timeoutMs,
131
+ );
132
+ if (response?.status === 'error') {
133
+ throw new Error(response.error ?? 'worker reported an evaluation error');
134
+ }
135
+ if (!response?.envelope) throw new Error('worker returned no envelope');
136
+ return response.envelope;
137
+ }
138
+
139
+ /** Stop the worker. */
140
+ stop() {
141
+ this.starting = null;
142
+ if (this.child && this.child.exitCode === null) {
143
+ this.child.kill();
144
+ }
145
+ this.child = null;
146
+ }
147
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@pact-harness/dsh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.5",
4
+ "type": "module",
5
+ "description": "PACT orchestration and enforcement for DeepSeek Harness",
6
+ "main": "index.js",
7
+ "files": [
8
+ "index.js",
9
+ "lib",
10
+ "cordis.patch.yml"
11
+ ],
12
+ "scripts": {
13
+ "test": "node --test test/"
14
+ },
15
+ "dsh": {
16
+ "bundle": {
17
+ "patch": "./cordis.patch.yml"
18
+ }
19
+ },
20
+ "engines": {
21
+ "dsh": ">=0.2.0 <0.3.0"
22
+ },
23
+ "license": "MIT",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/michael-wojcik/pact-harness.git",
27
+ "directory": "adapters/dsh"
28
+ },
29
+ "homepage": "https://github.com/michael-wojcik/pact-harness#readme",
30
+ "bugs": {
31
+ "url": "https://github.com/michael-wojcik/pact-harness/issues"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "keywords": [
37
+ "pact",
38
+ "deepseek",
39
+ "harness",
40
+ "agents",
41
+ "orchestration"
42
+ ]
43
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.