@pi-kode/tasks 0.0.0-init → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @pi-kode/tasks
2
+
3
+ Standalone [pi](https://github.com/badlogic/pi-mono) extension providing durable session-branch task tracking, a live TUI checklist widget, and supervised background shell jobs.
4
+
5
+ ## Capabilities
6
+
7
+ ### Task Management & Dependency Graph
8
+
9
+ Work items are persisted in the active pi session branch (`pk:tasks` entries, with backward-compatible restoration for `cc:tasks` and `code-compat:state`) and automatically restored on `session_start` and `session_tree` navigation. When tasks exist, the extension also injects active task state into the agent context on `before_agent_start`.
10
+
11
+ Registered tools:
12
+
13
+ | Tool | Mode | Description |
14
+ | --- | --- | --- |
15
+ | `TodoWrite` | sequential | Replaces the current task list with up to 100 durable items renumbered from `#1` (clears existing dependency edges). |
16
+ | `TaskCreate` | sequential | Creates a durable work item with `subject`, `description`, optional `activeForm`, and optional `metadata`. |
17
+ | `TaskGet` | parallel | Returns a single task by ID, including status and dependencies. |
18
+ | `TaskList` | parallel | Lists all work items in the active session branch. |
19
+ | `TaskUpdate` | sequential | Updates fields (`subject`, `description`, `activeForm`, `status`, `owner`, merged `metadata`), adds `addBlockedBy` / `addBlocks` dependencies, or deletes a task (`status: "deleted"`). |
20
+
21
+ Dependency rules enforced by `TaskUpdate`:
22
+ - Referenced dependencies must exist.
23
+ - Cycles are rejected before state is mutated.
24
+ - Tasks with incomplete `blockedBy` dependencies cannot transition to `in_progress` or `completed`.
25
+ - Deleting a task removes it from other tasks' `blocks` and `blockedBy` lists.
26
+
27
+ ### Checklist UI & Status Indicator
28
+
29
+ - **Status bar (`compat-tasks`)**: Shows the count of open tasks (cleared when no tasks remain).
30
+ - **TUI widget (`compat-todos`)**: Renders up to 8 tasks ordered `in_progress` → `pending` → `completed`, with status markers (`▶`, `○`, `✔`), optional owner, and dependency badges.
31
+ - **Custom tool rendering**: `TodoWrite`, `TaskCreate`, `TaskUpdate`, `TaskList`, and `TaskGet` provide compact call headers and checklist-formatted results.
32
+
33
+ ### Background Shell Jobs
34
+
35
+ Background jobs run detached via `/bin/bash -c` in the session working directory, with durable job records and log files stored under `~/.local/share/pi-code-compat/<cwd-hash>/<session-hash>/jobs/`.
36
+
37
+ Registered tools:
38
+
39
+ | Tool | Mode | Description |
40
+ | --- | --- | --- |
41
+ | `TaskRun` | sequential | Starts a background shell job with an optional `timeout` (`1`–`3600000` ms, default `600000` ms) and returns its UUID job ID. |
42
+ | `TaskOutput` | parallel | Returns job status and the retained log tail (up to 64 KB). Supports `block: true` polling up to `timeout` (`1`–`30000` ms, default `1000` ms) and abort signals. |
43
+ | `TaskStop` | sequential | Stops a running job (`SIGTERM`, then `SIGKILL` fallback) and retains its output. |
44
+
45
+ Lifecycle & safety:
46
+ - Jobs are stopped cleanly on `session_shutdown`.
47
+ - On `session_start`, `reconcile()` marks any orphaned `running` job records left behind by a crash as `interrupted`.
48
+ - Job completion emits a status message to the session.
49
+ - Output written to disk is capped at 16 MB per job.
50
+
51
+ ## Installation
52
+
53
+ Install the package through pi's package manager or npm using the scoped package name:
54
+
55
+ ```sh
56
+ pi install npm:@pi-kode/tasks
57
+ ```
58
+
59
+ The committed `.npmrc` routes `@pi-kode` packages to the public npm registry (`https://registry.npmjs.org`). Packages are published with public access and require no authentication to install.
60
+
61
+ ## Contributing & Development
62
+
63
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for local setup, running tests and type checks, architecture guidelines, and the release process.
package/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { default } from './lib/src/features/tasks.ts';
@@ -0,0 +1,29 @@
1
+ import { mkdir,readdir,readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { atomicWrite } from '../runtime/utils.ts';
5
+ import { runProcess } from './process.ts';
6
+ export interface Job {id:string;command:string;status:'running'|'completed'|'failed'|'stopped'|'interrupted';outputPath:string;exitCode?:number|null;error?:string}
7
+ export class Jobs {
8
+ private running=new Map<string,{controller:AbortController;done:Promise<void>}>();
9
+ readonly root:string;
10
+ private notify:(job:Job)=>void;
11
+ constructor(root:string,notify:(job:Job)=>void=()=>{}){this.root=root;this.notify=notify;}
12
+ private path(id:string){if(!/^[0-9a-f-]{36}$/.test(id))throw Error('Invalid job ID');return join(this.root,id+'.json');}
13
+ async get(id:string):Promise<Job>{return JSON.parse(await readFile(this.path(id),'utf8'));}
14
+ async reconcile(){await mkdir(this.root,{recursive:true});for(const file of await readdir(this.root)){if(!file.endsWith('.json'))continue;const job=await this.get(file.slice(0,-5));if(job.status==='running'&&!this.running.has(job.id)){job.status='interrupted';await atomicWrite(this.path(job.id),JSON.stringify(job));}}}
15
+ async start(command:string,cwd:string,timeout=600000):Promise<Job>{
16
+ const id=randomUUID();const job:Job={id,command,status:'running',outputPath:join(this.root,id+'.log')};
17
+ await atomicWrite(this.path(id),JSON.stringify(job));const controller=new AbortController();
18
+ const done=(async()=>{
19
+ try{const result=await runProcess('/bin/bash',['-c',command],{cwd,signal:controller.signal,timeout,outputPath:job.outputPath});job.status=result.cancelled?'stopped':result.exitCode===0&&!result.timedOut?'completed':'failed';job.exitCode=result.exitCode;}
20
+ catch(error){job.status=controller.signal.aborted?'stopped':'failed';job.error=String(error);}
21
+ finally{await atomicWrite(this.path(id),JSON.stringify(job));this.running.delete(id);this.notify(job);}
22
+ })();
23
+ // Observe even persistence/notification failures; callers retrieve the durable status.
24
+ done.catch(()=>{});this.running.set(id,{controller,done});return {...job};
25
+ }
26
+ async output(id:string,limit=64000){const job=await this.get(id);let text='';try{const bytes=await readFile(job.outputPath);text=bytes.subarray(Math.max(0,bytes.length-limit)).toString('utf8');}catch(e:any){if(e.code!=='ENOENT')throw e;}return {job,output:text};}
27
+ async stop(id:string){const entry=this.running.get(id);if(entry){entry.controller.abort();await entry.done;}return this.get(id);}
28
+ async close(){await Promise.allSettled([...this.running.values()].map(async e=>{e.controller.abort();await e.done;}));}
29
+ }
@@ -0,0 +1,121 @@
1
+ import { spawn } from 'node:child_process';
2
+ import type { FileHandle } from 'node:fs/promises';
3
+ import { mkdir, open } from 'node:fs/promises';
4
+ import { dirname } from 'node:path';
5
+
6
+ export interface ProcessResult {
7
+ output: string;
8
+ stdout: string;
9
+ stderr: string;
10
+ exitCode: number | null;
11
+ cancelled: boolean;
12
+ timedOut: boolean;
13
+ truncated: boolean;
14
+ outputPath?: string;
15
+ }
16
+
17
+ export async function runProcess(
18
+ command: string,
19
+ args: string[],
20
+ options: {
21
+ cwd: string;
22
+ signal?: AbortSignal;
23
+ timeout?: number;
24
+ input?: string;
25
+ outputPath?: string;
26
+ maxBytes?: number;
27
+ env?: NodeJS.ProcessEnv;
28
+ },
29
+ ): Promise<ProcessResult> {
30
+ options.signal?.throwIfAborted();
31
+ const maxBytes = options.maxBytes ?? 64_000;
32
+ let sink: FileHandle | undefined;
33
+ if (options.outputPath) {
34
+ await mkdir(dirname(options.outputPath), { recursive: true });
35
+ sink = await open(options.outputPath, 'wx', 0o600);
36
+ }
37
+ try {
38
+ return await new Promise<ProcessResult>((resolve, reject) => {
39
+ options.signal?.throwIfAborted();
40
+ const child = spawn(command, args, {
41
+ cwd: options.cwd,
42
+ env: options.env ?? process.env,
43
+ detached: true,
44
+ stdio: ['pipe', 'pipe', 'pipe'],
45
+ });
46
+ let stdout = Buffer.alloc(0);
47
+ let stderr = Buffer.alloc(0);
48
+ let output = Buffer.alloc(0);
49
+ let size = 0;
50
+ let diskSize = 0;
51
+ let timedOut = false;
52
+ let cancelled = false;
53
+ let settled = false;
54
+ let diskWrites = Promise.resolve();
55
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
56
+ const stop = () => {
57
+ try { process.kill(-child.pid!, 'SIGTERM'); } catch {}
58
+ killTimer ??= setTimeout(() => { try { process.kill(-child.pid!, 'SIGKILL'); } catch {} }, 250);
59
+ };
60
+ const onAbort = () => { cancelled = true; stop(); };
61
+ const timer = setTimeout(() => { timedOut = true; stop(); }, options.timeout ?? 120_000);
62
+ options.signal?.addEventListener('abort', onAbort, { once: true });
63
+ const cleanup = () => {
64
+ clearTimeout(timer);
65
+ options.signal?.removeEventListener('abort', onAbort);
66
+ };
67
+ const receive = (chunk: Buffer, stream: 'stdout' | 'stderr') => {
68
+ if (stream === 'stdout' && stdout.length < maxBytes) {
69
+ stdout = Buffer.concat([stdout, chunk.subarray(0, maxBytes - stdout.length)]);
70
+ }
71
+ if (stream === 'stderr' && stderr.length < maxBytes) {
72
+ stderr = Buffer.concat([stderr, chunk.subarray(0, maxBytes - stderr.length)]);
73
+ }
74
+ size += chunk.length;
75
+ if (output.length < maxBytes) {
76
+ output = Buffer.concat([output, chunk.subarray(0, maxBytes - output.length)]);
77
+ }
78
+ if (sink && diskSize < 16_000_000) {
79
+ const bytes = chunk.subarray(0, 16_000_000 - diskSize);
80
+ diskSize += bytes.length;
81
+ diskWrites = diskWrites.then(async () => { await sink!.write(bytes); });
82
+ diskWrites.catch(() => stop());
83
+ }
84
+ if (size > 16_000_000) stop();
85
+ };
86
+ child.stdout.on('data', chunk => receive(chunk, 'stdout'));
87
+ child.stderr.on('data', chunk => receive(chunk, 'stderr'));
88
+ child.stdin.on('error', () => {});
89
+ child.stdin.end(options.input);
90
+ child.on('error', error => {
91
+ if (settled) return;
92
+ settled = true;
93
+ cleanup();
94
+ reject(error);
95
+ });
96
+ child.on('close', async code => {
97
+ if (settled) return;
98
+ settled = true;
99
+ cleanup();
100
+ if (timedOut || cancelled) stop();
101
+ try {
102
+ await diskWrites;
103
+ resolve({
104
+ output: output.toString('utf8'),
105
+ stdout: stdout.toString('utf8'),
106
+ stderr: stderr.toString('utf8'),
107
+ exitCode: code,
108
+ timedOut,
109
+ cancelled,
110
+ truncated: size > maxBytes,
111
+ outputPath: options.outputPath,
112
+ });
113
+ } catch (error) {
114
+ reject(error);
115
+ }
116
+ });
117
+ });
118
+ } finally {
119
+ await sink?.close();
120
+ }
121
+ }
@@ -0,0 +1,149 @@
1
+ import { Type } from 'typebox';
2
+ import type { Task, TasksRuntime } from '../runtime/tasks.ts';
3
+ import { object } from '../runtime/schema.ts';
4
+ import { textResult, taskSummary } from '../runtime/utils.ts';
5
+
6
+ const id = () => Type.String({ pattern: '^[1-9][0-9]*$' });
7
+ const status = () => Type.Union([Type.Literal('pending'), Type.Literal('in_progress'), Type.Literal('completed')]);
8
+
9
+ export function validateGraph(tasks: Record<string, Task>): void {
10
+ const active = new Set<string>();
11
+ const done = new Set<string>();
12
+ function visit(id: string): void {
13
+ if (active.has(id)) throw new Error('Task dependencies would create a cycle');
14
+ if (done.has(id)) return;
15
+ active.add(id);
16
+ for (const dep of tasks[id].blockedBy) {
17
+ if (!tasks[dep]) throw new Error(`Unknown dependency: ${dep}`);
18
+ visit(dep);
19
+ }
20
+ active.delete(id);
21
+ done.add(id);
22
+ }
23
+ for (const id of Object.keys(tasks)) visit(id);
24
+ }
25
+
26
+ export function registerTasks(runtime: TasksRuntime): void {
27
+ runtime.register(
28
+ object({
29
+ todos: Type.Array(
30
+ object({ content: Type.String({ minLength: 1 }), activeForm: Type.String(), status: status() }),
31
+ { maxItems: 100 },
32
+ ),
33
+ }),
34
+ 'TodoWrite',
35
+ 'Replace the current todo list with durable task items. Existing dependency graphs are replaced explicitly.',
36
+ true,
37
+ async input => {
38
+ const tasks: Record<string, Task> = {};
39
+ let index = 0;
40
+ for (const todo of input.todos) {
41
+ const id = String(++index);
42
+ tasks[id] = {
43
+ id,
44
+ subject: todo.content,
45
+ description: todo.content,
46
+ activeForm: todo.activeForm,
47
+ status: todo.status,
48
+ blockedBy: [],
49
+ blocks: [],
50
+ };
51
+ }
52
+ runtime.state.nextTask = index + 1;
53
+ runtime.state.tasks = tasks;
54
+ runtime.persist();
55
+ return textResult(taskSummary(Object.values(tasks)), { tasks });
56
+ },
57
+ );
58
+
59
+ runtime.register(
60
+ object({
61
+ subject: Type.String({ minLength: 1 }),
62
+ description: Type.String(),
63
+ activeForm: Type.Optional(Type.String()),
64
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
65
+ }),
66
+ 'TaskCreate',
67
+ 'Create a durable session-branch work item. Work items are distinct from processes and subagents.',
68
+ true,
69
+ async input => {
70
+ const id = String(runtime.state.nextTask++);
71
+ const task: Task = { ...input, id, status: 'pending', blockedBy: [], blocks: [] };
72
+ runtime.state.tasks[id] = task;
73
+ runtime.persist();
74
+ return textResult(taskSummary([task]), { task });
75
+ },
76
+ );
77
+
78
+ runtime.register(
79
+ object({ taskId: id() }),
80
+ 'TaskGet',
81
+ 'Get a task by ID, including dependencies and status.',
82
+ false,
83
+ async input => {
84
+ const task = runtime.state.tasks[input.taskId];
85
+ if (!task) throw new Error('Task not found');
86
+ return textResult(taskSummary([task]), { task });
87
+ },
88
+ );
89
+
90
+ runtime.register(object({}), 'TaskList', 'List work items in the active session branch.', false, async () => {
91
+ const tasks = Object.values(runtime.state.tasks);
92
+ return textResult(taskSummary(tasks), { tasks });
93
+ });
94
+
95
+ runtime.register(
96
+ object({
97
+ taskId: id(),
98
+ subject: Type.Optional(Type.String({ minLength: 1 })),
99
+ description: Type.Optional(Type.String()),
100
+ activeForm: Type.Optional(Type.String()),
101
+ status: Type.Optional(Type.Union([status(), Type.Literal('deleted')])),
102
+ owner: Type.Optional(Type.String()),
103
+ addBlockedBy: Type.Optional(Type.Array(id())),
104
+ addBlocks: Type.Optional(Type.Array(id())),
105
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
106
+ }),
107
+ 'TaskUpdate',
108
+ 'Update a work item. Dependencies must exist and remain acyclic. Blocked tasks cannot start or complete.',
109
+ true,
110
+ async input => {
111
+ const tasks = structuredClone(runtime.state.tasks);
112
+ const task = tasks[input.taskId];
113
+ if (!task) throw new Error('Task not found');
114
+ if (input.status === 'deleted') {
115
+ delete tasks[task.id];
116
+ for (const item of Object.values(tasks)) {
117
+ item.blocks = item.blocks.filter(id => id !== task.id);
118
+ item.blockedBy = item.blockedBy.filter(id => id !== task.id);
119
+ }
120
+ runtime.state.tasks = tasks;
121
+ runtime.persist();
122
+ return textResult(`Deleted task #${task.id}: ${task.subject}`, { deleted: task.id });
123
+ }
124
+ if (input.metadata) input.metadata = { ...(task.metadata ?? {}), ...input.metadata };
125
+ for (const key of ['subject', 'description', 'activeForm', 'status', 'owner', 'metadata'] as const) {
126
+ if (input[key] !== undefined) (task as any)[key] = input[key];
127
+ }
128
+ for (const dep of input.addBlockedBy ?? []) {
129
+ if (!tasks[dep]) throw new Error(`Unknown dependency: ${dep}`);
130
+ task.blockedBy = [...new Set([...task.blockedBy, dep])];
131
+ tasks[dep].blocks = [...new Set([...tasks[dep].blocks, task.id])];
132
+ }
133
+ for (const child of input.addBlocks ?? []) {
134
+ if (!tasks[child]) throw new Error(`Unknown dependency: ${child}`);
135
+ task.blocks = [...new Set([...task.blocks, child])];
136
+ tasks[child].blockedBy = [...new Set([...tasks[child].blockedBy, task.id])];
137
+ }
138
+ validateGraph(tasks);
139
+ for (const item of Object.values(tasks)) {
140
+ if (item.status !== 'pending' && item.blockedBy.some(dep => tasks[dep].status !== 'completed')) {
141
+ throw new Error('Blocked tasks cannot start or complete');
142
+ }
143
+ }
144
+ runtime.state.tasks = tasks;
145
+ runtime.persist();
146
+ return textResult(taskSummary([task]), { task });
147
+ },
148
+ );
149
+ }
@@ -0,0 +1,100 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { Type } from 'typebox';
3
+ import { join } from 'node:path';
4
+ import { TasksRuntime } from '../runtime/tasks.ts';
5
+ import { registerTasks } from '../extensions/tasks.ts';
6
+ import { Jobs } from '../backends/jobs.ts';
7
+ import { textResult, humanReadable } from '../runtime/utils.ts';
8
+
9
+ const CHANNEL = 'pi-ko:tasks:v1';
10
+
11
+ export default function (pi: ExtensionAPI): void {
12
+ let existing: TasksRuntime | undefined;
13
+ pi.events.emit(CHANNEL, { accept: (value: TasksRuntime) => { existing = value; } });
14
+ if (existing) {
15
+ existing.pi = pi;
16
+ return;
17
+ }
18
+
19
+ const r = new TasksRuntime(pi);
20
+ const unsubscribe = pi.events.on(CHANNEL, (request: any) => request.accept(r));
21
+
22
+ registerTasks(r);
23
+
24
+ let jobs: Jobs | undefined;
25
+ pi.on('session_start', async (_e, ctx) => {
26
+ r.start(ctx);
27
+ await jobs?.close();
28
+ jobs = new Jobs(join(r.store, 'jobs'), job => r.message(`Background job ${job.id}: ${job.status}`));
29
+ await jobs.reconcile();
30
+ });
31
+ pi.on('session_tree', (_e, ctx) => r.start(ctx));
32
+ pi.on('session_shutdown', async e => {
33
+ await jobs?.close();
34
+ r.ready = false;
35
+ if (e.reason === 'reload' || e.reason === 'quit') unsubscribe();
36
+ });
37
+ pi.on('agent_settled', (_e, ctx) => r.status(ctx));
38
+
39
+ pi.on('before_agent_start', () => {
40
+ if (!r.ready) return;
41
+ const tasks = Object.values(r.state.tasks);
42
+ if (!tasks.length) return;
43
+ return {
44
+ message: {
45
+ customType: 'code-compat:tasks',
46
+ content: `Active tasks:\n${JSON.stringify(tasks)}`,
47
+ display: false,
48
+ },
49
+ };
50
+ });
51
+
52
+ const registry = () => {
53
+ if (!jobs) throw Error('Job supervisor is unavailable');
54
+ return jobs;
55
+ };
56
+ const jobId = Type.String({ pattern: '^[0-9a-f-]{36}$' });
57
+
58
+ r.register(
59
+ Type.Object({ command: Type.String({ minLength: 1 }), timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 3600000 })) }, { additionalProperties: false }),
60
+ 'TaskRun',
61
+ 'Start a background shell job. Requires permission. Returns a stable job ID; use TaskOutput and TaskStop. Jobs are stopped on graceful shutdown; crash leftovers are marked interrupted on restart.',
62
+ true,
63
+ async (input, ctx) => {
64
+ const job = await registry().start(input.command, ctx.cwd, input.timeout);
65
+ return textResult(humanReadable(job), { job });
66
+ },
67
+ );
68
+
69
+ r.register(
70
+ Type.Object(
71
+ { task_id: jobId, block: Type.Optional(Type.Boolean()), timeout: Type.Optional(Type.Integer({ minimum: 1, maximum: 30000 })) },
72
+ { additionalProperties: false },
73
+ ),
74
+ 'TaskOutput',
75
+ 'Retrieve retained background job output/status. Optional block waits up to timeout milliseconds (default 1000, maximum 30000).',
76
+ false,
77
+ async (input, _ctx, signal) => {
78
+ const deadline = Date.now() + (input.block ? input.timeout ?? 1000 : 0);
79
+ let result;
80
+ do {
81
+ signal?.throwIfAborted();
82
+ result = await registry().output(input.task_id);
83
+ if (result.job.status !== 'running' || Date.now() >= deadline) break;
84
+ await new Promise(resolve => setTimeout(resolve, Math.min(100, deadline - Date.now())));
85
+ } while (true);
86
+ return textResult(`${humanReadable(result.job)}\n\n${result.output || 'No output yet.'}`, result);
87
+ },
88
+ );
89
+
90
+ r.register(
91
+ Type.Object({ task_id: jobId }, { additionalProperties: false }),
92
+ 'TaskStop',
93
+ 'Stop a running background shell job and retain its output.',
94
+ true,
95
+ async input => {
96
+ const job = await registry().stop(input.task_id);
97
+ return textResult(humanReadable(job), { job });
98
+ },
99
+ );
100
+ }
@@ -0,0 +1,39 @@
1
+ import type { Task } from './tasks.ts';
2
+
3
+ export interface ChecklistComponent {
4
+ render(width: number): string[];
5
+ invalidate(): void;
6
+ }
7
+
8
+ export function checklistHeader(tasks: Task[], theme: any): string {
9
+ const completed = tasks.filter(task => task.status === 'completed').length;
10
+ const done = tasks.length > 0 && completed === tasks.length;
11
+ return `${theme.fg('toolTitle', theme.bold('Tasks'))} ${theme.fg(done ? 'success' : 'muted', `${completed}/${tasks.length}`)}`;
12
+ }
13
+
14
+ export function checklistLines(tasks: Task[], theme: any, opts: { maxRows?: number } = {}): string[] {
15
+ const shown = opts.maxRows !== undefined ? tasks.slice(0, opts.maxRows) : tasks;
16
+ const rows = shown.map(task => {
17
+ const suffix = `${task.owner ? theme.fg('dim', ` · ${task.owner}`) : ''}${
18
+ task.blockedBy.length ? theme.fg('dim', ` · deps: ${task.blockedBy.map(dep => '#' + dep).join(', ')}`) : ''
19
+ }`;
20
+ if (task.status === 'completed') return `${theme.fg('success', '✔')} ${theme.fg('muted', task.subject)}${suffix}`;
21
+ if (task.status === 'in_progress') return `${theme.fg('accent', '▶')} ${theme.fg('text', task.subject)}${suffix}`;
22
+ return `${theme.fg('dim', '○')} ${theme.fg('muted', task.subject)}${suffix}`;
23
+ });
24
+ if (tasks.length > shown.length) rows.push(theme.fg('dim', `… +${tasks.length - shown.length} more (TaskList)`));
25
+ return rows;
26
+ }
27
+
28
+ export function checklistComponent(
29
+ theme: any,
30
+ tasks: Task[],
31
+ opts: { header?: string; footer?: string; maxRows?: number } = {},
32
+ ): ChecklistComponent {
33
+ const lines = [
34
+ opts.header ?? checklistHeader(tasks, theme),
35
+ ...checklistLines(tasks, theme, opts),
36
+ ...(opts.footer ? [theme.fg('dim', opts.footer)] : []),
37
+ ];
38
+ return { render: () => lines, invalidate: () => {} };
39
+ }
@@ -0,0 +1,2 @@
1
+ import { Type } from 'typebox';
2
+ export const object = (properties: any) => Type.Object(properties, { additionalProperties: false });
@@ -0,0 +1,149 @@
1
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from '@earendil-works/pi-coding-agent';
2
+ import type { TSchema } from 'typebox';
3
+ import { Check } from 'typebox/value';
4
+ import { homedir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { hash, textResult } from './utils.ts';
7
+ import { checklistComponent } from './checklist.ts';
8
+
9
+ export interface Task {
10
+ id: string;
11
+ subject: string;
12
+ description: string;
13
+ activeForm?: string;
14
+ status: 'pending' | 'in_progress' | 'completed';
15
+ blockedBy: string[];
16
+ blocks: string[];
17
+ owner?: string;
18
+ metadata?: Record<string, unknown>;
19
+ }
20
+
21
+ export interface TasksState {
22
+ tasks: Record<string, Task>;
23
+ nextTask: number;
24
+ }
25
+
26
+ export const initialTasksState = (): TasksState => ({ tasks: {}, nextTask: 1 });
27
+
28
+ export function restoreTasksState(entries: readonly any[]): TasksState {
29
+ let state = initialTasksState();
30
+ for (const entry of entries) {
31
+ if (entry.type === 'custom' && (entry.customType === 'pk:tasks' || entry.customType === 'cc:tasks') && entry.data) {
32
+ state = {
33
+ tasks: structuredClone(entry.data.tasks ?? {}),
34
+ nextTask: typeof entry.data.nextTask === 'number' ? entry.data.nextTask : 1,
35
+ };
36
+ } else if (entry.type === 'custom' && entry.customType === 'code-compat:state' && entry.data?.tasks) {
37
+ state = {
38
+ tasks: structuredClone(entry.data.tasks),
39
+ nextTask: typeof entry.data.nextTask === 'number' ? entry.data.nextTask : 1,
40
+ };
41
+ }
42
+ }
43
+ return state;
44
+ }
45
+
46
+ export class TasksRuntime {
47
+ pi: ExtensionAPI;
48
+ state: TasksState = initialTasksState();
49
+ store = '';
50
+ ready = false;
51
+ private uiContext?: ExtensionContext;
52
+
53
+ constructor(pi: ExtensionAPI) {
54
+ this.pi = pi;
55
+ }
56
+
57
+ start(ctx: ExtensionContext): void {
58
+ this.state = restoreTasksState(ctx.sessionManager.getBranch());
59
+ this.store = join(
60
+ homedir(),
61
+ '.local/share/pi-code-compat',
62
+ hash(ctx.cwd).slice(0, 24),
63
+ hash(ctx.sessionManager.getSessionId()).slice(0, 24),
64
+ );
65
+ this.ready = true;
66
+ this.status(ctx);
67
+ }
68
+
69
+ persist(): void {
70
+ this.pi.appendEntry('pk:tasks', structuredClone(this.state));
71
+ if (this.uiContext) this.status(this.uiContext);
72
+ }
73
+
74
+ status(ctx: ExtensionContext): void {
75
+ this.uiContext = ctx;
76
+ const tasks = Object.values(this.state.tasks);
77
+ const open = tasks.filter(t => t.status !== 'completed').length;
78
+ ctx.ui.setStatus('compat-tasks', tasks.length ? `${open} open tasks` : undefined);
79
+ if (ctx.hasUI) {
80
+ const ordered = [
81
+ ...tasks.filter(task => task.status === 'in_progress'),
82
+ ...tasks.filter(task => task.status === 'pending'),
83
+ ...tasks.filter(task => task.status === 'completed'),
84
+ ];
85
+ ctx.ui.setWidget?.(
86
+ 'compat-todos',
87
+ tasks.length ? (_tui: any, theme: any) => checklistComponent(theme, ordered, { maxRows: 8 }) : undefined,
88
+ );
89
+ }
90
+ }
91
+
92
+ message(content: string): void {
93
+ this.pi.sendMessage({ customType: 'code-compat', content, display: true });
94
+ }
95
+
96
+ register(
97
+ schema: TSchema,
98
+ name: string,
99
+ description: string,
100
+ write: boolean,
101
+ backend: (input: any, ctx: ExtensionContext, signal?: AbortSignal) => Promise<ReturnType<typeof textResult>>,
102
+ ): void {
103
+ const tool: ToolDefinition<any, any> = {
104
+ name,
105
+ label: name,
106
+ description,
107
+ parameters: schema,
108
+ executionMode: write ? 'sequential' : 'parallel',
109
+ execute: async (_id, raw, signal, _update, ctx) => {
110
+ if (!this.ready) throw new Error('Tasks runtime is unavailable');
111
+ const input: any = structuredClone(raw);
112
+ if (!Check(schema, input)) throw new Error(`Invalid ${name} input`);
113
+ const result = await backend(input, ctx, signal);
114
+ this.status(ctx);
115
+ return result;
116
+ },
117
+ };
118
+ if (['TodoWrite', 'TaskCreate', 'TaskUpdate', 'TaskList', 'TaskGet'].includes(name)) {
119
+ tool.renderCall = (args: any, theme: any) => {
120
+ const summary =
121
+ name === 'TodoWrite'
122
+ ? `${args?.todos?.length ?? 0} items`
123
+ : typeof args?.taskId === 'string'
124
+ ? `#${args.taskId}`
125
+ : typeof args?.subject === 'string'
126
+ ? args.subject
127
+ : '';
128
+ return {
129
+ render: () => [`${theme.fg('toolTitle', theme.bold(name))}${summary ? ` ${theme.fg('muted', summary)}` : ''}`],
130
+ invalidate: () => {},
131
+ };
132
+ };
133
+ tool.renderResult = (result: any, options: any, theme: any) => {
134
+ const tasks: Task[] = result?.details?.tasks ?? (result?.details?.task ? [result.details.task] : []);
135
+ if (tasks.length) return checklistComponent(theme, tasks, { maxRows: options?.expanded ? undefined : 10 });
136
+ const text = (result?.content ?? [])
137
+ .filter((block: any) => block.type === 'text')
138
+ .map((block: any) => block.text)
139
+ .join('\n')
140
+ .trim();
141
+ return {
142
+ render: () => (text ? text.split('\n').map((line: string) => theme.fg('toolOutput', line)) : []),
143
+ invalidate: () => {},
144
+ };
145
+ };
146
+ }
147
+ this.pi.registerTool(tool);
148
+ }
149
+ }
@@ -0,0 +1,61 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, rename, rm, writeFile, stat } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+
5
+ export const hash = (value: string | Buffer) => createHash('sha256').update(value).digest('hex');
6
+
7
+ export async function atomicWrite(file: string, contents: string | Buffer): Promise<void> {
8
+ await mkdir(dirname(file), { recursive: true });
9
+ const temp = `${file}.${randomUUID()}.tmp`;
10
+ let mode = 0o600;
11
+ try {
12
+ mode = (await stat(file)).mode & 0o777;
13
+ } catch (error: any) {
14
+ if (error.code !== 'ENOENT') throw error;
15
+ }
16
+ try {
17
+ await writeFile(temp, contents, { mode, flag: 'wx' });
18
+ await rename(temp, file);
19
+ } finally {
20
+ await rm(temp, { force: true });
21
+ }
22
+ }
23
+
24
+ export const textResult = (text: string, details: Record<string, unknown> = {}) => ({
25
+ content: [{ type: 'text' as const, text }],
26
+ details,
27
+ });
28
+
29
+ export function humanReadable(value: unknown, indent = ''): string {
30
+ if (value === null || value === undefined) return 'None';
31
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
32
+ if (typeof value !== 'object') return String(value);
33
+ const entries = Array.isArray(value)
34
+ ? value.map((item, index) => [String(index + 1), item] as const)
35
+ : Object.entries(value);
36
+ if (!entries.length) return 'None';
37
+ return entries
38
+ .map(([key, item]) => {
39
+ const label = key.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/_/g, ' ');
40
+ return item !== null && typeof item === 'object'
41
+ ? `${indent}${label}:\n${humanReadable(item, indent + ' ')}`
42
+ : `${indent}${label}: ${humanReadable(item)}`;
43
+ })
44
+ .join('\n');
45
+ }
46
+
47
+ export function taskSummary(
48
+ tasks: { id: string; subject: string; status: string; blockedBy: string[]; owner?: string; description?: string }[],
49
+ ): string {
50
+ if (!tasks.length) return 'No tasks.';
51
+ const completed = tasks.filter(task => task.status === 'completed').length;
52
+ return [
53
+ `Tasks — ${completed}/${tasks.length} completed`,
54
+ ...tasks.map(task => {
55
+ const marker = task.status === 'completed' ? '✓' : task.status === 'in_progress' ? '→' : '○';
56
+ return `${marker} #${task.id} ${task.subject} (${task.status.replace(/_/g, ' ')})${task.owner ? ` · ${task.owner}` : ''}${
57
+ task.blockedBy.length ? ` · dependencies: ${task.blockedBy.map(id => '#' + id).join(', ')}` : ''
58
+ }${task.description && task.description !== task.subject ? `\n ${task.description}` : ''}`;
59
+ }),
60
+ ].join('\n');
61
+ }
package/package.json CHANGED
@@ -1,5 +1,42 @@
1
1
  {
2
2
  "name": "@pi-kode/tasks",
3
- "version": "0.0.0-init",
4
- "description": "Bootstrap placeholder for npm Trusted Publishing setup"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "description": "Standalone pi extension: tasks, todo checklist UI, and background jobs",
9
+ "files": [
10
+ "index.ts",
11
+ "lib",
12
+ "tests",
13
+ "tsconfig.json"
14
+ ],
15
+ "pi": {
16
+ "extensions": [
17
+ "./index.ts"
18
+ ]
19
+ },
20
+ "peerDependencies": {
21
+ "@earendil-works/pi-coding-agent": "1.5.2",
22
+ "typebox": "1.3.27"
23
+ },
24
+ "scripts": {
25
+ "test": "node --experimental-strip-types --test tests/*.test.ts",
26
+ "typecheck": "tsc --noEmit",
27
+ "prepublishOnly": "npm test && npm run typecheck"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "22.19.19",
31
+ "typescript": "5.9.3"
32
+ },
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/pi-kode/tasks.git"
36
+ },
37
+ "homepage": "https://github.com/pi-kode/tasks#readme",
38
+ "bugs": "https://github.com/pi-kode/tasks/issues",
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
5
42
  }
@@ -0,0 +1,72 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
5
+
6
+ export async function harness(install: (pi: ExtensionAPI) => void) {
7
+ const root = await mkdtemp(join(tmpdir(), 'pi-feature-'));
8
+ const handlers = new Map<string, any[]>();
9
+ const tools = new Map<string, any>();
10
+ const commands = new Map<string, any>();
11
+ const listeners = new Map<string, any[]>();
12
+ const entries: any[] = [];
13
+ const answers: any[] = [];
14
+ const pi: any = {
15
+ events: {
16
+ emit: (name: string, data: any) => {
17
+ for (const fn of listeners.get(name) ?? []) fn(data);
18
+ },
19
+ on: (name: string, fn: any) => {
20
+ listeners.set(name, [...(listeners.get(name) ?? []), fn]);
21
+ return () => {};
22
+ },
23
+ },
24
+ on: (name: string, fn: any) => {
25
+ handlers.set(name, [...(handlers.get(name) ?? []), fn]);
26
+ return () => {};
27
+ },
28
+ registerTool: (tool: any) => tools.set(tool.name, tool),
29
+ registerCommand: (name: string, value: any) => commands.set(name, value),
30
+ appendEntry: (customType: string, data: any) =>
31
+ entries.push({ type: 'custom', customType, data: structuredClone(data) }),
32
+ sendMessage: () => {},
33
+ getActiveTools: () => ['read', 'bash'],
34
+ getAllTools: () => [],
35
+ };
36
+ install(pi);
37
+ let runtime: any;
38
+ pi.events.emit('pi-ko:tasks:v1', { accept: (s: any) => (runtime = s) });
39
+ const ctx: any = {
40
+ model: { provider: 'mock', id: 'mock' },
41
+ cwd: root,
42
+ hasUI: true,
43
+ mode: 'tui',
44
+ isProjectTrusted: () => true,
45
+ getSystemPrompt: () => 'Test assistant',
46
+ sessionManager: { getBranch: () => entries, getSessionId: () => 'test' },
47
+ ui: { select: async () => answers.shift() ?? 'Allow once', setStatus: () => {}, notify: () => {} },
48
+ };
49
+ runtime.store = join(root, '.runtime');
50
+ runtime.ready = true;
51
+ return {
52
+ root,
53
+ tools,
54
+ commands,
55
+ runtime,
56
+ ctx,
57
+ entries,
58
+ handlers,
59
+ answers,
60
+ pi,
61
+ call: (name: string, input: any, signal?: AbortSignal) => tools.get(name).execute('call', input, signal, undefined, ctx),
62
+ async emit(name: string, event: any = {}) {
63
+ const results = [];
64
+ for (const fn of handlers.get(name) ?? []) results.push(await fn(event, ctx));
65
+ return results;
66
+ },
67
+ async close() {
68
+ for (const fn of handlers.get('session_shutdown') ?? []) await fn({ reason: 'quit' }, ctx);
69
+ await rm(root, { recursive: true, force: true });
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,40 @@
1
+ import {test} from 'node:test';import assert from 'node:assert/strict';import install from '../lib/src/features/tasks.ts';import {harness} from './helper.ts';
2
+ test('task dependency cycles, readiness, metadata merge, deletion and TodoWrite',async t=>{
3
+ const h=await harness(install);t.after(()=>h.close());
4
+ await h.call('TaskCreate',{subject:'first',description:'one',metadata:{keep:1}});await h.call('TaskCreate',{subject:'second',description:'two'});
5
+ await h.call('TaskUpdate',{taskId:'2',addBlockedBy:['1']});await assert.rejects(h.call('TaskUpdate',{taskId:'1',addBlockedBy:['2']}),/cycle/);
6
+ await assert.rejects(h.call('TaskUpdate',{taskId:'2',status:'completed'}),/Blocked/);
7
+ await h.call('TaskUpdate',{taskId:'1',metadata:{extra:2}});assert.deepEqual(h.runtime.state.tasks['1'].metadata,{keep:1,extra:2});
8
+ await h.call('TaskUpdate',{taskId:'1',status:'deleted'});assert.deepEqual(h.runtime.state.tasks['2'].blockedBy,[]);
9
+ await h.call('TodoWrite',{todos:[{content:'final',activeForm:'Finishing',status:'in_progress'}]});assert.equal(Object.values(h.runtime.state.tasks).length,1);
10
+ });
11
+ test('background output retained, failed status, stop and startup reconciliation',async t=>{
12
+ const h=await harness(install);t.after(()=>h.close());await h.emit('session_start');
13
+ const started=await h.call('TaskRun',{command:'printf hello; exit 3'});const id=started.details.job.id;
14
+ const output=await h.call('TaskOutput',{task_id:id,block:true,timeout:5000});assert.equal(output.details.job.status,'failed');assert.match(output.details.output,/hello/);
15
+ const sleeping=await h.call('TaskRun',{command:'sleep 30'});const stop=await h.call('TaskStop',{task_id:sleeping.details.job.id});assert.equal(stop.details.job.status,'stopped');
16
+ await assert.rejects(h.call('TaskOutput',{task_id:'../../secret'}),/Invalid/);
17
+ });
18
+ test('startup marks orphaned job records interrupted',async t=>{
19
+ const {Jobs}=await import('../lib/src/backends/jobs.ts');const {mkdir,writeFile}=await import('node:fs/promises');const {join}=await import('node:path');
20
+ const h=await harness(install);t.after(()=>h.close());const root=join(h.root,'orphaned');await mkdir(root);
21
+ const id='12345678-1234-1234-1234-123456789012';await writeFile(join(root,id+'.json'),JSON.stringify({id,command:'lost',status:'running',outputPath:join(root,'output')}));
22
+ const registry=new Jobs(root);await registry.reconcile();assert.equal((await registry.get(id)).status,'interrupted');
23
+ });
24
+ test('todo UI updates with progress and clears after deletion',async t=>{
25
+ const h=await harness(install);t.after(()=>h.close());
26
+ const theme={fg:(_color:string,text:string)=>text,bold:(text:string)=>text};
27
+ let widget:any;h.ctx.ui.setWidget=(key:string,content:any)=>{assert.equal(key,'compat-todos');widget=content;};
28
+ const lines=()=>typeof widget==='function'?widget({},theme).render(80).join('\n'):undefined;
29
+ h.runtime.status(h.ctx);assert.equal(widget,undefined);
30
+ const result=await h.call('TodoWrite',{todos:[{content:'Build UI',activeForm:'Building UI',status:'in_progress'}]});
31
+ assert.match(result.content[0].text,/→ #1 Build UI/);assert.match(lines()!,/Tasks 0\/1/);assert.match(lines()!,/▶ Build UI/);
32
+ await h.call('TaskUpdate',{taskId:'1',status:'completed'});assert.match(lines()!,/✔ Build UI/);assert.match(lines()!,/Tasks 1\/1/);
33
+ await h.call('TaskUpdate',{taskId:'1',status:'deleted'});assert.equal(widget,undefined);
34
+ });
35
+ test('TodoWrite renumbers items from 1 on every call',async t=>{
36
+ const h=await harness(install);t.after(()=>h.close());
37
+ await h.call('TodoWrite',{todos:[{content:'a',activeForm:'A',status:'pending'},{content:'b',activeForm:'B',status:'pending'}]});
38
+ const again=await h.call('TodoWrite',{todos:[{content:'c',activeForm:'C',status:'in_progress'}]});
39
+ assert.deepEqual(Object.keys(h.runtime.state.tasks),['1']);assert.equal(h.runtime.state.nextTask,2);assert.match(again.content[0].text,/→ #1 c/);
40
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2023",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "allowImportingTsExtensions": true,
9
+ "skipLibCheck": true,
10
+ "types": [
11
+ "node"
12
+ ]
13
+ },
14
+ "include": [
15
+ "index.ts",
16
+ "lib/**/*.ts",
17
+ "tests/**/*.ts"
18
+ ]
19
+ }