@agimon-ai/po-task 0.0.0-alpha.3 → 0.0.0-alpha.4
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 +8 -8
- package/dist/apiContracts.d.mts +18 -18
- package/dist/{config-CdX-Bv8q.cjs → config-BC-bztyx.cjs} +8 -8
- package/dist/config-BC-bztyx.cjs.map +1 -0
- package/dist/{config-CFSs3iku.mjs → config-BTadoGeF.mjs} +8 -8
- package/dist/config-BTadoGeF.mjs.map +1 -0
- package/dist/config.cjs +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/config.mjs +1 -1
- package/dist/{delegation-CdMqOZB4.mjs → delegation-Dsqf7fUM.mjs} +11 -11
- package/dist/delegation-Dsqf7fUM.mjs.map +1 -0
- package/dist/{delegation-DsnKjMbJ.cjs → delegation-frvEXhIz.cjs} +10 -10
- package/dist/delegation-frvEXhIz.cjs.map +1 -0
- package/dist/delegationManager.cjs +1 -1
- package/dist/delegationManager.d.mts +1 -1
- package/dist/delegationManager.mjs +1 -1
- package/dist/extensions/mcp-ui.mjs.map +1 -1
- package/dist/extensions/mcp.cjs +23 -23
- package/dist/extensions/mcp.cjs.map +1 -1
- package/dist/extensions/mcp.d.mts +1 -1
- package/dist/extensions/mcp.mjs +23 -23
- package/dist/extensions/mcp.mjs.map +1 -1
- package/dist/extensions/server.cjs +14 -14
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.mts +1 -1
- package/dist/extensions/server.mjs +18 -18
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +28 -28
- package/dist/extensions/web.mjs.map +1 -1
- package/dist/{index-teIf67qQ.d.mts → index-B9QNwUBr.d.mts} +8 -8
- package/dist/{index-teIf67qQ.d.mts.map → index-B9QNwUBr.d.mts.map} +1 -1
- package/dist/{index-B-3sCF2S.d.mts → index-BsZ8DxpJ.d.mts} +7 -7
- package/dist/{index-B-3sCF2S.d.mts.map → index-BsZ8DxpJ.d.mts.map} +1 -1
- package/dist/{index-XY9VPmfm.d.mts → index-CA4Opp4r.d.mts} +2 -2
- package/dist/{index-XY9VPmfm.d.mts.map → index-CA4Opp4r.d.mts.map} +1 -1
- package/dist/{index-Dvb8X_qB.d.mts → index-qQGWsPum.d.mts} +2 -2
- package/dist/index-qQGWsPum.d.mts.map +1 -0
- package/dist/index.cjs +4 -4
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +4 -4
- package/dist/{logSinkTelemetry-B23qGiP-.cjs → logSinkTelemetry-BGb8WQBz.cjs} +4 -4
- package/dist/logSinkTelemetry-BGb8WQBz.cjs.map +1 -0
- package/dist/{logSinkTelemetry-BMBsC54p.mjs → logSinkTelemetry-BhbKdn-x.mjs} +5 -5
- package/dist/logSinkTelemetry-BhbKdn-x.mjs.map +1 -0
- package/dist/logSinkTelemetry.cjs +2 -2
- package/dist/logSinkTelemetry.d.mts +3 -3
- package/dist/logSinkTelemetry.mjs +2 -2
- package/dist/{paths-Cah1vFGv.mjs → paths-DajceJig.mjs} +4 -4
- package/dist/paths-DajceJig.mjs.map +1 -0
- package/dist/{paths-CSya2l9_.cjs → paths-P-XvOUuH.cjs} +4 -4
- package/dist/paths-P-XvOUuH.cjs.map +1 -0
- package/dist/storePaths.cjs +1 -1
- package/dist/storePaths.d.mts +1 -1
- package/dist/storePaths.mjs +1 -1
- package/dist/storeTaskStore.cjs +1 -1
- package/dist/storeTaskStore.d.mts +1 -1
- package/dist/storeTaskStore.mjs +1 -1
- package/dist/{task-Dhta7JyA.d.mts → task-4HeGAS8o.d.mts} +6 -6
- package/dist/{task-Dhta7JyA.d.mts.map → task-4HeGAS8o.d.mts.map} +1 -1
- package/dist/{taskStore-pAJ971Ml.mjs → taskStore-BAi54FKL.mjs} +4 -4
- package/dist/{taskStore-pAJ971Ml.mjs.map → taskStore-BAi54FKL.mjs.map} +1 -1
- package/dist/{taskStore-DjU60rMm.cjs → taskStore-C4vcUOzA.cjs} +4 -4
- package/dist/{taskStore-DjU60rMm.cjs.map → taskStore-C4vcUOzA.cjs.map} +1 -1
- package/dist/telemetry-DYfgUFF8.d.mts +35 -0
- package/dist/telemetry-DYfgUFF8.d.mts.map +1 -0
- package/dist/telemetry-gEGWTaMI.mjs +25 -0
- package/dist/telemetry-gEGWTaMI.mjs.map +1 -0
- package/dist/telemetry-x3JxCA5K.cjs +30 -0
- package/dist/telemetry-x3JxCA5K.cjs.map +1 -0
- package/dist/toolPromptGuidelines.cjs +1 -1
- package/dist/toolPromptGuidelines.cjs.map +1 -1
- package/dist/toolPromptGuidelines.mjs +1 -1
- package/dist/toolPromptGuidelines.mjs.map +1 -1
- package/dist/toolSchema.d.mts +1 -1
- package/package.json +15 -15
- package/dist/config-CFSs3iku.mjs.map +0 -1
- package/dist/config-CdX-Bv8q.cjs.map +0 -1
- package/dist/delegation-CdMqOZB4.mjs.map +0 -1
- package/dist/delegation-DsnKjMbJ.cjs.map +0 -1
- package/dist/index-Dvb8X_qB.d.mts.map +0 -1
- package/dist/logSinkTelemetry-B23qGiP-.cjs.map +0 -1
- package/dist/logSinkTelemetry-BMBsC54p.mjs.map +0 -1
- package/dist/paths-CSya2l9_.cjs.map +0 -1
- package/dist/paths-Cah1vFGv.mjs.map +0 -1
- package/dist/telemetry-Ca0I3Tqo.cjs +0 -30
- package/dist/telemetry-Ca0I3Tqo.cjs.map +0 -1
- package/dist/telemetry-DyS44zAD.mjs +0 -25
- package/dist/telemetry-DyS44zAD.mjs.map +0 -1
- package/dist/telemetry-FMGRovb4.d.mts +0 -35
- package/dist/telemetry-FMGRovb4.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logSinkTelemetry-BhbKdn-x.mjs","names":[],"sources":["../src/services/logSinkTelemetry/index.ts"],"sourcesContent":["import { createPoTelemetry, type PoTelemetry, type PoTelemetryOptions } from '@agimon-ai/po-telemetry';\n\nimport { TASK_EVENT, type TaskErrorAttributes, type TaskFailureReporter } from '../../types/telemetry';\n\nexport {\n TASK_EVENT,\n type TaskErrorAttributes,\n type TaskErrorSink,\n type TaskEventName,\n type TaskEventSink,\n type TaskFailureReporter,\n} from '../../types/telemetry';\n\nconst SERVICE_NAME = 'po-task';\nconst PACKAGE_NAME = '@agimon-ai/po-task';\nconst NOTIFICATION_OPERATION = 'completion_notification';\n\nexport interface TaskErrorReporterOptions {\n cwd?: string;\n workspaceRoot?: string;\n env?: NodeJS.ProcessEnv;\n telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;\n warn?: (message: string) => void;\n}\n\nexport interface TaskErrorReporter {\n recordError(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordWarning(event: string, error: unknown, attributes?: TaskErrorAttributes): Promise<void>;\n recordEvent(event: string, attributes?: TaskErrorAttributes): Promise<void>;\n recordNotificationError(error: unknown, taskId: number): Promise<void>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport function createTaskErrorReporter(options: TaskErrorReporterOptions = {}): TaskErrorReporter {\n const telemetry: PoTelemetry = createPoTelemetry({\n serviceName: SERVICE_NAME,\n packageName: PACKAGE_NAME,\n cwd: options.cwd,\n workspaceRoot: options.workspaceRoot,\n env: options.env,\n telemetryFactory: options.telemetryFactory,\n warn: options.warn,\n enableLogs: true,\n enableTraces: true,\n });\n return {\n recordError: (event, error, attributes) => telemetry.recordError(event, error, attributes),\n recordWarning: (event, error, attributes) => telemetry.recordWarning(event, error, attributes),\n recordEvent: (event, attributes) => telemetry.recordEvent(event, attributes),\n recordNotificationError: (error, taskId) =>\n telemetry.recordError(TASK_EVENT.notificationFailed, error, {\n 'task.id': taskId,\n 'task.operation': NOTIFICATION_OPERATION,\n }),\n flush: () => telemetry.flush(),\n shutdown: () => telemetry.shutdown(),\n };\n}\n\nexport function toFailureReporter(reporter: TaskErrorReporter): TaskFailureReporter {\n return {\n error: (event, error, attributes) => void reporter.recordError(event, error, attributes),\n warn: (event, error, attributes) => void reporter.recordWarning(event, error, attributes),\n event: (event, attributes) => void reporter.recordEvent(event, attributes),\n };\n}\n"],"mappings":";;;AAaA,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,yBAAyB;AAmB/B,SAAgB,wBAAwB,UAAoC,CAAC,GAAsB;CACjG,MAAM,YAAyB,kBAAkB;EAC/C,aAAa;EACb,aAAa;EACb,KAAK,QAAQ;EACb,eAAe,QAAQ;EACvB,KAAK,QAAQ;EACb,kBAAkB,QAAQ;EAC1B,MAAM,QAAQ;EACd,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO;EACL,cAAc,OAAO,OAAO,eAAe,UAAU,YAAY,OAAO,OAAO,UAAU;EACzF,gBAAgB,OAAO,OAAO,eAAe,UAAU,cAAc,OAAO,OAAO,UAAU;EAC7F,cAAc,OAAO,eAAe,UAAU,YAAY,OAAO,UAAU;EAC3E,0BAA0B,OAAO,WAC/B,UAAU,YAAY,WAAW,oBAAoB,OAAO;GAC1D,WAAW;GACX,kBAAkB;EACpB,CAAC;EACH,aAAa,UAAU,MAAM;EAC7B,gBAAgB,UAAU,SAAS;CACrC;AACF;AAEA,SAAgB,kBAAkB,UAAkD;CAClF,OAAO;EACL,QAAQ,OAAO,OAAO,eAAe,KAAK,SAAS,YAAY,OAAO,OAAO,UAAU;EACvF,OAAO,OAAO,OAAO,eAAe,KAAK,SAAS,cAAc,OAAO,OAAO,UAAU;EACxF,QAAQ,OAAO,eAAe,KAAK,SAAS,YAAY,OAAO,UAAU;CAC3E;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_telemetry = require("./telemetry-
|
|
3
|
-
const require_logSinkTelemetry = require("./logSinkTelemetry-
|
|
2
|
+
const require_telemetry = require("./telemetry-x3JxCA5K.cjs");
|
|
3
|
+
const require_logSinkTelemetry = require("./logSinkTelemetry-BGb8WQBz.cjs");
|
|
4
4
|
exports.TASK_EVENT = require_telemetry.TASK_EVENT;
|
|
5
5
|
exports.createTaskErrorReporter = require_logSinkTelemetry.createTaskErrorReporter;
|
|
6
6
|
exports.toFailureReporter = require_logSinkTelemetry.toFailureReporter;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { a as TaskEventSink, i as TaskEventName, n as TaskErrorAttributes, o as TaskFailureReporter, r as TaskErrorSink, t as TASK_EVENT } from "./telemetry-
|
|
2
|
-
import {
|
|
1
|
+
import { a as TaskEventSink, i as TaskEventName, n as TaskErrorAttributes, o as TaskFailureReporter, r as TaskErrorSink, t as TASK_EVENT } from "./telemetry-DYfgUFF8.mjs";
|
|
2
|
+
import { PoTelemetryOptions } from "@agimon-ai/po-telemetry";
|
|
3
3
|
//#region src/services/logSinkTelemetry/index.d.ts
|
|
4
4
|
export interface TaskErrorReporterOptions {
|
|
5
5
|
cwd?: string;
|
|
6
6
|
workspaceRoot?: string;
|
|
7
7
|
env?: NodeJS.ProcessEnv;
|
|
8
|
-
telemetryFactory?: NonNullable<
|
|
8
|
+
telemetryFactory?: NonNullable<PoTelemetryOptions['telemetryFactory']>;
|
|
9
9
|
warn?: (message: string) => void;
|
|
10
10
|
}
|
|
11
11
|
export interface TaskErrorReporter {
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as TASK_EVENT } from "./telemetry-
|
|
2
|
-
import { n as toFailureReporter, t as createTaskErrorReporter } from "./logSinkTelemetry-
|
|
1
|
+
import { t as TASK_EVENT } from "./telemetry-gEGWTaMI.mjs";
|
|
2
|
+
import { n as toFailureReporter, t as createTaskErrorReporter } from "./logSinkTelemetry-BhbKdn-x.mjs";
|
|
3
3
|
export { TASK_EVENT, createTaskErrorReporter, toFailureReporter };
|
|
@@ -4,8 +4,8 @@ import path from "node:path";
|
|
|
4
4
|
import { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from "@agimon-ai/po-core/childProcess";
|
|
5
5
|
import { piAgentDirectory } from "@agimon-ai/po-core/piSettings";
|
|
6
6
|
//#region src/services/paths/index.ts
|
|
7
|
-
const STORE_PATH_ENV = "
|
|
8
|
-
const STORE_DIR_NAME = "
|
|
7
|
+
const STORE_PATH_ENV = "PO_TASK_STORE";
|
|
8
|
+
const STORE_DIR_NAME = "po-task";
|
|
9
9
|
const STORE_FILE_NAME = "tasks.json";
|
|
10
10
|
const FILE_ENCODING = "utf8";
|
|
11
11
|
const NOT_FOUND_ERROR_CODE = "ENOENT";
|
|
@@ -56,7 +56,7 @@ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey =
|
|
|
56
56
|
const override = env[STORE_PATH_ENV]?.trim();
|
|
57
57
|
if (override) return path.resolve(override);
|
|
58
58
|
const trimmedSessionKey = sessionKey.trim();
|
|
59
|
-
if (!trimmedSessionKey) throw new Error("
|
|
59
|
+
if (!trimmedSessionKey) throw new Error("po-task session id cannot be blank");
|
|
60
60
|
return path.join(piAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
|
|
61
61
|
}
|
|
62
62
|
/** Whether a deliberate unscoped task-store override is active. */
|
|
@@ -204,4 +204,4 @@ function tempPathFor(storePath, pid = process.pid) {
|
|
|
204
204
|
//#endregion
|
|
205
205
|
export { removeLegacyStoreDirectoryAsync as a, resolveSessionKey as c, sweepStoreFilesAsync as d, tempPathFor as f, removeLegacyStoreDirectory as i, resolveStorePath as l, hasStorePathOverride as n, resolveLegacyStoreDirectory as o, lockPathFor as r, resolveLegacyStoreDirectoryAsync as s, STORE_PATH_ENV as t, sweepStoreFiles as u };
|
|
206
206
|
|
|
207
|
-
//# sourceMappingURL=paths-
|
|
207
|
+
//# sourceMappingURL=paths-DajceJig.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths-DajceJig.mjs","names":[],"sources":["../src/services/paths/index.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/po-core/childProcess';\nimport { piAgentDirectory } from '@agimon-ai/po-core/piSettings';\n\nexport const STORE_PATH_ENV = 'PO_TASK_STORE';\n\nconst STORE_DIR_NAME = 'po-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n rootSessionId: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: Readonly<Record<string, string | undefined>> = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('po-task session id cannot be blank');\n return path.join(piAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":";;;;;;AAOA,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAgB,KAAiC;CAC5D,IAAI;EAMF,MAAM,UALS,aAAa,OAAO,MAAM;GACvC;GACA,UAAU;GACV,OAAO;IAAC;IAAU;IAAQ;GAAQ;EACpC,CACqB,CAAC,CAAC,KAAK;EAC5B,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;CACxC,QAAQ;EACN;CACF;AACF;AAEA,eAAe,SAAS,MAAgB,KAA0C;CAChF,OAAO,IAAI,SAAS,YAAY;EAC9B,SAAS,OAAO,MAAM;GAAE;GAAK,UAAU;EAAc,IAAI,OAAO,WAAW;GACzE,IAAI,OAAO;IACT,QAAQ,KAAA,CAAS;IACjB;GACF;GACA,MAAM,UAAU,OAAO,KAAK;GAC5B,QAAQ,QAAQ,SAAS,IAAI,UAAU,KAAA,CAAS;EAClD,CAAC;CACH,CAAC;AACH;AAEA,SAAS,SAAS,MAAc,WAA4B;CAC1D,MAAM,WAAW,KAA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,qBAAqB,yBAAyB;EAClD,IAAI;GACF,MAAM,GAAG,SAAS,OAAO,SAAS;GAClC,IAAI;IACF,MAAM,GAAG,SAAS,OAAO,YAAY,SAAS,CAAC;IAC/C;GACF,SAAS,OAAO;IACd,IAAK,MAAgC,SAAS,sBAAsB,MAAM;GAC5E;GACA,KAAK,MAAM,MAAM,GAAG,SAAS,SAAS,WAAW,aAAa,CAAC;GAC/D,IAAI,OAAO,MAAM,GAAG,SAAS,KAAK,SAAS,EAAA,CAAG,WAAW,OAAO;GAChE,MAAM,GAAG,SAAS,GAAG,kBAAkB;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACvE,OAAO,QAAQ,KAAK,gBAAgB;EACtC,SAAS,OAAO;GACd,IAAK,MAAgC,SAAS,sBAAsB;GACpE,OAAO,OAAO,KAAK,8BAA8B,UAAU,IAAI,OAAO,KAAK,GAAG;EAChF;CACF;CACA,OAAO;AACT;AAEA,SAAgB,YAAY,WAA2B;CACrD,OAAO,GAAG,UAAU;AACtB;AAEA,SAAgB,YAAY,WAAmB,MAAc,QAAQ,KAAa;CAChF,OAAO,GAAG,UAAU,OAAO;AAC7B"}
|
|
@@ -28,8 +28,8 @@ node_path = __toESM(node_path, 1);
|
|
|
28
28
|
let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
|
|
29
29
|
let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
|
|
30
30
|
//#region src/services/paths/index.ts
|
|
31
|
-
const STORE_PATH_ENV = "
|
|
32
|
-
const STORE_DIR_NAME = "
|
|
31
|
+
const STORE_PATH_ENV = "PO_TASK_STORE";
|
|
32
|
+
const STORE_DIR_NAME = "po-task";
|
|
33
33
|
const STORE_FILE_NAME = "tasks.json";
|
|
34
34
|
const FILE_ENCODING = "utf8";
|
|
35
35
|
const NOT_FOUND_ERROR_CODE = "ENOENT";
|
|
@@ -80,7 +80,7 @@ function resolveStorePath(_cwd = process.cwd(), env = process.env, sessionKey =
|
|
|
80
80
|
const override = env[STORE_PATH_ENV]?.trim();
|
|
81
81
|
if (override) return node_path.default.resolve(override);
|
|
82
82
|
const trimmedSessionKey = sessionKey.trim();
|
|
83
|
-
if (!trimmedSessionKey) throw new Error("
|
|
83
|
+
if (!trimmedSessionKey) throw new Error("po-task session id cannot be blank");
|
|
84
84
|
return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);
|
|
85
85
|
}
|
|
86
86
|
/** Whether a deliberate unscoped task-store override is active. */
|
|
@@ -305,4 +305,4 @@ Object.defineProperty(exports, "tempPathFor", {
|
|
|
305
305
|
}
|
|
306
306
|
});
|
|
307
307
|
|
|
308
|
-
//# sourceMappingURL=paths-
|
|
308
|
+
//# sourceMappingURL=paths-P-XvOUuH.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths-P-XvOUuH.cjs","names":["execFileSync","path","SUBAGENT_CHILD_ENV","SUBAGENT_PARENT_SESSION_ENV","piAgentDirectory","fs"],"sources":["../src/services/paths/index.ts"],"sourcesContent":["import { execFile, execFileSync } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport { SUBAGENT_CHILD_ENV, SUBAGENT_PARENT_SESSION_ENV } from '@agimon-ai/po-core/childProcess';\nimport { piAgentDirectory } from '@agimon-ai/po-core/piSettings';\n\nexport const STORE_PATH_ENV = 'PO_TASK_STORE';\n\nconst STORE_DIR_NAME = 'po-task';\nconst STORE_FILE_NAME = 'tasks.json';\nconst FILE_ENCODING = 'utf8';\nconst NOT_FOUND_ERROR_CODE = 'ENOENT';\n\nfunction git(args: string[], cwd: string): string | undefined {\n try {\n const output = execFileSync('git', args, {\n cwd,\n encoding: FILE_ENCODING,\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n const trimmed = output.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function gitAsync(args: string[], cwd: string): Promise<string | undefined> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, encoding: FILE_ENCODING }, (error, stdout) => {\n if (error) {\n resolve(undefined);\n return;\n }\n const trimmed = stdout.trim();\n resolve(trimmed.length > 0 ? trimmed : undefined);\n });\n });\n}\n\nfunction isWithin(root: string, candidate: string): boolean {\n const relative = path.relative(path.resolve(root), path.resolve(candidate));\n return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Resolve the tree root without relying on extension startup order. */\nexport function resolveSessionKey(\n rootSessionId: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n if (!env[SUBAGENT_CHILD_ENV]) return rootSessionId;\n const parentSessionId = env[SUBAGENT_PARENT_SESSION_ENV]?.trim();\n if (!parentSessionId) throw new Error(`${SUBAGENT_PARENT_SESSION_ENV} is required in a subagent child`);\n return parentSessionId;\n}\n\n/** Resolve one root session tree to a task document under the Pi agent directory. */\nexport function resolveStorePath(\n _cwd: string = process.cwd(),\n env: Readonly<Record<string, string | undefined>> = process.env,\n sessionKey: string = 'standalone',\n): string {\n const override = env[STORE_PATH_ENV]?.trim();\n if (override) return path.resolve(override);\n\n const trimmedSessionKey = sessionKey.trim();\n if (!trimmedSessionKey) throw new Error('po-task session id cannot be blank');\n return path.join(piAgentDirectory(env), STORE_DIR_NAME, trimmedSessionKey, STORE_FILE_NAME);\n}\n\n/** Whether a deliberate unscoped task-store override is active. */\nexport function hasStorePathOverride(env: Readonly<Record<string, string | undefined>> = process.env): boolean {\n return Boolean(env[STORE_PATH_ENV]?.trim());\n}\n\n/** Exact legacy Git-directory store, if the current working tree has one. */\nexport function resolveLegacyStoreDirectory(cwd: string = process.cwd()): string | undefined {\n const commonDirectory = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport async function resolveLegacyStoreDirectoryAsync(cwd: string = process.cwd()): Promise<string | undefined> {\n const commonDirectory = await gitAsync(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n return commonDirectory ? path.join(commonDirectory, STORE_DIR_NAME) : undefined;\n}\n\nexport interface StoreSweepResult {\n removed: string[];\n errors: string[];\n}\n\n/** Remove only the validated legacy Git store unless it contains the active override. */\nexport function removeLegacyStoreDirectory(currentStorePath: string, cwd: string = process.cwd()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = resolveLegacyStoreDirectory(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n if (!fs.existsSync(target)) return result;\n fs.rmSync(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n return result;\n}\n\nexport async function removeLegacyStoreDirectoryAsync(\n currentStorePath: string,\n cwd: string = process.cwd(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const target = await resolveLegacyStoreDirectoryAsync(cwd);\n if (!target || path.basename(target) !== STORE_DIR_NAME || isWithin(target, currentStorePath)) return result;\n\n try {\n await fs.promises.access(target);\n await fs.promises.rm(target, { recursive: true, force: true });\n result.removed.push(target);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove legacy task store ${target}: ${String(error)}`);\n }\n }\n return result;\n}\n\n/** Delete expired sibling session stores while preserving active or unreadable stores. */\nexport function sweepStoreFiles(currentStorePath: string, ttlMs: number, now: number = Date.now()): StoreSweepResult {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = fs.readdirSync(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory || !fs.existsSync(candidate)) continue;\n try {\n if (fs.existsSync(lockPathFor(candidate))) continue;\n JSON.parse(fs.readFileSync(candidate, FILE_ENCODING));\n if (now - fs.statSync(candidate).mtimeMs <= ttlMs) continue;\n fs.rmSync(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport async function sweepStoreFilesAsync(\n currentStorePath: string,\n ttlMs: number,\n now: number = Date.now(),\n): Promise<StoreSweepResult> {\n const result: StoreSweepResult = { removed: [], errors: [] };\n const currentSessionDirectory = path.dirname(currentStorePath);\n const storeDirectory = path.dirname(currentSessionDirectory);\n let entries: string[];\n try {\n entries = await fs.promises.readdir(storeDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read task store directory ${storeDirectory}: ${String(error)}`);\n return result;\n }\n\n for (const entry of entries) {\n const sessionDirectory = path.join(storeDirectory, entry);\n const candidate = path.join(sessionDirectory, STORE_FILE_NAME);\n if (sessionDirectory === currentSessionDirectory) continue;\n try {\n await fs.promises.access(candidate);\n try {\n await fs.promises.access(lockPathFor(candidate));\n continue;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) throw error;\n }\n JSON.parse(await fs.promises.readFile(candidate, FILE_ENCODING));\n if (now - (await fs.promises.stat(candidate)).mtimeMs <= ttlMs) continue;\n await fs.promises.rm(sessionDirectory, { recursive: true, force: true });\n result.removed.push(sessionDirectory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) continue;\n result.errors.push(`Could not sweep task store ${candidate}: ${String(error)}`);\n }\n }\n return result;\n}\n\nexport function lockPathFor(storePath: string): string {\n return `${storePath}.lock`;\n}\n\nexport function tempPathFor(storePath: string, pid: number = process.pid): string {\n return `${storePath}.tmp.${pid}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,uBAAuB;AAE7B,SAAS,IAAI,MAAgB,KAAiC;CAC5D,IAAI;EAMF,MAAM,WAAA,GALSA,mBAAAA,aAAAA,CAAa,OAAO,MAAM;GACvC;GACA,UAAU;GACV,OAAO;IAAC;IAAU;IAAQ;GAAQ;EACpC,CACqB,CAAC,CAAC,KAAK;EAC5B,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;CACxC,QAAQ;EACN;CACF;AACF;AAEA,eAAe,SAAS,MAAgB,KAA0C;CAChF,OAAO,IAAI,SAAS,YAAY;EAC9B,CAAA,GAAA,mBAAA,SAAA,CAAS,OAAO,MAAM;GAAE;GAAK,UAAU;EAAc,IAAI,OAAO,WAAW;GACzE,IAAI,OAAO;IACT,QAAQ,KAAA,CAAS;IACjB;GACF;GACA,MAAM,UAAU,OAAO,KAAK;GAC5B,QAAQ,QAAQ,SAAS,IAAI,UAAU,KAAA,CAAS;EAClD,CAAC;CACH,CAAC;AACH;AAEA,SAAS,SAAS,MAAc,WAA4B;CAC1D,MAAM,WAAWC,UAAAA,QAAK,SAASA,UAAAA,QAAK,QAAQ,IAAI,GAAGA,UAAAA,QAAK,QAAQ,SAAS,CAAC;CAC1E,OAAO,aAAa,MAAO,CAAC,SAAS,WAAW,IAAI,KAAK,CAACA,UAAAA,QAAK,WAAW,QAAQ;AACpF;;AAGA,SAAgB,kBACd,eACA,MAAoD,QAAQ,KACpD;CACR,IAAI,CAAC,IAAIC,gCAAAA,qBAAqB,OAAO;CACrC,MAAM,kBAAkB,IAAIC,gCAAAA,4BAA4B,EAAE,KAAK;CAC/D,IAAI,CAAC,iBAAi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S,OAAO,SAAS;GAClC,IAAI;IACF,MAAMA,QAAAA,QAAG,SAAS,OAAO,YAAY,SAAS,CAAC;IAC/C;GACF,SAAS,OAAO;IACd,IAAK,MAAgC,SAAS,sBAAsB,MAAM;GAC5E;GACA,KAAK,MAAM,MAAMA,QAAAA,QAAG,SAAS,SAAS,WAAW,aAAa,CAAC;GAC/D,IAAI,OAAO,MAAMA,QAAAA,QAAG,SAAS,KAAK,SAAS,EAAA,CAAG,WAAW,OAAO;GAChE,MAAMA,QAAAA,QAAG,SAAS,GAAG,kBAAkB;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GACvE,OAAO,QAAQ,KAAK,gBAAgB;EACtC,SAAS,OAAO;GACd,IAAK,MAAgC,SAAS,sBAAsB;GACpE,OAAO,OAAO,KAAK,8BAA8B,UAAU,IAAI,OAAO,KAAK,GAAG;EAChF;CACF;CACA,OAAO;AACT;AAEA,SAAgB,YAAY,WAA2B;CACrD,OAAO,GAAG,UAAU;AACtB;AAEA,SAAgB,YAAY,WAAmB,MAAc,QAAQ,KAAa;CAChF,OAAO,GAAG,UAAU,OAAO;AAC7B"}
|
package/dist/storePaths.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_paths = require("./paths-
|
|
2
|
+
const require_paths = require("./paths-P-XvOUuH.cjs");
|
|
3
3
|
exports.STORE_PATH_ENV = require_paths.STORE_PATH_ENV;
|
|
4
4
|
exports.hasStorePathOverride = require_paths.hasStorePathOverride;
|
|
5
5
|
exports.lockPathFor = require_paths.lockPathFor;
|
package/dist/storePaths.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as removeLegacyStoreDirectory, c as resolveLegacyStoreDirectoryAsync, d as sweepStoreFiles, f as sweepStoreFilesAsync, i as lockPathFor, l as resolveSessionKey, n as StoreSweepResult, o as removeLegacyStoreDirectoryAsync, p as tempPathFor, r as hasStorePathOverride, s as resolveLegacyStoreDirectory, t as STORE_PATH_ENV, u as resolveStorePath } from "./index-
|
|
1
|
+
import { a as removeLegacyStoreDirectory, c as resolveLegacyStoreDirectoryAsync, d as sweepStoreFiles, f as sweepStoreFilesAsync, i as lockPathFor, l as resolveSessionKey, n as StoreSweepResult, o as removeLegacyStoreDirectoryAsync, p as tempPathFor, r as hasStorePathOverride, s as resolveLegacyStoreDirectory, t as STORE_PATH_ENV, u as resolveStorePath } from "./index-CA4Opp4r.mjs";
|
|
2
2
|
export { STORE_PATH_ENV, StoreSweepResult, hasStorePathOverride, lockPathFor, removeLegacyStoreDirectory, removeLegacyStoreDirectoryAsync, resolveLegacyStoreDirectory, resolveLegacyStoreDirectoryAsync, resolveSessionKey, resolveStorePath, sweepStoreFiles, sweepStoreFilesAsync, tempPathFor };
|
package/dist/storePaths.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as STORE_PATH_ENV, n as hasStorePathOverride, r as lockPathFor, i as removeLegacyStoreDirectory, a as removeLegacyStoreDirectoryAsync, o as resolveLegacyStoreDirectory, s as resolveLegacyStoreDirectoryAsync, c as resolveSessionKey, l as resolveStorePath, u as sweepStoreFiles, d as sweepStoreFilesAsync, f as tempPathFor } from "./paths-
|
|
1
|
+
export { t as STORE_PATH_ENV, n as hasStorePathOverride, r as lockPathFor, i as removeLegacyStoreDirectory, a as removeLegacyStoreDirectoryAsync, o as resolveLegacyStoreDirectory, s as resolveLegacyStoreDirectoryAsync, c as resolveSessionKey, l as resolveStorePath, u as sweepStoreFiles, d as sweepStoreFilesAsync, f as tempPathFor } from "./paths-DajceJig.mjs";
|
package/dist/storeTaskStore.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as TaskStoreOptions, t as TaskStore } from "./index-
|
|
1
|
+
import { n as TaskStoreOptions, t as TaskStore } from "./index-qQGWsPum.mjs";
|
|
2
2
|
export { TaskStore, TaskStoreOptions };
|
package/dist/storeTaskStore.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as TaskStore } from "./taskStore-
|
|
1
|
+
export { t as TaskStore } from "./taskStore-BAi54FKL.mjs";
|
|
@@ -4,9 +4,9 @@ import { Static, Type } from "typebox";
|
|
|
4
4
|
declare const COMMAND_NAME = "tasks";
|
|
5
5
|
//#endregion
|
|
6
6
|
//#region src/schemas/task.d.ts
|
|
7
|
-
declare const TASK_ACTIONS: readonly [
|
|
8
|
-
declare const TASK_STATUSES: readonly [
|
|
9
|
-
declare const TASK_CONTEXTS: readonly [
|
|
7
|
+
declare const TASK_ACTIONS: readonly ["upsert", "list", "get", "delete", "clear", "assign", "cancel"];
|
|
8
|
+
declare const TASK_STATUSES: readonly ["pending", "in_progress", "completed", "failed", "deleted"];
|
|
9
|
+
declare const TASK_CONTEXTS: readonly ["fresh", "fork"];
|
|
10
10
|
declare const TOOL_NAME = "task";
|
|
11
11
|
declare const TOOL_LABEL = "Task";
|
|
12
12
|
declare const ERR_REQUIRES_INTERACTIVE = "/tasks requires interactive mode";
|
|
@@ -98,8 +98,9 @@ declare const TaskParamsSchema: Type.TObject<{
|
|
|
98
98
|
includeDeleted: Type.TOptional<Type.TBoolean>;
|
|
99
99
|
}>;
|
|
100
100
|
/** Remote MCP connections track tasks only; delegation stays with the local agent. */
|
|
101
|
-
declare const REMOTE_TASK_ACTIONS: readonly [
|
|
101
|
+
declare const REMOTE_TASK_ACTIONS: readonly ["upsert", "list", "get", "delete", "clear"];
|
|
102
102
|
declare const RemoteTaskParamsSchema: Type.TObject<{
|
|
103
|
+
action: Type.TString;
|
|
103
104
|
tasks: Type.TOptional<Type.TArray<Type.TObject<{
|
|
104
105
|
id: Type.TOptional<Type.TInteger>;
|
|
105
106
|
ref: Type.TOptional<Type.TString>;
|
|
@@ -116,11 +117,10 @@ declare const RemoteTaskParamsSchema: Type.TObject<{
|
|
|
116
117
|
id: Type.TOptional<Type.TInteger>;
|
|
117
118
|
status: Type.TOptional<Type.TString>;
|
|
118
119
|
includeDeleted: Type.TOptional<Type.TBoolean>;
|
|
119
|
-
action: Type.TString;
|
|
120
120
|
}>;
|
|
121
121
|
type TaskItemParams = Static<typeof TaskItemSchema>;
|
|
122
122
|
type TaskAssignmentParams = Static<typeof TaskAssignmentSchema>;
|
|
123
123
|
type TaskParams = Static<typeof TaskParamsSchema>;
|
|
124
124
|
//#endregion
|
|
125
125
|
export { TaskParamsSchema as _, RemoteTaskParamsSchema as a, TASK_CONTEXTS as c, TOOL_NAME as d, TaskAssignmentParams as f, TaskParams as g, TaskItemSchema as h, REMOTE_TASK_ACTIONS as i, TASK_STATUSES as l, TaskItemParams as m, MSG_NO_TASKS as n, TASK_ACTIONS as o, TaskAssignmentSchema as p, MSG_UPSERT_FIELD_MISPLACED as r, TASK_ACTION_FIELDS as s, ERR_REQUIRES_INTERACTIVE as t, TOOL_LABEL as u, taskActionAcceptsField as v, COMMAND_NAME as y };
|
|
126
|
-
//# sourceMappingURL=task-
|
|
126
|
+
//# sourceMappingURL=task-4HeGAS8o.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-
|
|
1
|
+
{"version":3,"file":"task-4HeGAS8o.d.mts","names":[],"sources":["../src/constants/task.ts","../src/schemas/task.ts"],"mappings":";;;cAAa;;;cCOA;cACA;cACA;cAEA;cACA;cAEA;cACA;;;;;;;;;cAUA;;;;;;;;;iBAUG,uBAAuB,QAAQ,YAAY;;cAK9C;;;;;;cAcA,gBAAc,KAAA;;;;;;;;;;;;;;cA2Dd,sBAAoB,KAAA;;;;;;;;;;;;;;;;cA6BpB,kBAAgB,KAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAiChB;cAEA,wBAAsB,KAAA;;;;;;;;;;;;;;;;;;;KAKvB,iBAAiB,cAAc;KAC/B,uBAAuB,cAAc;KACrC,aAAa,cAAc"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as TASK_EVENT } from "./telemetry-
|
|
1
|
+
import { t as TASK_EVENT } from "./telemetry-gEGWTaMI.mjs";
|
|
2
2
|
import { r as emptyDocument } from "./task-giCbpKzV.mjs";
|
|
3
3
|
import { t as isProcessAlive } from "./processLiveness-Ccd9wenT.mjs";
|
|
4
|
-
import { f as tempPathFor, l as resolveStorePath, r as lockPathFor } from "./paths-
|
|
4
|
+
import { f as tempPathFor, l as resolveStorePath, r as lockPathFor } from "./paths-DajceJig.mjs";
|
|
5
5
|
import { n as canonicalizeTasks } from "./invariants-q_UamF7D.mjs";
|
|
6
6
|
import fs from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
@@ -61,7 +61,7 @@ var TaskStore = class {
|
|
|
61
61
|
}
|
|
62
62
|
/** Bind a default store to the current session tree before reading it. */
|
|
63
63
|
configureSession(sessionKey) {
|
|
64
|
-
if (this.env["
|
|
64
|
+
if (this.env["PO_TASK_STORE"]?.trim()) return;
|
|
65
65
|
this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);
|
|
66
66
|
this.cached = emptyDocument();
|
|
67
67
|
}
|
|
@@ -205,4 +205,4 @@ var TaskStore = class {
|
|
|
205
205
|
//#endregion
|
|
206
206
|
export { TaskStore as t };
|
|
207
207
|
|
|
208
|
-
//# sourceMappingURL=taskStore-
|
|
208
|
+
//# sourceMappingURL=taskStore-BAi54FKL.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taskStore-pAJ971Ml.mjs","names":[],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = canonicalizeTasks(\n candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n ),\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;A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kCACX,IAAI,MAAM,oCAAoC,KAAK,cAAc,0BAA0B,GAC3F,GAAG,uBAAuB,KAAK,UAAU,CAC3C;IACA,aAAa,CAAC;GAChB;GAIA,KAAK,eAAe,QAAQ;GAC5B,MAAM,MAAM,qBAAqB,KAAK,OAAO,IAAI,iBAAiB;EACpE;CAEJ;;CAGA,eAAuB,UAA2B;EAChD,IAAI;GACF,MAAM,SAAS,KAAK,MAAM,GAAG,aAAa,UAAU,aAAa,CAAC;GAClE,MAAM,UAAU,OAAO,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,OAAO,OAAO;GAC9E,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAAC,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,GAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAK,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
|
|
1
|
+
{"version":3,"file":"taskStore-BAi54FKL.mjs","names":[],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = canonicalizeTasks(\n candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n ),\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB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,KAAK,cAAc,0BAA0B,GAC3F,GAAG,uBAAuB,KAAK,UAAU,CAC3C;IACA,aAAa,CAAC;GAChB;GAIA,KAAK,eAAe,QAAQ;GAC5B,MAAM,MAAM,qBAAqB,KAAK,OAAO,IAAI,iBAAiB;EACpE;CAEJ;;CAGA,eAAuB,UAA2B;EAChD,IAAI;GACF,MAAM,SAAS,KAAK,MAAM,GAAG,aAAa,UAAU,aAAa,CAAC;GAClE,MAAM,UAAU,OAAO,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,OAAO,OAAO;GAC9E,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAAC,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,GAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAK,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const require_paths = require("./paths-
|
|
2
|
-
const require_telemetry = require("./telemetry-
|
|
1
|
+
const require_paths = require("./paths-P-XvOUuH.cjs");
|
|
2
|
+
const require_telemetry = require("./telemetry-x3JxCA5K.cjs");
|
|
3
3
|
const require_task = require("./task-CXF9VULl.cjs");
|
|
4
4
|
const require_processLiveness = require("./processLiveness-umpNgsPR.cjs");
|
|
5
5
|
const require_invariants = require("./invariants-DhjEjBPU.cjs");
|
|
@@ -63,7 +63,7 @@ var TaskStore = class {
|
|
|
63
63
|
}
|
|
64
64
|
/** Bind a default store to the current session tree before reading it. */
|
|
65
65
|
configureSession(sessionKey) {
|
|
66
|
-
if (this.env["
|
|
66
|
+
if (this.env["PO_TASK_STORE"]?.trim()) return;
|
|
67
67
|
this.storePath = require_paths.resolveStorePath(this.cwd, this.env, sessionKey);
|
|
68
68
|
this.cached = require_task.emptyDocument();
|
|
69
69
|
}
|
|
@@ -212,4 +212,4 @@ Object.defineProperty(exports, "TaskStore", {
|
|
|
212
212
|
}
|
|
213
213
|
});
|
|
214
214
|
|
|
215
|
-
//# sourceMappingURL=taskStore-
|
|
215
|
+
//# sourceMappingURL=taskStore-C4vcUOzA.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"taskStore-DjU60rMm.cjs","names":["emptyDocument","canonicalizeTasks","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = canonicalizeTasks(\n candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n ),\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAY7B,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;;;;;;;AAQA,SAAS,kBAAkB,QAA+B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAOA,aAAAA,cAAc;CAChE,MAAM,YAAY;CAClB,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,GAAG,OAAOA,aAAAA,cAAc;CAE1D,MAAM,QAAQC,mBAAAA,kBACZ,UAAU,MAAM,QACb,SAAuB,QAAQ,IAAI,KAAK,OAAO,SAAS,YAAY,OA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CAEJ;;CAGA,eAAuB,UAA2B;EAChD,IAAI;GACF,MAAM,SAAS,KAAK,MAAMD,QAAAA,QAAG,aAAa,UAAU,aAAa,CAAC;GAClE,MAAM,UAAU,OAAO,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,OAAO,OAAO;GAC9E,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAACK,wBAAAA,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,QAAA,QAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAKJ,kBAAAA,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
|
|
1
|
+
{"version":3,"file":"taskStore-C4vcUOzA.cjs","names":["emptyDocument","canonicalizeTasks","resolveStorePath","fs","TASK_EVENT","path","tempPathFor","lockPathFor","isProcessAlive"],"sources":["../src/services/taskStore/index.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { emptyDocument, STORE_SCHEMA_VERSION, type Task, type TaskDocument } from '../../models/task';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry';\nimport { canonicalizeTasks } from '../invariants';\nimport { lockPathFor, resolveStorePath, STORE_PATH_ENV, tempPathFor } from '../paths';\nimport { isProcessAlive } from '../processLiveness';\n\nconst LOCK_TIMEOUT_MS = 2000;\nconst LOCK_STALE_MS = 10_000;\nconst LOCK_RETRY_BASE_MS = 10;\nconst LOCK_RETRY_MAX_MS = 60;\nconst UTF8_ENCODING = 'utf8';\nconst MISSING_FILE_CODE = 'ENOENT';\nconst LOCK_EXISTS_CODE = 'EEXIST';\nconst STORE_PATH_ATTRIBUTE = 'store.path';\n\nexport interface TaskStoreOptions {\n cwd?: string;\n env?: Readonly<Record<string, string | undefined>>;\n storePath?: string;\n /** How long to wait for the advisory lock before proceeding lock-free. */\n lockTimeoutMs?: number;\n /** Where swallowed failures go, so silent degradation stays visible. */\n report?: TaskFailureReporter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Coerce arbitrary parsed JSON into a valid document.\n *\n * A corrupt or truncated store must not take the session down: the worst\n * acceptable outcome is starting from an empty list, never a crash on startup.\n */\nfunction normalizeDocument(parsed: unknown): TaskDocument {\n if (!parsed || typeof parsed !== 'object') return emptyDocument();\n const candidate = parsed as Partial<TaskDocument>;\n if (!Array.isArray(candidate.tasks)) return emptyDocument();\n\n const tasks = canonicalizeTasks(\n candidate.tasks.filter(\n (task): task is Task => Boolean(task) && typeof task === 'object' && typeof (task as Task).id === 'number',\n ),\n );\n const maxId = tasks.reduce((max, task) => Math.max(max, task.id), 0);\n return {\n version: typeof candidate.version === 'number' ? candidate.version : STORE_SCHEMA_VERSION,\n rev: typeof candidate.rev === 'number' ? candidate.rev : 0,\n nextId: typeof candidate.nextId === 'number' && candidate.nextId > maxId ? candidate.nextId : maxId + 1,\n tasks,\n };\n}\n\n/**\n * File-backed task store shared by one root session and its delegated children.\n *\n * Durability model: the JSON file is the source of truth. Mutations are\n * read-modify-write under an advisory lock so concurrent delegated processes\n * cannot clobber each other, and writes land via temp-file rename so a\n * crash mid-write can never leave a partial document behind.\n */\nexport class TaskStore {\n storePath: string;\n\n private readonly cwd: string;\n private readonly env: Readonly<Record<string, string | undefined>>;\n private cached: TaskDocument = emptyDocument();\n private readonly listeners = new Set<(document: TaskDocument) => void>();\n private readonly lockTimeoutMs: number;\n private readonly report?: TaskFailureReporter;\n\n constructor(options: TaskStoreOptions = {}) {\n this.cwd = options.cwd ?? process.cwd();\n this.env = options.env ?? process.env;\n this.storePath = options.storePath ?? resolveStorePath(this.cwd, this.env);\n this.lockTimeoutMs = options.lockTimeoutMs ?? LOCK_TIMEOUT_MS;\n this.report = options.report;\n }\n\n /** Bind a default store to the current session tree before reading it. */\n configureSession(sessionKey: string): void {\n if (this.env[STORE_PATH_ENV]?.trim()) return;\n this.storePath = resolveStorePath(this.cwd, this.env, sessionKey);\n this.cached = emptyDocument();\n }\n\n /** Last document read from disk, without hitting the filesystem. */\n get snapshot(): TaskDocument {\n return this.cached;\n }\n\n read(): TaskDocument {\n try {\n const raw = fs.readFileSync(this.storePath, UTF8_ENCODING);\n this.cached = normalizeDocument(JSON.parse(raw));\n } catch (error) {\n // A missing file is the normal state before the first write. Anything\n // else means the task list just silently became empty, which is worth a\n // record: unreadable or corrupt JSON looks identical to \"no tasks yet\".\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n this.cached = emptyDocument();\n }\n return this.cached;\n }\n\n async readAsync(\n shouldApply: () => boolean = () => true,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n const storePath = this.storePath;\n const document = await this.readDocumentAsync(storePath, onReadError);\n if (!shouldApply()) return document;\n this.cached = document;\n return document;\n }\n\n private async readDocumentAsync(\n storePath: string = this.storePath,\n onReadError?: (error: unknown) => void,\n ): Promise<TaskDocument> {\n try {\n const raw = await fs.promises.readFile(storePath, UTF8_ENCODING);\n return normalizeDocument(JSON.parse(raw));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.error(TASK_EVENT.storeReadFailed, error, { [STORE_PATH_ATTRIBUTE]: storePath });\n try {\n onReadError?.(error);\n } catch {\n // Diagnostic failures must not change fail-open reads.\n }\n }\n return emptyDocument();\n }\n }\n\n /**\n * Apply a mutation under the store lock.\n *\n * `mutate` receives the freshest on-disk document and returns either the next\n * document to commit or `undefined` for a read-only action (list/get), which\n * skips the write entirely so queries never bump `rev`.\n */\n async mutate<T>(\n mutate: (document: TaskDocument) => { document?: TaskDocument; value: T },\n ): Promise<{ document: TaskDocument; value: T }> {\n const release = await this.acquireLock();\n const outcome = (() => {\n try {\n const current = this.read();\n const mutation = mutate(current);\n if (!mutation.document) {\n return { result: { document: current, value: mutation.value } };\n }\n const committed = this.write(mutation.document);\n return {\n result: { document: committed, value: mutation.value },\n notification: committed,\n };\n } finally {\n release();\n }\n })();\n if (outcome.notification) {\n this.notifyCommitted(outcome.notification);\n }\n return outcome.result;\n }\n\n private notifyCommitted(committed: TaskDocument): void {\n for (const listener of this.listeners) {\n try {\n listener(committed);\n } catch (error) {\n this.report?.error(TASK_EVENT.storeListenerFailed, error, { [STORE_PATH_ATTRIBUTE]: this.storePath });\n }\n }\n }\n\n private write(document: TaskDocument): TaskDocument {\n const next: TaskDocument = { ...document, version: STORE_SCHEMA_VERSION, rev: document.rev + 1 };\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const temp = tempPathFor(this.storePath);\n fs.writeFileSync(temp, `${JSON.stringify(next, undefined, 2)}\\n`, UTF8_ENCODING);\n fs.renameSync(temp, this.storePath);\n this.cached = next;\n return next;\n }\n\n private async acquireLock(): Promise<() => void> {\n const lockPath = lockPathFor(this.storePath);\n fs.mkdirSync(path.dirname(this.storePath), { recursive: true });\n const deadline = Date.now() + this.lockTimeoutMs;\n\n for (;;) {\n try {\n const handle = fs.openSync(lockPath, 'wx');\n fs.writeSync(handle, JSON.stringify({ pid: process.pid, time: Date.now() }));\n fs.closeSync(handle);\n return () => fs.rmSync(lockPath, { force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== LOCK_EXISTS_CODE) throw error;\n // The deadline is checked before breaking a stale lock so a peer that\n // keeps recreating one cannot spin this loop without bound.\n if (Date.now() >= deadline) {\n // Proceeding lock-free beats stalling the agent: the rename is atomic,\n // so the worst case is a lost concurrent update, not a corrupt file.\n // Reported because a lost update here can strand a delegation.\n this.report?.warn(\n TASK_EVENT.storeLockTimeout,\n new Error(`Task store lock still held after ${this.lockTimeoutMs}ms; proceeding without it`),\n { [STORE_PATH_ATTRIBUTE]: this.storePath },\n );\n return () => {};\n }\n // Clearing a dead holder's lock still goes through the backoff. Yielding\n // on every iteration is what stops a peer that keeps recreating the\n // lock from turning this into a spin.\n this.breakStaleLock(lockPath);\n await sleep(LOCK_RETRY_BASE_MS + Math.random() * LOCK_RETRY_MAX_MS);\n }\n }\n }\n\n /** Remove a lock left behind by a dead process or one held implausibly long. */\n private breakStaleLock(lockPath: string): boolean {\n try {\n const holder = JSON.parse(fs.readFileSync(lockPath, UTF8_ENCODING)) as { pid?: number; time?: number };\n const expired = typeof holder.time === 'number' && Date.now() - holder.time > LOCK_STALE_MS;\n const dead = typeof holder.pid === 'number' && !isProcessAlive(holder.pid);\n if (!expired && !dead) return false;\n fs.unlinkSync(lockPath);\n return true;\n } catch (error) {\n // Losing the race to another breaker is normal; a persistent failure here\n // shows up as the lock timeout above, so this stays a warning.\n if ((error as NodeJS.ErrnoException).code !== MISSING_FILE_CODE) {\n this.report?.warn(TASK_EVENT.storeLockBreakFailed, error, { [STORE_PATH_ATTRIBUTE]: lockPath });\n }\n return false;\n }\n }\n\n /**\n * Listen for commits made through this store instance.\n *\n * Live cross-process updates use the owning session's direct event bus. This\n * listener publishes local commits to that bus and never watches the filesystem.\n */\n onExternalChange(listener: (document: TaskDocument) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n this.listeners.clear();\n }\n}\n"],"mappings":";;;;;;;;;;AASA,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAC1B,MAAM,gBAAgB;AACtB,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAY7B,SAAS,MAAM,IAA2B;CACxC,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,E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MAAgC,SAAS,kBAAkB,MAAM;GAGtE,IAAI,KAAK,IAAI,KAAK,UAAU;IAI1B,KAAK,QAAQ,KACXC,kBAAAA,WAAW,kCACX,IAAI,MAAM,oCAAoC,KAAK,cAAc,0BAA0B,GAC3F,GAAG,uBAAuB,KAAK,UAAU,CAC3C;IACA,aAAa,CAAC;GAChB;GAIA,KAAK,eAAe,QAAQ;GAC5B,MAAM,MAAM,qBAAqB,KAAK,OAAO,IAAI,iBAAiB;EACpE;CAEJ;;CAGA,eAAuB,UAA2B;EAChD,IAAI;GACF,MAAM,SAAS,KAAK,MAAMD,QAAAA,QAAG,aAAa,UAAU,aAAa,CAAC;GAClE,MAAM,UAAU,OAAO,OAAO,SAAS,YAAY,KAAK,IAAI,IAAI,OAAO,OAAO;GAC9E,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,CAACK,wBAAAA,eAAe,OAAO,GAAG;GACzE,IAAI,CAAC,WAAW,CAAC,MAAM,OAAO;GAC9B,QAAA,QAAG,WAAW,QAAQ;GACtB,OAAO;EACT,SAAS,OAAO;GAGd,IAAK,MAAgC,SAAS,mBAC5C,KAAK,QAAQ,KAAKJ,kBAAAA,WAAW,sBAAsB,OAAO,GAAG,uBAAuB,SAAS,CAAC;GAEhG,OAAO;EACT;CACF;;;;;;;CAQA,iBAAiB,UAAwD;EACvE,KAAK,UAAU,IAAI,QAAQ;EAC3B,aAAa,KAAK,UAAU,OAAO,QAAQ;CAC7C;CAEA,UAAgB;EACd,KAAK,UAAU,MAAM;CACvB;AACF"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/types/telemetry.d.ts
|
|
2
|
+
declare const TASK_EVENT: {
|
|
3
|
+
readonly notificationFailed: "po_task.notification_failed";
|
|
4
|
+
readonly storeReadFailed: "po_task.store_read_failed";
|
|
5
|
+
readonly storeLockTimeout: "po_task.store_lock_timeout";
|
|
6
|
+
readonly storeLockBreakFailed: "po_task.store_lock_break_failed";
|
|
7
|
+
readonly storeWatchFailed: "po_task.store_watch_failed";
|
|
8
|
+
readonly storeListenerFailed: "po_task.store_listener_failed";
|
|
9
|
+
readonly storeSweepFailed: "po_task.store_sweep_failed";
|
|
10
|
+
readonly sessionStartFailed: "po_task.session_start_failed";
|
|
11
|
+
readonly sessionStartDegraded: "po_task.session_start_degraded";
|
|
12
|
+
readonly toolFailed: "po_task.tool_failed";
|
|
13
|
+
readonly delegationRequestFailed: "po_task.delegation_request_failed";
|
|
14
|
+
readonly delegationStartFailed: "po_task.delegation_start_failed";
|
|
15
|
+
readonly delegationResponseFailed: "po_task.delegation_response_failed";
|
|
16
|
+
readonly delegationSettleFailed: "po_task.delegation_settle_failed";
|
|
17
|
+
readonly delegationTimedOut: "po_task.delegation_timed_out";
|
|
18
|
+
readonly delegationOrphaned: "po_task.delegation_orphaned";
|
|
19
|
+
readonly delegationAssigned: "po_task.delegation_assigned";
|
|
20
|
+
readonly delegationCompleted: "po_task.delegation_completed";
|
|
21
|
+
};
|
|
22
|
+
type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];
|
|
23
|
+
type TaskErrorAttributes = Record<string, string | number | boolean>;
|
|
24
|
+
type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;
|
|
25
|
+
type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;
|
|
26
|
+
/** Host-neutral telemetry port consumed by Task services and store adapters. */
|
|
27
|
+
interface TaskFailureReporter {
|
|
28
|
+
error: TaskErrorSink;
|
|
29
|
+
warn: TaskErrorSink;
|
|
30
|
+
/** Info-level event sink. Required so an unwired reporter fails to compile. */
|
|
31
|
+
event: TaskEventSink;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { TaskEventSink as a, TaskEventName as i, TaskErrorAttributes as n, TaskFailureReporter as o, TaskErrorSink as r, TASK_EVENT as t };
|
|
35
|
+
//# sourceMappingURL=telemetry-DYfgUFF8.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-DYfgUFF8.d.mts","names":[],"sources":["../src/types/telemetry.ts"],"mappings":";cAAa;;;;;;;;;;;;;;;;;;;;KAuBD,wBAAwB,yBAAyB;KACjD,sBAAsB;KACtB,iBAAiB,OAAO,eAAe,gBAAgB,aAAa;KACpE,iBAAiB,OAAO,eAAe,aAAa;;UAG/C;EACf,OAAO;EACP,MAAM;;EAEN,OAAO"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/types/telemetry.ts
|
|
2
|
+
const TASK_EVENT = {
|
|
3
|
+
notificationFailed: "po_task.notification_failed",
|
|
4
|
+
storeReadFailed: "po_task.store_read_failed",
|
|
5
|
+
storeLockTimeout: "po_task.store_lock_timeout",
|
|
6
|
+
storeLockBreakFailed: "po_task.store_lock_break_failed",
|
|
7
|
+
storeWatchFailed: "po_task.store_watch_failed",
|
|
8
|
+
storeListenerFailed: "po_task.store_listener_failed",
|
|
9
|
+
storeSweepFailed: "po_task.store_sweep_failed",
|
|
10
|
+
sessionStartFailed: "po_task.session_start_failed",
|
|
11
|
+
sessionStartDegraded: "po_task.session_start_degraded",
|
|
12
|
+
toolFailed: "po_task.tool_failed",
|
|
13
|
+
delegationRequestFailed: "po_task.delegation_request_failed",
|
|
14
|
+
delegationStartFailed: "po_task.delegation_start_failed",
|
|
15
|
+
delegationResponseFailed: "po_task.delegation_response_failed",
|
|
16
|
+
delegationSettleFailed: "po_task.delegation_settle_failed",
|
|
17
|
+
delegationTimedOut: "po_task.delegation_timed_out",
|
|
18
|
+
delegationOrphaned: "po_task.delegation_orphaned",
|
|
19
|
+
delegationAssigned: "po_task.delegation_assigned",
|
|
20
|
+
delegationCompleted: "po_task.delegation_completed"
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { TASK_EVENT as t };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=telemetry-gEGWTaMI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-gEGWTaMI.mjs","names":[],"sources":["../src/types/telemetry.ts"],"sourcesContent":["export const TASK_EVENT = {\n notificationFailed: 'po_task.notification_failed',\n storeReadFailed: 'po_task.store_read_failed',\n storeLockTimeout: 'po_task.store_lock_timeout',\n storeLockBreakFailed: 'po_task.store_lock_break_failed',\n storeWatchFailed: 'po_task.store_watch_failed',\n storeListenerFailed: 'po_task.store_listener_failed',\n storeSweepFailed: 'po_task.store_sweep_failed',\n sessionStartFailed: 'po_task.session_start_failed',\n sessionStartDegraded: 'po_task.session_start_degraded',\n toolFailed: 'po_task.tool_failed',\n delegationRequestFailed: 'po_task.delegation_request_failed',\n delegationStartFailed: 'po_task.delegation_start_failed',\n delegationResponseFailed: 'po_task.delegation_response_failed',\n delegationSettleFailed: 'po_task.delegation_settle_failed',\n delegationTimedOut: 'po_task.delegation_timed_out',\n delegationOrphaned: 'po_task.delegation_orphaned',\n // Info-level lifecycle events. These are the measurement pair: the shape of\n // the brief that went out, and the cost of the run it produced.\n delegationAssigned: 'po_task.delegation_assigned',\n delegationCompleted: 'po_task.delegation_completed',\n} as const;\n\nexport type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];\nexport type TaskErrorAttributes = Record<string, string | number | boolean>;\nexport type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;\nexport type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;\n\n/** Host-neutral telemetry port consumed by Task services and store adapters. */\nexport interface TaskFailureReporter {\n error: TaskErrorSink;\n warn: TaskErrorSink;\n /** Info-level event sink. Required so an unwired reporter fails to compile. */\n event: TaskEventSink;\n}\n"],"mappings":";AAAA,MAAa,aAAa;CACxB,oBAAoB;CACpB,iBAAiB;CACjB,kBAAkB;CAClB,sBAAsB;CACtB,kBAAkB;CAClB,qBAAqB;CACrB,kBAAkB;CAClB,oBAAoB;CACpB,sBAAsB;CACtB,YAAY;CACZ,yBAAyB;CACzB,uBAAuB;CACvB,0BAA0B;CAC1B,wBAAwB;CACxB,oBAAoB;CACpB,oBAAoB;CAGpB,oBAAoB;CACpB,qBAAqB;AACvB"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/types/telemetry.ts
|
|
2
|
+
const TASK_EVENT = {
|
|
3
|
+
notificationFailed: "po_task.notification_failed",
|
|
4
|
+
storeReadFailed: "po_task.store_read_failed",
|
|
5
|
+
storeLockTimeout: "po_task.store_lock_timeout",
|
|
6
|
+
storeLockBreakFailed: "po_task.store_lock_break_failed",
|
|
7
|
+
storeWatchFailed: "po_task.store_watch_failed",
|
|
8
|
+
storeListenerFailed: "po_task.store_listener_failed",
|
|
9
|
+
storeSweepFailed: "po_task.store_sweep_failed",
|
|
10
|
+
sessionStartFailed: "po_task.session_start_failed",
|
|
11
|
+
sessionStartDegraded: "po_task.session_start_degraded",
|
|
12
|
+
toolFailed: "po_task.tool_failed",
|
|
13
|
+
delegationRequestFailed: "po_task.delegation_request_failed",
|
|
14
|
+
delegationStartFailed: "po_task.delegation_start_failed",
|
|
15
|
+
delegationResponseFailed: "po_task.delegation_response_failed",
|
|
16
|
+
delegationSettleFailed: "po_task.delegation_settle_failed",
|
|
17
|
+
delegationTimedOut: "po_task.delegation_timed_out",
|
|
18
|
+
delegationOrphaned: "po_task.delegation_orphaned",
|
|
19
|
+
delegationAssigned: "po_task.delegation_assigned",
|
|
20
|
+
delegationCompleted: "po_task.delegation_completed"
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
Object.defineProperty(exports, "TASK_EVENT", {
|
|
24
|
+
enumerable: true,
|
|
25
|
+
get: function() {
|
|
26
|
+
return TASK_EVENT;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=telemetry-x3JxCA5K.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-x3JxCA5K.cjs","names":[],"sources":["../src/types/telemetry.ts"],"sourcesContent":["export const TASK_EVENT = {\n notificationFailed: 'po_task.notification_failed',\n storeReadFailed: 'po_task.store_read_failed',\n storeLockTimeout: 'po_task.store_lock_timeout',\n storeLockBreakFailed: 'po_task.store_lock_break_failed',\n storeWatchFailed: 'po_task.store_watch_failed',\n storeListenerFailed: 'po_task.store_listener_failed',\n storeSweepFailed: 'po_task.store_sweep_failed',\n sessionStartFailed: 'po_task.session_start_failed',\n sessionStartDegraded: 'po_task.session_start_degraded',\n toolFailed: 'po_task.tool_failed',\n delegationRequestFailed: 'po_task.delegation_request_failed',\n delegationStartFailed: 'po_task.delegation_start_failed',\n delegationResponseFailed: 'po_task.delegation_response_failed',\n delegationSettleFailed: 'po_task.delegation_settle_failed',\n delegationTimedOut: 'po_task.delegation_timed_out',\n delegationOrphaned: 'po_task.delegation_orphaned',\n // Info-level lifecycle events. These are the measurement pair: the shape of\n // the brief that went out, and the cost of the run it produced.\n delegationAssigned: 'po_task.delegation_assigned',\n delegationCompleted: 'po_task.delegation_completed',\n} as const;\n\nexport type TaskEventName = (typeof TASK_EVENT)[keyof typeof TASK_EVENT];\nexport type TaskErrorAttributes = Record<string, string | number | boolean>;\nexport type TaskErrorSink = (event: TaskEventName, error: unknown, attributes?: TaskErrorAttributes) => void;\nexport type TaskEventSink = (event: TaskEventName, attributes?: TaskErrorAttributes) => void;\n\n/** Host-neutral telemetry port consumed by Task services and store adapters. */\nexport interface TaskFailureReporter {\n error: TaskErrorSink;\n warn: TaskErrorSink;\n /** Info-level event sink. Required so an unwired reporter fails to compile. */\n event: TaskEventSink;\n}\n"],"mappings":";AAAA,MAAa,aAAa;CACxB,oBAAoB;CACpB,iBAAiB;CACjB,kBAAkB;CAClB,sBAAsB;CACtB,kBAAkB;CAClB,qBAAqB;CACrB,kBAAkB;CAClB,oBAAoB;CACpB,sBAAsB;CACtB,YAAY;CACZ,yBAAyB;CACzB,uBAAuB;CACvB,0BAA0B;CAC1B,wBAAwB;CACxB,oBAAoB;CACpB,oBAAoB;CAGpB,oBAAoB;CACpB,qBAAqB;AACvB"}
|
|
@@ -19,7 +19,7 @@ const DEFAULT_PROMPT_GUIDELINES = [
|
|
|
19
19
|
"Assign through assignments[] even for a single task: {\"action\":\"assign\",\"assignments\":[{\"id\":1,\"agent\":\"researcher\"}]}. Put independent ready tasks in one batch rather than repeated calls or multi_tool, and do not start a direct subagent run for work already on the task list. Successful entries keep running when another entry fails, so retry only the failures.",
|
|
20
20
|
"Fill relevantFiles only with files you actually read or located, and priorFindings only with verified facts in a few lines, not directives. A guessed path costs more than an omitted one.",
|
|
21
21
|
"Subject stays short and imperative. description is the durable brief handed to the subagent, extended at assign time by instructions, relevantFiles and priorFindings, so do not repeat one in the other.",
|
|
22
|
-
"When a delegated task completes and unblocks another, reconsider it promptly. If a child asks for a decision or an assignment fails to start, respond, rescope or retry instead of leaving it pending.
|
|
22
|
+
"When a delegated task completes and unblocks another, reconsider it promptly. If a child asks for a decision or an assignment fails to start, respond, rescope or retry instead of leaving it pending. Po Task records delegated lifecycle and results on the task itself."
|
|
23
23
|
];
|
|
24
24
|
//#endregion
|
|
25
25
|
exports.DEFAULT_PROMPT_GUIDELINES = DEFAULT_PROMPT_GUIDELINES;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolPromptGuidelines.cjs","names":[],"sources":["../src/constants/promptGuidelines.ts"],"sourcesContent":["/**\n * Cross-call behaviour the schema cannot express.\n *\n * Every rule lives in exactly one surface. Argument-site mechanics belong to\n * the parameter descriptions in `schemas/task.ts`, the use/do-not-use policy\n * and session scoping belong to the tool description, and general delegation\n * judgement belongs to the Team orchestrator prompt. What is left here is what\n * none of those three can carry: how calls should be sequenced across a turn.\n */\nexport const DEFAULT_PROMPT_GUIDELINES: string[] = [\n 'Batch the whole plan in one upsert: {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Research the store\"},{\"subject\":\"Write the reducer\"}]}. Report progress one call at a time: mark a task in_progress before you start it and completed the moment it lands, never batched at the end of a turn. Keep one task in_progress for your own work; delegated tasks run in parallel and do not count.',\n 'Never mark a task completed while tests fail or the work is partial. Use failed, or keep it in_progress and add a task for the blocker in the same upsert.',\n 'When every non-deleted task is completed, review the list once and call {\"action\":\"clear\"}.',\n \"Status flow: pending, in_progress, completed. failed is recoverable, deleted is a tombstone. Pass activeForm (e.g. 'writing tests') when marking in_progress.\",\n 'upsert applies each entry independently: passing entries commit and failures are reported by array index. Resend only the corrected failures, because resending an applied entry with no id creates a duplicate task.',\n 'Apply the session delegation criteria before choosing what to delegate, then call subagent {\"action\":\"agents\"} and use an exact discovered name. Prefer a general-purpose write-capable agent such as delegate or worker when no specialist fits, and use a focused inlineAgent only for read-only work.',\n 'Assign through assignments[] even for a single task: {\"action\":\"assign\",\"assignments\":[{\"id\":1,\"agent\":\"researcher\"}]}. Put independent ready tasks in one batch rather than repeated calls or multi_tool, and do not start a direct subagent run for work already on the task list. Successful entries keep running when another entry fails, so retry only the failures.',\n 'Fill relevantFiles only with files you actually read or located, and priorFindings only with verified facts in a few lines, not directives. A guessed path costs more than an omitted one.',\n 'Subject stays short and imperative. description is the durable brief handed to the subagent, extended at assign time by instructions, relevantFiles and priorFindings, so do not repeat one in the other.',\n 'When a delegated task completes and unblocks another, reconsider it promptly. If a child asks for a decision or an assignment fails to start, respond, rescope or retry instead of leaving it pending.
|
|
1
|
+
{"version":3,"file":"toolPromptGuidelines.cjs","names":[],"sources":["../src/constants/promptGuidelines.ts"],"sourcesContent":["/**\n * Cross-call behaviour the schema cannot express.\n *\n * Every rule lives in exactly one surface. Argument-site mechanics belong to\n * the parameter descriptions in `schemas/task.ts`, the use/do-not-use policy\n * and session scoping belong to the tool description, and general delegation\n * judgement belongs to the Team orchestrator prompt. What is left here is what\n * none of those three can carry: how calls should be sequenced across a turn.\n */\nexport const DEFAULT_PROMPT_GUIDELINES: string[] = [\n 'Batch the whole plan in one upsert: {\"action\":\"upsert\",\"tasks\":[{\"subject\":\"Research the store\"},{\"subject\":\"Write the reducer\"}]}. Report progress one call at a time: mark a task in_progress before you start it and completed the moment it lands, never batched at the end of a turn. Keep one task in_progress for your own work; delegated tasks run in parallel and do not count.',\n 'Never mark a task completed while tests fail or the work is partial. Use failed, or keep it in_progress and add a task for the blocker in the same upsert.',\n 'When every non-deleted task is completed, review the list once and call {\"action\":\"clear\"}.',\n \"Status flow: pending, in_progress, completed. failed is recoverable, deleted is a tombstone. Pass activeForm (e.g. 'writing tests') when marking in_progress.\",\n 'upsert applies each entry independently: passing entries commit and failures are reported by array index. Resend only the corrected failures, because resending an applied entry with no id creates a duplicate task.',\n 'Apply the session delegation criteria before choosing what to delegate, then call subagent {\"action\":\"agents\"} and use an exact discovered name. Prefer a general-purpose write-capable agent such as delegate or worker when no specialist fits, and use a focused inlineAgent only for read-only work.',\n 'Assign through assignments[] even for a single task: {\"action\":\"assign\",\"assignments\":[{\"id\":1,\"agent\":\"researcher\"}]}. Put independent ready tasks in one batch rather than repeated calls or multi_tool, and do not start a direct subagent run for work already on the task list. Successful entries keep running when another entry fails, so retry only the failures.',\n 'Fill relevantFiles only with files you actually read or located, and priorFindings only with verified facts in a few lines, not directives. A guessed path costs more than an omitted one.',\n 'Subject stays short and imperative. description is the durable brief handed to the subagent, extended at assign time by instructions, relevantFiles and priorFindings, so do not repeat one in the other.',\n 'When a delegated task completes and unblocks another, reconsider it promptly. If a child asks for a decision or an assignment fails to start, respond, rescope or retry instead of leaving it pending. Po Task records delegated lifecycle and results on the task itself.',\n];\n"],"mappings":";;;;;;;;;;;AASA,MAAa,4BAAsC;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|