@mcoda/codali 0.1.135-codali.40 → 0.1.135-codali.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +8 -0
  3. package/config/skills/testing-and-verification/SKILL.md +5 -5
  4. package/config/skills/webapp-testing/SKILL.md +13 -0
  5. package/config/skills/webapp-testing/journey-driver.mjs +85 -0
  6. package/dist/cli/TerminalCommand.js +2 -2
  7. package/dist/cli/tui/TerminalPresentation.js +1 -1
  8. package/dist/config/OrchestrationConfig.d.ts +1 -0
  9. package/dist/config/OrchestrationConfig.d.ts.map +1 -1
  10. package/dist/config/OrchestrationConfig.js +8 -3
  11. package/dist/docdex/DocdexClient.d.ts +11 -0
  12. package/dist/docdex/DocdexClient.d.ts.map +1 -1
  13. package/dist/docdex/DocdexClient.js +55 -1
  14. package/dist/permissions/PermissionGate.d.ts +7 -0
  15. package/dist/permissions/PermissionGate.d.ts.map +1 -1
  16. package/dist/permissions/PermissionGate.js +26 -0
  17. package/dist/providers/ConfiguredProvider.d.ts +2 -0
  18. package/dist/providers/ConfiguredProvider.d.ts.map +1 -1
  19. package/dist/providers/ConfiguredProvider.js +29 -0
  20. package/dist/providers/ModelServiceError.d.ts +2 -2
  21. package/dist/providers/ModelServiceError.d.ts.map +1 -1
  22. package/dist/providers/ModelServiceError.js +4 -0
  23. package/dist/runtime/AnswerVerification.d.ts +14 -0
  24. package/dist/runtime/AnswerVerification.d.ts.map +1 -1
  25. package/dist/runtime/AnswerVerification.js +26 -0
  26. package/dist/runtime/ContextCompression.d.ts +5 -0
  27. package/dist/runtime/ContextCompression.d.ts.map +1 -1
  28. package/dist/runtime/ContextCompression.js +16 -4
  29. package/dist/runtime/FigureCheck.d.ts +20 -0
  30. package/dist/runtime/FigureCheck.d.ts.map +1 -0
  31. package/dist/runtime/FigureCheck.js +44 -0
  32. package/dist/runtime/InteractionContract.d.ts +22 -0
  33. package/dist/runtime/InteractionContract.d.ts.map +1 -1
  34. package/dist/runtime/InteractionContract.js +41 -0
  35. package/dist/runtime/InteractionRouter.d.ts +3 -3
  36. package/dist/runtime/InteractionRouter.d.ts.map +1 -1
  37. package/dist/runtime/InteractionRouter.js +1 -1
  38. package/dist/runtime/OutageWait.d.ts +33 -5
  39. package/dist/runtime/OutageWait.d.ts.map +1 -1
  40. package/dist/runtime/OutageWait.js +68 -8
  41. package/dist/runtime/ResearchEvidence.d.ts +21 -1
  42. package/dist/runtime/ResearchEvidence.d.ts.map +1 -1
  43. package/dist/runtime/ResearchEvidence.js +109 -3
  44. package/dist/runtime/ReviewCoordinator.d.ts.map +1 -1
  45. package/dist/runtime/ReviewCoordinator.js +2 -1
  46. package/dist/runtime/ReviewSource.d.ts +5 -0
  47. package/dist/runtime/ReviewSource.d.ts.map +1 -1
  48. package/dist/runtime/ReviewSource.js +6 -1
  49. package/dist/runtime/SessionController.d.ts +71 -1
  50. package/dist/runtime/SessionController.d.ts.map +1 -1
  51. package/dist/runtime/SessionController.js +553 -39
  52. package/dist/runtime/TaskReview.d.ts.map +1 -1
  53. package/dist/runtime/TaskReview.js +17 -2
  54. package/dist/runtime/VerificationCommand.d.ts +8 -0
  55. package/dist/runtime/VerificationCommand.d.ts.map +1 -1
  56. package/dist/runtime/VerificationCommand.js +114 -0
  57. package/dist/runtime/WorkingStyle.d.ts +20 -0
  58. package/dist/runtime/WorkingStyle.d.ts.map +1 -0
  59. package/dist/runtime/WorkingStyle.js +71 -0
  60. package/dist/tools/ToolRegistry.d.ts.map +1 -1
  61. package/dist/tools/ToolRegistry.js +19 -2
  62. package/dist/tools/ToolTypes.d.ts +3 -0
  63. package/dist/tools/ToolTypes.d.ts.map +1 -1
  64. package/dist/tools/browser/BrowserTool.d.ts +23 -1
  65. package/dist/tools/browser/BrowserTool.d.ts.map +1 -1
  66. package/dist/tools/browser/BrowserTool.js +83 -4
  67. package/dist/tools/browser/HttpFallback.d.ts +39 -0
  68. package/dist/tools/browser/HttpFallback.d.ts.map +1 -0
  69. package/dist/tools/browser/HttpFallback.js +240 -0
  70. package/dist/tools/calculation/CalculatorTool.d.ts +16 -1
  71. package/dist/tools/calculation/CalculatorTool.d.ts.map +1 -1
  72. package/dist/tools/calculation/CalculatorTool.js +147 -20
  73. package/dist/tools/shell/AsyncProcess.d.ts.map +1 -1
  74. package/dist/tools/shell/AsyncProcess.js +6 -0
  75. package/dist/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  76. package/dist/tools/shell/IsolatedExecutor.js +10 -2
  77. package/dist/tools/shell/ShellTool.d.ts +2 -0
  78. package/dist/tools/shell/ShellTool.d.ts.map +1 -1
  79. package/dist/tools/shell/ShellTool.js +32 -2
  80. package/dist/tools/verification/VitestTool.d.ts.map +1 -1
  81. package/dist/tools/verification/VitestTool.js +75 -5
  82. package/package.json +3 -3
@@ -4,6 +4,12 @@ import { runProcess } from "./AsyncProcess.js";
4
4
  import { resolveShellWorkingDirectory } from "./ShellWorkingDirectory.js";
5
5
  /** Shared by terminal execution and tool-enabled benchmark baselines. */
6
6
  export const DEVELOPMENT_COMMANDS = ["git", "rg", "grep", "node", "npm", "pnpm", "npx", "python3", "pytest", "cargo", "rustc", "go", "make", "cmake", "tsc", "sh", "bash", "ls", "cat", "pwd", "expr", "printf", "head", "tail", "sed", "awk", "uname", "which", "env", "find", "wc", "sort", "uniq", "cut", "diff", "file", "stat", "du", "df", "mkdir", "touch", "cp", "mv", "rm", "curl", "wget", "tar", "unzip", "zip", "cc", "gcc", "g++", "clang", "clang++", "ar", "swift", "swiftc", "java", "javac", "xcrun", "xcodebuild", "google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
7
+ /** A fixed two minutes ended test suites and browser journeys fifteen times in
8
+ * one 12-hour build; the caller can now ask for the time a command needs. */
9
+ /** What to use when a listed command is missing on the host. */
10
+ const MISSING_ALTERNATIVES = { rg: "grep -rn (add -E for extended patterns)", fd: "find", python3: "node", pytest: "python3 -m unittest", pnpm: "npm", tsc: "npx tsc" };
11
+ export const DEFAULT_SHELL_TIMEOUT_SECONDS = 120;
12
+ export const MAX_SHELL_TIMEOUT_SECONDS = 900;
7
13
  const resolveAllowlist = (context) => {
8
14
  return context.shellAllowlist ?? [];
9
15
  };
@@ -56,6 +62,7 @@ export const createShellTool = () => ({
56
62
  args: { type: "array", items: { type: "string" } },
57
63
  cwd: { type: "string", description: "Existing working directory inside the workspace, relative to its root. Default: workspace root. Does not change the base of writePaths." },
58
64
  writePaths: { type: "array", items: { type: "string" }, description: "Terminal mode: root-relative existing files/directories to make writable, regardless of cwd. Default: no workspace writes. Must fit the claimed task scope." },
65
+ timeoutSeconds: { type: "integer", minimum: 1, maximum: MAX_SHELL_TIMEOUT_SECONDS, description: `Time allowed for this command. Default ${DEFAULT_SHELL_TIMEOUT_SECONDS}; raise it (up to ${MAX_SHELL_TIMEOUT_SECONDS}) for a full test suite, a build or a browser journey that needs longer.` },
59
66
  },
60
67
  },
61
68
  handler: async (args, context) => {
@@ -64,7 +71,10 @@ export const createShellTool = () => ({
64
71
  retryable: false,
65
72
  });
66
73
  }
67
- const { command, args: commandArgs = [], cwd } = args;
74
+ const { command, args: commandArgs = [], cwd, timeoutSeconds } = args;
75
+ if (timeoutSeconds !== undefined && (!Number.isSafeInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > MAX_SHELL_TIMEOUT_SECONDS)) {
76
+ throw new ToolExecutionError("tool_invalid_args", `timeoutSeconds must be a whole number from 1 to ${MAX_SHELL_TIMEOUT_SECONDS}`, { retryable: false });
77
+ }
68
78
  if (!context.allowDestructiveOperations
69
79
  && !context.shellIsolated
70
80
  && isDestructiveShellAction(command, commandArgs)) {
@@ -96,6 +106,26 @@ export const createShellTool = () => ({
96
106
  }
97
107
  effectiveArgs.splice(at, 0, "-o", "pipefail");
98
108
  }
99
- return (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory });
109
+ // A host may set the default (shellTimeoutMs) and the most a command may ask
110
+ // for (shellMaxTimeoutMs). A host that sets only a default keeps it as the cap.
111
+ const defaultMs = context.shellTimeoutMs ?? DEFAULT_SHELL_TIMEOUT_SECONDS * 1000;
112
+ const maxMs = context.shellMaxTimeoutMs ?? (context.shellTimeoutMs !== undefined ? context.shellTimeoutMs : MAX_SHELL_TIMEOUT_SECONDS * 1000);
113
+ const shellTimeoutMs = timeoutSeconds === undefined ? defaultMs : Math.min(timeoutSeconds * 1000, maxMs);
114
+ try {
115
+ return await (context.shellExecutor ?? runProcess)(command, effectiveArgs, { ...context, shellWorkingDirectory, shellTimeoutMs });
116
+ }
117
+ catch (error) {
118
+ // An allowed command that is not installed on this machine (rg on a host
119
+ // without ripgrep) is named as such, with what to use instead.
120
+ const missing = error instanceof ToolExecutionError ? /execvp ([\w.+-]+): No such file or directory|spawn ([\w.+-]+) ENOENT/.exec(`${error.message} ${String(error.details?.stderr ?? "")}`) : null;
121
+ if (missing) {
122
+ const name = missing[1] ?? missing[2];
123
+ throw new ToolExecutionError("tool_execution_failed", `${name} is not installed on this machine.${MISSING_ALTERNATIVES[name] ? ` Use ${MISSING_ALTERNATIVES[name]} instead.` : " Use another available command."}`, { retryable: false, details: error.details });
124
+ }
125
+ if (error instanceof ToolExecutionError && error.code === "tool_timeout" && shellTimeoutMs < maxMs) {
126
+ error.message += `\nThe command was stopped after ${Math.round(shellTimeoutMs / 1000)} s. If it needs longer, pass timeoutSeconds (up to ${Math.floor(maxMs / 1000)}); start servers in the background so the call can return.`;
127
+ }
128
+ throw error;
129
+ }
100
130
  },
101
131
  });
@@ -1 +1 @@
1
- {"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAyCF,eAAO,MAAM,gBAAgB,QAAO,cAwGlC,CAAC"}
1
+ {"version":3,"file":"VitestTool.d.ts","sourceRoot":"","sources":["../../../src/tools/verification/VitestTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E;+EAC+E;AAC/E,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,MAGpD,CAAC;AAiFF,eAAO,MAAM,gBAAgB,QAAO,cAsIlC,CAAC"}
@@ -60,9 +60,48 @@ async function runnerRuntime() {
60
60
  throw Error("Vitest runtime does not match the pinned version");
61
61
  return { entry, version, mounts: [...mounts] };
62
62
  }
63
+ /** Standard-library stand-in for the part of pytest that generated tests use. */
64
+ const PYTEST_STAND_IN = `import math,re
65
+ class _Raises:
66
+ def __init__(self,expected,match=None): self.expected=expected; self.match=match; self.value=None
67
+ def __enter__(self): return self
68
+ def __exit__(self,kind,value,trace):
69
+ if kind is None: raise AssertionError('DID NOT RAISE '+str(self.expected))
70
+ if not issubclass(kind,self.expected): return False
71
+ if self.match is not None and not re.search(self.match,str(value)): raise AssertionError('raised message '+repr(str(value))+' does not match '+repr(self.match))
72
+ self.value=value; return True
73
+ def raises(expected,*args,match=None,**kwargs):
74
+ if args:
75
+ with _Raises(expected,match): args[0](*args[1:],**kwargs)
76
+ return None
77
+ return _Raises(expected,match)
78
+ class approx:
79
+ def __init__(self,expected,rel=None,abs=None): self.expected=expected; self.rel=1e-6 if rel is None else rel; self.abs=1e-12 if abs is None else abs
80
+ def _one(self,actual,expected): return math.isclose(actual,expected,rel_tol=self.rel,abs_tol=self.abs)
81
+ def __eq__(self,actual):
82
+ e=self.expected
83
+ if isinstance(e,dict): return isinstance(actual,dict) and actual.keys()==e.keys() and all(self._one(actual[k],e[k]) for k in e)
84
+ if isinstance(e,(list,tuple)): return len(actual)==len(e) and all(self._one(a,b) for a,b in zip(actual,e))
85
+ return self._one(actual,e)
86
+ def __ne__(self,actual): return not self.__eq__(actual)
87
+ def __repr__(self): return 'approx('+repr(self.expected)+')'
88
+ def fail(reason=''): raise AssertionError(reason)
89
+ class _Mark:
90
+ def parametrize(self,names,values,**ignored):
91
+ keys=[n.strip() for n in names.split(',')] if isinstance(names,str) else list(names)
92
+ def wrap(fn):
93
+ rows=[tuple(v) if len(keys)>1 else (v,) for v in values]
94
+ earlier=getattr(fn,'_codali_params',[()]); earlier_names=getattr(fn,'_codali_names',())
95
+ fn._codali_params=[tuple(r)+tuple(e) for r in rows for e in earlier]; fn._codali_names=tuple(keys)+tuple(earlier_names)
96
+ return fn
97
+ return wrap
98
+ def __getattr__(self,name): raise AttributeError('pytest.mark.'+name+' is not available in this runner; only parametrize is')
99
+ mark=_Mark()
100
+ def __getattr__(name): raise AttributeError('pytest.'+name+' is not available in this runner (stand-in provides raises, approx, fail and mark.parametrize); use the standard library')
101
+ `;
63
102
  export const createVitestTool = () => ({
64
103
  name: "verify_tests", readOnly: true, capability: "verification",
65
- description: "Run supplied tests offline: runner vitest (default) for JS/TS, node for node:test, python for standard-library unittest (test_*.py). Use the requested language/runner without translating tests. No workspace/config/credentials. Reports supplied-test results, not independent proof.",
104
+ description: "Run supplied tests offline: runner vitest (default) for JS/TS, node for node:test, python for unittest classes and pytest-style test_ functions or Test classes in test_*.py (pytest.raises/approx/parametrize only; no fixtures, async tests or plugins). Use the requested language/runner without translating tests. No workspace/config/credentials. Reports supplied-test results, not independent proof.",
66
105
  inputSchema: { type: "object", properties: { runner: { type: "string", enum: ["vitest", "node", "python"] }, files: { type: "array", minItems: 1, maxItems: 12, items: { type: "object", properties: {
67
106
  path: { type: "string", minLength: 1, maxLength: 160 }, content: { type: "string", maxLength: 24000 },
68
107
  }, required: ["path", "content"], additionalProperties: false } } }, required: ["files"], additionalProperties: false },
@@ -94,13 +133,44 @@ export const createVitestTool = () => ({
94
133
  await fs.mkdir(path.join(root, "artifacts"));
95
134
  if (runner !== "vitest") {
96
135
  const tests = args.files.filter(file => testPattern.test(file.path)).map(file => path.join(root, file.path));
97
- const python = `import unittest,sys,os,json,importlib.util
136
+ // Models write pytest-style tests (plain test_* functions, pytest.raises,
137
+ // approx, parametrize) far more often than unittest classes; cycle 6 lost
138
+ // twelve test runs to "pytest is not installed". A small stand-in covers
139
+ // that subset on the standard library; anything else says so by name.
140
+ if (runner === "python" && !args.files.some(file => file.path === "pytest.py" || file.path.startsWith("pytest/")))
141
+ await fs.writeFile(path.join(root, "pytest.py"), PYTEST_STAND_IN);
142
+ const python = `import unittest,sys,os,json,importlib.util,inspect
98
143
  sys.path.insert(0,os.getcwd())
99
144
  suite=unittest.TestSuite()
145
+ def one(name,fn,owner=None):
146
+ sets=getattr(fn,'_codali_params',[()])
147
+ for index,values in enumerate(sets):
148
+ names=getattr(fn,'_codali_names',())
149
+ kwargs=dict(zip(names,values))
150
+ needed=[p for p in inspect.signature(fn).parameters if p not in kwargs and p!='self']
151
+ def run(fn=fn,kwargs=kwargs,needed=needed):
152
+ if inspect.iscoroutinefunction(fn) or inspect.isasyncgenfunction(fn): raise RuntimeError('async test '+name+' is not run by this runner: make it a plain function and call asyncio.run(...) inside it')
153
+ if inspect.isgeneratorfunction(fn): raise RuntimeError('generator test '+name+' is not run by this runner: its body after the first yield would never execute')
154
+ if needed: raise RuntimeError('fixture '+needed[0]+' is not available in this runner: build the value inside the test or use unittest setUp')
155
+ if owner is None: return fn(**kwargs)
156
+ target=owner()
157
+ if hasattr(target,'setup_method'): target.setup_method(fn)
158
+ try: getattr(target,fn.__name__)(**kwargs)
159
+ finally:
160
+ if hasattr(target,'teardown_method'): target.teardown_method(fn)
161
+ yield unittest.FunctionTestCase(run,description=name+('['+str(index)+']' if len(sets)>1 else ''))
162
+ def cases(module):
163
+ for name,item in sorted(vars(module).items()):
164
+ if getattr(item,'__module__',None)!=module.__name__: continue
165
+ if name.startswith('test') and inspect.isfunction(item): yield from one(name,item)
166
+ elif name.startswith('Test') and inspect.isclass(item) and not issubclass(item,unittest.TestCase):
167
+ for method,fn in sorted(vars(item).items()):
168
+ if method.startswith('test') and inspect.isfunction(fn): yield from one(name+'.'+method,fn,item)
100
169
  for i,file in enumerate(sys.argv[1:]):
101
170
  spec=importlib.util.spec_from_file_location('codali_test_'+str(i),file)
102
- module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
171
+ module=importlib.util.module_from_spec(spec);sys.modules[spec.name]=module;spec.loader.exec_module(module)
103
172
  suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
173
+ suite.addTests(cases(module))
104
174
  result=unittest.TextTestRunner(verbosity=2).run(suite)
105
175
  data={'total':result.testsRun,'failedTests':len(result.failures)+len(result.errors)+len(result.unexpectedSuccesses),'pendingTests':len(result.skipped)+len(result.expectedFailures)}
106
176
  data['passedTests']=data['total']-data['failedTests']-data['pendingTests']
@@ -122,14 +192,14 @@ sys.exit(0 if result.wasSuccessful() and data['total']>0 and data['pendingTests'
122
192
  if (runner === "python") {
123
193
  const stat = await fs.lstat(reportPath).catch(() => undefined);
124
194
  if (!stat)
125
- throw new ToolExecutionError("tool_execution_failed", `Python tests could not start. This runner loads standard-library unittest.TestCase tests; third-party packages such as pytest are not installed. Fix the reported import/syntax error or use unittest.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
195
+ throw new ToolExecutionError("tool_execution_failed", `Python tests could not start. This runner loads unittest.TestCase classes and plain test_* functions, with a stand-in for pytest.raises, pytest.approx and pytest.mark.parametrize; other third-party packages are not installed. Fix the reported import/syntax error.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
126
196
  if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16000)
127
197
  throw new Error("Invalid test report");
128
198
  }
129
199
  const report = runner === "node" ? { total: count("tests"), passedTests: count("pass"), failedTests: count("fail"), pendingTests: count("skipped") + count("todo") + count("cancelled") }
130
200
  : JSON.parse(await fs.readFile(reportPath, "utf8"));
131
201
  if (!Object.values(report).every(value => Number.isSafeInteger(value) && Number(value) >= 0) || report.total < 1)
132
- throw new ToolExecutionError("tool_execution_failed", `No complete test results were produced. Python requires unittest.TestCase methods named test_*; Node requires node:test cases. Zero executed tests cannot establish correctness.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
202
+ throw new ToolExecutionError("tool_execution_failed", `No complete test results were produced. Python requires test_* functions or unittest.TestCase methods named test_*; Node requires node:test cases. Zero executed tests cannot establish correctness.\n${testFailureSummary(output)}`, { details: { exitCode, output } });
133
203
  const result = { library: runner === "node" ? "node:test" : "unittest", ...report,
134
204
  passed: exitCode === 0 && report.failedTests === 0 && report.pendingTests === 0 && report.passedTests === report.total,
135
205
  diagnostic: testFailureSummary(output).slice(0, 1800), sourceSha256: createHash("sha256").update(payload).digest("hex"), elapsedMs: Date.now() - started,
package/package.json CHANGED
@@ -9,8 +9,8 @@
9
9
  "url": "https://github.com/bekirdag/mcoda/issues"
10
10
  },
11
11
  "dependencies": {
12
- "@mcoda/db": "0.1.135-codali.40",
13
- "@mcoda/shared": "0.1.135-codali.40",
12
+ "@mcoda/db": "0.1.135-codali.42",
13
+ "@mcoda/shared": "0.1.135-codali.42",
14
14
  "@modelcontextprotocol/sdk": "1.30.0",
15
15
  "ajv": "8.20.0",
16
16
  "browser-use": "0.9.0",
@@ -58,5 +58,5 @@
58
58
  },
59
59
  "type": "module",
60
60
  "types": "dist/index.d.ts",
61
- "version": "0.1.135-codali.40"
61
+ "version": "0.1.135-codali.42"
62
62
  }