@causyne/agent 1.20.87 → 1.20.91

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,142 @@
1
+ /**
2
+ * Permission -> PreToolUse -> execute -> PostToolUse -> result.
3
+ *
4
+ * TypeScript successor to toolDispatch.js. This is a deliberately narrow
5
+ * migration: names, result-message shape, and exported public functions stay
6
+ * compatible. Authorization may be asynchronous; it must always be awaited
7
+ * before a tool can execute. A failed payload must never report isError=false.
8
+ */
9
+
10
+ type MaybePromise<T> = T | Promise<T>;
11
+ export type ToolPayload = Record<string, unknown> & { success?: boolean; error?: string };
12
+
13
+ export interface HookFeedback {
14
+ denied?: boolean;
15
+ messages?: readonly string[];
16
+ }
17
+
18
+ export interface AuthorizationDecision {
19
+ allow?: boolean;
20
+ reason?: string;
21
+ }
22
+
23
+ export interface DispatchToolCallInput {
24
+ toolCallId: string;
25
+ name: string;
26
+ args?: Record<string, unknown>;
27
+ authorize?: ((name: string, args: Record<string, unknown>) => MaybePromise<AuthorizationDecision | undefined | null>) | null;
28
+ preHook?: ((name: string, args: Record<string, unknown>) => MaybePromise<HookFeedback | undefined | null>) | null;
29
+ postHook?: ((name: string, args: Record<string, unknown>, payload: ToolPayload, isError: boolean) => MaybePromise<HookFeedback | undefined | null>) | null;
30
+ execute: (name: string, args: Record<string, unknown>) => Promise<unknown> | unknown;
31
+ }
32
+
33
+ export interface ToolResultMessage {
34
+ role: 'tool';
35
+ tool_call_id: string;
36
+ name: string;
37
+ content: string;
38
+ }
39
+
40
+ export interface DispatchToolCallResult {
41
+ message: ToolResultMessage;
42
+ isError: boolean;
43
+ denied: boolean;
44
+ }
45
+
46
+ function errorString(error: unknown): string {
47
+ if (error instanceof Error) return error.message;
48
+ return typeof error === 'string' ? error : String(error);
49
+ }
50
+
51
+ export function toolResultMessage(toolCallId: string, name: string, payload: ToolPayload): ToolResultMessage {
52
+ return { role: 'tool', tool_call_id: toolCallId, name, content: JSON.stringify(payload) };
53
+ }
54
+
55
+ export function mergeHookFeedback<T extends ToolPayload>(
56
+ payload: T,
57
+ messages?: readonly string[] | null,
58
+ denied = false
59
+ ): T & { hookFeedback?: string } {
60
+ if (!messages || messages.length === 0) return payload;
61
+ const title = denied ? 'Hook feedback (denied)' : 'Hook feedback';
62
+ const note = `${title}:\n${messages.join('\n')}`;
63
+ const existing = typeof payload.hookFeedback === 'string' ? `${payload.hookFeedback}\n` : '';
64
+ return { ...payload, hookFeedback: existing + note };
65
+ }
66
+
67
+ function failed(toolCallId: string, name: string, error: string, denied = false): DispatchToolCallResult {
68
+ return { denied, isError: true, message: toolResultMessage(toolCallId, name, { success: false, error }) };
69
+ }
70
+
71
+ function normalizePayload(value: unknown): ToolPayload {
72
+ if (value === null || value === undefined) return { success: true };
73
+ if (value instanceof Error) return { success: false, error: value.message };
74
+ if (typeof value !== 'object' || Array.isArray(value)) return { success: true, output: value };
75
+ const payload = { ...(value as Record<string, unknown>) };
76
+ if (typeof payload.success !== 'boolean') {
77
+ payload.success = typeof payload.error === 'string' ? false : true;
78
+ }
79
+ return payload as ToolPayload;
80
+ }
81
+
82
+ export async function dispatchToolCall({
83
+ toolCallId,
84
+ name,
85
+ args = {},
86
+ authorize = null,
87
+ preHook = null,
88
+ postHook = null,
89
+ execute
90
+ }: DispatchToolCallInput): Promise<DispatchToolCallResult> {
91
+ // Authorization failures are denials, never permission to proceed.
92
+ try {
93
+ if (authorize) {
94
+ const decision = await authorize(name, args);
95
+ if (decision?.allow !== true) {
96
+ return failed(toolCallId, name, decision?.reason || `Tool "${name}" was not permitted.`, true);
97
+ }
98
+ }
99
+ } catch (error) {
100
+ return failed(toolCallId, name, `Authorization failed for "${name}": ${errorString(error)}`, true);
101
+ }
102
+
103
+ let pre: HookFeedback;
104
+ try {
105
+ pre = await preHook?.(name, args) ?? { denied: false, messages: [] };
106
+ } catch (error) {
107
+ return failed(toolCallId, name, `PreToolUse hook failed for "${name}": ${errorString(error)}`, true);
108
+ }
109
+ if (pre.denied) {
110
+ const payload = mergeHookFeedback(
111
+ { success: false, error: `PreToolUse hook denied tool "${name}".` }, pre.messages, true
112
+ );
113
+ return { denied: true, isError: true, message: toolResultMessage(toolCallId, name, payload) };
114
+ }
115
+
116
+ let payload: ToolPayload;
117
+ try {
118
+ payload = normalizePayload(await execute(name, args));
119
+ } catch (error) {
120
+ payload = { success: false, error: errorString(error) };
121
+ }
122
+ let isError = payload.success === false || typeof payload.error === 'string';
123
+ payload = mergeHookFeedback(payload, pre.messages);
124
+
125
+ // A post-hook can reject the outcome but cannot undo an already executed
126
+ // side effect. Expose that uncertainty instead of returning false success.
127
+ let post: HookFeedback;
128
+ try {
129
+ post = await postHook?.(name, args, payload, isError) ?? { denied: false, messages: [] };
130
+ } catch (error) {
131
+ post = { denied: true, messages: [`PostToolUse hook raised: ${errorString(error)}`] };
132
+ }
133
+ if (post.denied) {
134
+ isError = true;
135
+ payload = { ...payload, success: false, error: payload.error ||
136
+ 'PostToolUse hook denied or failed after execution; inspect actual side effects before retry.' };
137
+ }
138
+ payload = mergeHookFeedback(payload, post.messages, Boolean(post.denied));
139
+ isError ||= payload.success === false || typeof payload.error === 'string';
140
+
141
+ return { denied: false, isError, message: toolResultMessage(toolCallId, name, payload) };
142
+ }
@@ -140,7 +140,15 @@ export const TOOL_NAME_ALIASES = {
140
140
  printer_list: 'printer_list_printers',
141
141
  create_skill: 'skill_create',
142
142
  read_skill: 'fs_read_skill',
143
+ read_skil: 'fs_read_skill',
144
+ fs_read_skil: 'fs_read_skill',
145
+ skill_read: 'fs_read_skill',
146
+ skill_read_native: 'fs_read_skill',
143
147
  readNativeSkill: 'fs_read_skill',
148
+ read_native_skill: 'fs_read_skill',
149
+ load_skill: 'fs_read_skill',
150
+ get_skill: 'fs_read_skill',
151
+ skill: 'fs_read_skill',
144
152
  take_screenshot: 'screenshot',
145
153
  capture_screenshot: 'screenshot',
146
154
  open_file: 'desktop_open',
@@ -169,7 +169,15 @@ export const TOOL_NAME_ALIASES: Record<string, string> = {
169
169
  printer_list: 'printer_list_printers',
170
170
  create_skill: 'skill_create',
171
171
  read_skill: 'fs_read_skill',
172
+ read_skil: 'fs_read_skill',
173
+ fs_read_skil: 'fs_read_skill',
174
+ skill_read: 'fs_read_skill',
175
+ skill_read_native: 'fs_read_skill',
172
176
  readNativeSkill: 'fs_read_skill',
177
+ read_native_skill: 'fs_read_skill',
178
+ load_skill: 'fs_read_skill',
179
+ get_skill: 'fs_read_skill',
180
+ skill: 'fs_read_skill',
173
181
  take_screenshot: 'screenshot',
174
182
  capture_screenshot: 'screenshot',
175
183
  open_file: 'desktop_open',
@@ -611,13 +611,14 @@ export class ChatRenderer {
611
611
  * Mirrors OpenCode's session conversation loader so prior turns are visible in viewport.
612
612
  */
613
613
  renderSessionHistory(messages = [], sessionInfo = null) {
614
- this.transcript?.surface?.leaveHome?.(true);
615
- this.clearTranscript();
616
- this.latestPlan = [];
617
- this.onPlanChange?.([]);
618
- this.resetTurn();
619
-
620
- const info = sessionInfo ? { ...sessionInfo } : {};
614
+ const renderContent = () => {
615
+ this.transcript?.surface?.leaveHome?.(true);
616
+ this.clearTranscript();
617
+ this.latestPlan = [];
618
+ this.onPlanChange?.([]);
619
+ this.resetTurn();
620
+
621
+ const info = sessionInfo ? { ...sessionInfo } : {};
621
622
  if (info.messagesCount === undefined || info.messagesCount === null) {
622
623
  info.messagesCount = messages.filter(m => m && m.role !== 'system').length;
623
624
  }
@@ -779,10 +780,17 @@ export class ChatRenderer {
779
780
  });
780
781
  }
781
782
 
782
- if (this.transcript?.surface?.viewport) {
783
- this.transcript.surface.viewport.manual = false;
784
- this.transcript.surface.viewport.unseen = 0;
785
- this.transcript.surface.viewport.toBottom();
783
+ if (this.transcript?.surface?.viewport) {
784
+ this.transcript.surface.viewport.manual = false;
785
+ this.transcript.surface.viewport.unseen = 0;
786
+ this.transcript.surface.viewport.toBottom();
787
+ }
788
+ };
789
+
790
+ if (this.transcript && typeof this.transcript.batch === 'function') {
791
+ this.transcript.batch(renderContent);
792
+ } else {
793
+ renderContent();
786
794
  }
787
795
  }
788
796
 
@@ -1,4 +1,3 @@
1
- // @ts-expect-error userSkills.js is awaiting TypeScript migration.
2
1
  import { writeUserSkill, validateSegment, skillTemplate } from '../userSkills.js';
3
2
  import { invalidateUserSkills } from '../skillsManager.js';
4
3
  // @ts-expect-error theme.js has no TypeScript declaration yet.
@@ -1,4 +1,3 @@
1
- // @ts-expect-error userSkills.js is awaiting TypeScript migration.
2
1
  import { writeUserSkill, validateSegment, skillTemplate } from '../userSkills.js';
3
2
  import { invalidateUserSkills } from '../skillsManager.js';
4
3
  // @ts-expect-error theme.js has no TypeScript declaration yet.
@@ -14,7 +13,7 @@ export interface CreatedUserSkill {
14
13
  name: string;
15
14
  description: string;
16
15
  content: string;
17
- path?: string;
16
+ path?: string | undefined;
18
17
  source: 'user';
19
18
  }
20
19
 
@@ -128,6 +128,22 @@ export class Transcript {
128
128
  return frame.id;
129
129
  }
130
130
 
131
+ /**
132
+ * Batch multiple appends or frame updates under a single change event,
133
+ * preventing O(N^2) reflows during session history restoration.
134
+ */
135
+ batch(action) {
136
+ if (typeof action !== 'function') return;
137
+ const prevOnChange = this.onChange;
138
+ this.onChange = null;
139
+ try {
140
+ action();
141
+ } finally {
142
+ this.onChange = prevOnChange;
143
+ this.changed();
144
+ }
145
+ }
146
+
131
147
  changed() {
132
148
  if (!this.onChange) return;
133
149
  // A listener that throws must not take the transcript down with it: the
@@ -0,0 +1,26 @@
1
+ /** Types for the existing JavaScript user skill store during the TS migration. */
2
+ export interface UserSkill {
3
+ domain: string;
4
+ id: string;
5
+ name: string;
6
+ description: string;
7
+ content: string;
8
+ source: 'user';
9
+ path: string;
10
+ }
11
+ export const MAX_USER_SKILLS: number;
12
+ export const MAX_SKILL_BYTES: number;
13
+ export const MAX_DESCRIPTION: number;
14
+ export function userSkillsRoot(): string;
15
+ export function validateSegment(value: unknown, what?: string): string | null;
16
+ export function parseSkillId(id: unknown):
17
+ | { domain: string; name: string; error?: never }
18
+ | { domain?: never; name?: never; error: string };
19
+ export function loadUserSkills(root?: string): { skills: UserSkill[]; problems: string[] };
20
+ export function skillTemplate(domain: string, name: string, description?: string): string;
21
+ export function writeUserSkill(input: {
22
+ domain: string; name: string; content: string; overwrite?: boolean;
23
+ }, root?: string): { ok: boolean; path?: string; error?: string };
24
+ export function deleteUserSkill(domain: string, name: string, root?: string): {
25
+ ok: boolean; path?: string; error?: string;
26
+ };
package/src/userSkills.js CHANGED
@@ -4,6 +4,7 @@ import fs from 'fs';
4
4
  import os from 'os';
5
5
  import path from 'path';
6
6
  import { causyneHome } from './utils/paths.js';
7
+ import { assertSkillTreeSafe } from './skills/skillResourceSafety.js';
7
8
 
8
9
  // Bounds. Every one of these protects the context window, which is the resource
9
10
  // a skill library actually spends.
@@ -137,6 +138,7 @@ export function loadUserSkills(root = userSkillsRoot()) {
137
138
  const file = path.join(root, domain, name, 'SKILL.md');
138
139
  let content;
139
140
  try {
141
+ assertSkillTreeSafe(root, domain, name);
140
142
  // Refuse a symlink outright: it is the one way a file inside this
141
143
  // directory can point at something outside it.
142
144
  const stat = fs.lstatSync(file);
@@ -237,8 +239,21 @@ export function writeUserSkill({ domain, name, content, overwrite = false }, roo
237
239
  }
238
240
 
239
241
  try {
242
+ // Causyne Skills Safety v1: lexical path checks do not stop an existing
243
+ // symlinked parent directory from redirecting a skill write elsewhere.
244
+ assertSkillTreeSafe(root, domain, name, true);
240
245
  fs.mkdirSync(directory, { recursive: true });
241
- fs.writeFileSync(file, body, 'utf8');
246
+ assertSkillTreeSafe(root, domain, name);
247
+ const nofollow = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
248
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | nofollow
249
+ | (overwrite ? fs.constants.O_TRUNC : fs.constants.O_EXCL);
250
+ const fd = fs.openSync(file, flags, 0o600);
251
+ try {
252
+ if (!fs.fstatSync(fd).isFile()) throw new Error('SKILL.md must be a regular file');
253
+ fs.writeFileSync(fd, body, 'utf8');
254
+ } finally {
255
+ fs.closeSync(fd);
256
+ }
242
257
  } catch (e) {
243
258
  return { ok: false, error: `could not write ${file}: ${e.message}` };
244
259
  }
@@ -257,6 +272,11 @@ export function deleteUserSkill(domain, name, root = userSkillsRoot()) {
257
272
  return { ok: false, error: `${domain}/${name} is not a user skill` };
258
273
  }
259
274
  try {
275
+ assertSkillTreeSafe(root, domain, name);
276
+ const skillFile = fs.lstatSync(path.join(directory, 'SKILL.md'));
277
+ if (skillFile.isSymbolicLink() || !skillFile.isFile()) {
278
+ throw new Error('SKILL.md must be a regular file');
279
+ }
260
280
  fs.rmSync(directory, { recursive: true, force: true });
261
281
  } catch (e) {
262
282
  return { ok: false, error: `could not remove ${directory}: ${e.message}` };