uireSort(value, defaultValue = 'recency') {
    const v = String(value ?? defaultValue).trim().toLowerCase();
    if (!SORT_VALUES.has(v)) {
        throw new ArgumentError(`upwork sort must be one of ${Array.from(SORT_VALUES).join(' / ')}, got "${value}"`

 Build the Upwork search URL. Only forwards filters the user actually
 * supplied so the URL stays canonical and round-trippable.
 */
export function buildSearchUrl({ query, location, category, sort, page, perPage }) {
    const params = new URLSearchParam


code(encoding)
                    return (
                        "nbformat" in notebook_content
                        and "nbformat_minor" in notebook_content
                    )
                finally:
                    file_stream.seek(cur_pos)

*kwargs: Any,  # Options to pass to the converter
    ) -> DocumentConverterResult:
        # Parse and convert the notebook
        encoding = stream_info.charset or "utf-8"
        notebook_content = file_stream.read().decode(encoding=encoding)
        r

        return False

    def convert(
        self,
        file_stream: BinaryIO,
        stream_info: StreamInfo,
        *


am.read()).decode("utf-8")
        except Exception as e:
            return None
        finally:
            file_stream.seek(cur_pos)

        # Prepare the data-uri
        data_uri = f"data:{content_type};base64,{base64_image}"

        # Prepare the

    "image_url": {
                            "url": data_uri,
                        },
                    },
                ],
            }
        ]

        # Call the OpenAI API
        response = client.chat.completions.create(model=model, messa

OpenAI API request
        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},
                    {
                        "type": "image_url",


szel/internal/entities/system"
)

// ConnectionManager manages the connection state and events for the agent.
// It handles both WebSocket and SSH connections, automatically switching between
// them based on availability and managing reconnection attempts

WebSocketClient     // WebSocket client for hub communication
	serverOptions  ServerOptions        // Configuration for SSH server
	wsTicker       *time.Ticker         // Ticker for WebSocket connection attempts
	isConnecting   bool                 // Prev

.
type ConnectionManager struct {
	agent          *Agent               // Reference to the parent agent
	State          ConnectionState      // Current connection state
	eventChan      chan ConnectionEvent // Channel for connection events
	wsClient       *


ect(plainLogOutput().some((line) => line.includes("Couldn't check for updates"))).toBe(true);
    expect(plainLogOutput().some((line) => line.includes("npm install -g ctx7@latest"))).toBe(true);
  });

  test("shows retry guidance when the upgrade command

event === "close") handler(243);
        return undefined;
      },
    });
    checkForUpdates.mockResolvedValue({
      currentVersion: "0.3.13",
      latestVersion: "0.3.99",
      updateAvailable: true,
      installMethod: "npm-global",
      upgrade

fails", async () => {
    spawn.mockReturnValue({
      on: (event: string, handler: (value?: number) => void) => {
        if (


ls["html"])
            assert response.status == 200
            assert session.page_pool.pages_count == 0

            # Check pool stats
            stats = session.get_pool_stats()
            assert stats["total_pages"] == 0
            assert stats["

test_dynamic_session_with_options(self, urls):
        """Test AsyncDynamicSession with various options"""
        async with AsyncDynamicSession(
                headless=False,
                disable_resources=True,
                extra_headers={"X-Tes


r)

		var signal *core.InterruptSignal
		assert.True(t, errors.As(err, &signal))
		assert.Len(t, signal.Subs, 2)
	})
}

func TestGetInterruptState(t *testing.T) {
	t.Run("not interrupted returns false", func(t *testing.T) {
		ctx := context.Background()

)
		assert.False(t, wasInterrupted)
		assert.False(t, hasState)
		assert.Empty(t, state)
	})
}

func TestGetResumeContext(t *testing.T) {
	t.Run("not resume target returns false", func(t *testing.T) {
		ctx := context.Background()
		isResumeTarget, hasData

wasInterrupted, hasState, state := GetInterruptState[string](ctx


(hook.work_dir())
                .args(&entry[1..])
                .env(EnvVars::PATH, &new_path)
                .env(EnvVars::CONDA_PREFIX, env_dir)
                .env_remove(EnvVars::PYTHONHOME)
                .env_remove(EnvVars::VIRTUAL_ENV)

               .file_args(batch)
                .check(false)
                .stdin(Stdio::null())
                .pty_output_with_sink(reporter.output_sink(progress))
                .await?;

            reporter.on_run_progress(progress, batch.len()

            .envs(&hook.env)
                .args(&hook.args)


t-token")

	_, err2 := newWebSocketClient(agent)
	assert.Error(t, err2, "WebSocket client creation should fail with invalid URL")

	// Test with missing token
	t.Setenv("BESZEL_AGENT_HUB_URL", "http://localhost:8080")
	t.Setenv("BESZEL_AGENT_TOKEN", "")

{
	agent := createTestAgent(t)
	cm := agent.connectionManager
	cm.eventChan = make(chan ConnectionEvent, 1)

	// Test that isConnecting flag prevents duplicate reconnection attempts
	// Start from connected state, then simulate disconnect
	cm.State = WebSo

_, err3 := newWebSocketClient(agent)
	assert.Error(t, err3, "WebSocket client creation should fail without token")
}

// TestConnectionManager_ReconnectionLogic tests reconnection prevention logic
func TestConnectionManager_ReconnectionLogic(t *testing.T)


ileSync(path.join(agentsDir, 'cavecrew-reviewer.md'), 'utf8');
    assert.strictEqual(out, REVIEWER_FM, 'file should be unchanged when env unset');
  });
});

test('body content preserved after model patch', () => {
  withTmpPlugin((root, agentsDir) => {

path.join(agentsDir, 'cavecrew-reviewer.md'), 'utf8');
    assert.ok(out.includes('## Extra'), 'extra body section lost');
    assert.ok(out.includes('Extra section body.'), 'body text lost');
  });
});

// ── Summary ──────────────────────────────────────

   const content = REVIEWER_FM + '\n\n## Extra\n\nExtra section body.\n';
    fs.writeFileSync(path.join(agentsDir, 'cavecrew-reviewer.md'), content, 'utf8');
    applyOverrides(root, { CAVECREW_REVIEWER_MODEL: 'sonnet' });
    const out = fs.readFileSync(


sage
from browser_use.llm.ollama.serializer import OllamaMessageSerializer
from browser_use.llm.views import ChatInvokeCompletion

T = TypeVar('T', bound=BaseModel)

@dataclass
class ChatOllama(BaseChatModel):
	"""
	A wrapper around Ollama's chat model.

 None = None
	ollama_options: Mapping[str, Any] | Options | None = None

	# Static
	@property
	def provider(self) -> str:
		return 'ollama'

	def _get_client_params(self) -> dict[str, Any]:
		"""Prepare client parameters dictionary."""
		return {
			'host'

"""

	model: str

	# # Model params
	# TODO (matic): Why is this commented out?
	# temperature: float | None = None

	# Client initialization parameters
	host: str | None = None
	timeout: float | httpx.Timeout | None = None
	client_params: dict[str, Any] |


sDir, 'badschema', projectRoot);
    expect(progress).toEqual({ total: 2, completed: 1 });
  });

  it('counts a single top-level tasks.md unchanged under the default schema', async () => {
    // No project-local schema, no .openspec.yaml -> default spec-

 = await getTaskProgressForChange(changesDir, 'plain', projectRoot);
    expect(progress).toEqual({ total: 3, completed: 2 });
  });

  it('reports zero tasks when no file matches the tracked glob', async () => {
    await writeGlobSchema();
    await writ

driven (tracks tasks.md).
    await writeChange('plain', { 'tasks.md': '- [x] a\n- [x] b\n- [ ] c\n' }, '');

    const progress


> Result<()> {
    with_openai_cassette_result(
        CassetteSpec::new("multi_extract/batch_multi_extract_chain").unordered(),
        |client| async move {
            let names_extractor = client
                .extractor::<Names>(openai::GPT_4O_MINI

)
                .retries(2)
                .build();
            let topics_extractor = client
                .extractor::<Topics>(openai::GPT_4O_MINI)
                .preamble("Extract topics from the given text.")
                .retries(2)

)
                .preamble("Extract names from the given text."


port os
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
BROWSER_USE_REPO_SKILL_URL = 'https://raw.githubusercontent.com/browser-use/browser-use/main/skills/browser-use/SKILL.md'
EXPECTED_SKILL_INSTALL_PATHS

Path('.claude') / 'skills' / 'browser-use' / 'SKILL.md',
	Path('.codex') / 'skills' / 'browser-use' / 'SKILL.md',
	Path('.copilot') / 'skills' / 'browser-use' / 'SKILL.md',
	Path('.cursor') / 'skills' / 'browser-use' / 'SKILL.md',
	Path('.gemini') / 'skill

 = (
	Path('.agents') / 'skills' / 'browser-use' / 'SKILL.md',


"sqlite-vec.h"
#include "sqlite3.h"
#include <assert.h>

int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  if (size < 2) return 0;

  int rc;
  sqlite3 *db;

  rc = sqlite3_open(":memory:", &db);
  assert(rc == SQLITE_OK);
  rc = sqlite3_vec

0,0], [0,-1,0,1], [1,1,0,1] as little-endian float32 hex
  rc = sqlite3_exec(db,
    "CREATE VIRTUAL TABLE v USING vec0(emb float[4]);"
    "INSERT INTO v(rowid, emb) VALUES (1, X'0000803f000000000000000000000000');"
    "INSERT INTO v(rowid, emb) VALUES (

_init(db, NULL, NULL);
  assert(rc == SQLITE_OK);

  // Build a valid table with 3 vectors (float[4] = 16 bytes each)
  // [1,0,


	traversal string slips through, the (1)/(2) collision-avoidance logic
	silently writes outside the intended directory."""

	async def test_unique_filename_on_basename_stays_inside_dir(self, tmp_path: Path) -> None:
		# Pre-sanitized name — what the caller

await DownloadsWatchdog._get_unique_filename(str(tmp_path), 'report.pdf')
		assert result == 'report.pdf'
		# The resolved path lives inside tmp_path.
		assert DownloadsWatchdog._is_path_contained(tmp_path / result, tmp_path)

	async def test_unique_filena


dirAll(mmcDeviceDir, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.MkdirAll(mmcQueueDir, 0o755); err != nil {
		t.Fatal(err)
	}

	write := func(path, content string) {
		t.Helper()
		if err := os.WriteFile(path, []byte(content), 0o644); err != nil {

time"), "0x04 0x05\n")
	write(filepath.Join(mmcDeviceDir, "name"), "H26M52103FMR\n")
	write(filepath.Join(mmcDeviceDir, "serial"), "01234567\n")
	write(filepath.Join(mmcDeviceDir, "prv"), "0x08\n")
	write(filepath.Join(mmcQueueDir, "logical_block_size"), "

			t.Fatal(err)
		}
	}

	write(filepath.Join(mmcDeviceDir, "pre_eol_info"), "0x02\n")
	write(filepath.Join(mmcDeviceDir, "life_


 created by the watchdog
		non_blank_tabs = [tab for tab in tabs_info if 'about:blank' not in tab.url]
		assert len(non_blank_tabs) == 1, (
			f'Should have one non-blank tab open after closing the second, but got {len(non_blank_tabs)}: {non_blank_tabs}'

anymore
	# @pytest.mark.asyncio
	# async def test_remove_highlights(self, browser_session, base_url):
	# 	"""Test that remove_highlights successfully removes highlight elements."""
	# 	# Navigate to a test page
	# 	from browser_use.browser.events import Na

	)
		assert base_url in non_blank_tabs[0].url, 'The remaining tab should be the home page'

	# TODO: highlighting doesn't exist


icationShown(info.latestVersion);
    log.blank();
    return;
  }

  if (!info.upgradePlan.canRun) {
    log.box([
      `${pc.white(pc.bold("Update available:"))} ${pc.green(pc.bold(`v${info.currentVersion}`))} ${pc.dim("->")} ${pc.green(pc.bold(`v${info

{pc.white("Or run")} ${pc.yellow(info.upgradePlan.displayCommand)}`,
    ]);
    await markUpdateNotificationShown(info.latestVersion);
    log.blank();
    return;
  }

  log.box([
    `${pc.white(pc.bold("Update available:"))} ${pc.green(pc.bold(`v${info

.latestVersion}`))}`,
      `${pc.white("Run")} ${pc.yellow(pc.bold("ctx7 upgrade"))} ${pc.white("for update steps")}`,
      `$


ath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, '..', '..');
const PS1 = fs.readFileSync(path.join(REPO_ROOT, 'install.ps1'), 'utf8');

// Strip comment lines so doc mentions of param()/path vars don't false-positive.
const code = PS1.split('\n

', () => {
  const beforeFunction = code.slice(0, code.indexOf('function '));
  assert.ok(code.includes('function '), 'install.ps1 must wrap its logic in a function for iex piping');
  assert.ok(
    !/param\s*\(/i.test(beforeFunction),
    'install.ps1 mu

').filter(l => !/^\s*#/.test(l)).join('\n');

test('#565 install.ps1 has no top-level param block (everything inside a function)


ed_ns      INTEGER NOT NULL,
  ended_ns        INTEGER NOT NULL,
  duration_ns     INTEGER NOT NULL,
  cumulative_rows INTEGER NOT NULL,   -- total rows inserted so far
  rate_rows_per_s REAL    NOT NULL    -- cumulative rate
);

CREATE TABLE IF NOT EXISTS

,
  run_id            INTEGER NOT NULL REFERENCES runs(run_id),
  k                 INTEGER NOT NULL,
  query_vector_id   INTEGER NOT NULL,
  started_ns        INTEGER NOT NULL,
  ended_ns          INTEGER NOT NULL,
  duration_ms       REAL    NOT NULL,

 queries (
  query_id          INTEGER PRIMARY KEY AUTOINCREMENT


ons = generateInstructions(context, 'specs');

    expect(instructions.skipped).toBe(true);
    expect(instructions.warning).toContain('Do not create spec files');
  });

  it('marks the specs dependency as skipped instead of done with files to read', () =

    const tasksInstructions = generateInstructions(context, 'tasks');
    const specsDep = tasksInstructions.dependencies.find((d) => d.id === 'specs');
    expect(specsDep?.skipped).toBe(true);

    const output = capture('tasks');
    expect(output).toC

> {
    const context = loadChangeContext(tempDir, 'my-change');


).unwrap_or_default()
            };
            match &self.filter {
                Some(filter) => Ok(filter(messages)),
                None => Ok(messages),
            }
        })
    }

    fn append<'a>(
        &'a self,
        conversation_id:

or_default()
                .extend(messages);
            Ok(())
        })
    }

    fn clear<'a>(
        &'a self,
        conversation_id: &'a str,
    ) -> WasmBoxedFuture<'a, Result<(), MemoryError>> {
        Box::pin(async move {
            let

&'a str,
        messages: Vec<Message>,
    ) -> WasmBoxedFuture<'a, Result<(), MemoryError>> {
        Box::pin(async move {
            let mut guard = self.lock()?;
            guard
                .entry(conversation_id.to_string())
                .


 to run — we drive it purely through a throwaway HERMES_HOME.
//
// The uninstall test is the important one: PR #524 shipped installHermes with
// NO matching uninstall block, so `--uninstall` silently orphaned all 7 skill
// folders forever. This pins the

';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath

 symmetry so it cannot regress.

import { test } from 'node:test


ent" in headers`,
				},
			},
		},
		{
			name: "both-or-and",
			inp: `{
			"all": ["\"User-Agent\" in headers"],
			"any": ["\"User-Agent\" in headers"]
			}`,
			validErr: ErrExpressionCantHaveBoth,
		},
		{
			name: "expression-empty",
			inp: `{
			"

	if err := json.Unmarshal([]byte(tt.inp), &eol); !errors.Is(err, tt.err) {
				t.Errorf("wanted unmarshal error: %v but got: %v", tt.err, err)
			}

			if tt.result != nil && !eol.Equal(tt.result) {
				t.Logf("wanted: %#v", tt.result)
				t.Logf("got:

any": []
			}`,
			validErr: ErrExpressionEmpty,
		},
	} {
		t.Run(tt.name, func(t *testing.T) {
			var eol ExpressionOrList


getLogger(__name__)

@dataclass
class ChatGroq(BaseChatModel):
	"""
	A wrapper around AsyncGroq that implements the BaseLLM protocol.
	"""

	# Model configuration
	model: GroqVerifiedModels | str

	# Model params
	temperature: float | None = None
	service

: float | None = None
	seed: int | None = None

	# Client initialization parameters
	api_key: str | None = None
	base_url: str | URL | None = None
	timeout: float | Timeout | NotGiven | None = None
	max_retries: int = 10  # Increase default retries for aut

_tier: Literal['auto', 'on_demand', 'flex'] | None = None
	top_p


}: React.ComponentProps<typeof Button>) {
  const { orientation, scrollPrev, canScrollPrev } = useCarousel()

  return (
    <Button
      data-slot="carousel-previous"
      variant={variant}
      size={size}
      className={cn(
        "absolute touch-

          ? "top-1/2 -left-12 -translate-y-1/2"
          : "-top-12 left-1/2 -translate-x-1/2 rotate-90",
        className
      )}
      disabled={!canScrollPrev}
      onClick={scrollPrev}
      {...props}
    >
      <HugeiconsIcon icon={ArrowLeft01I

manipulation rounded-full",
        orientation === "horizontal"


ssion_id: str | None = None) -> None:
					# no-op; included to mirror CDP API surface used by impl
					pass

			class _Send:
				def __init__(self, outer: 'StubCDP') -> None:
					self.Fetch = _FetchSend(outer)

			class _FetchRegister:
				def __init__(

					self._outer = outer

				def authRequired(self, callback) -> None:
					self._outer.auth_callback = callback

				def requestPaused(self, callback) -> None:
					self._outer.request_paused_callback = callback

			class _Register:
				def __init__(sel


    return;
  }

  const ctx = result as ContextResponse;

  if (ctx.error) {
    if (ctx.redirectUrl) {
      spinner?.warn("Library has been redirected");
      if (!spinner) log.warn("Library has been redirected");
      log.info(`New ID: ${pc.cyan(ctx.

`Run: ${pc.cyan(`ctx7 docs "${ctx.redirectUrl}" "${query}"`)}`);
      process.exitCode = 1;
      return;
    }

    spinner?.fail(ctx.message || ctx.error);
    if (!spinner) log.error(ctx.message || ctx.error);
    process.exitCode = 1;
    return;
  }


_name()).build();

    let response: SmokeStructuredOutput = agent
        .prompt_typed(STRUCTURED_OUTPUT_PROMPT)
        .await
        .expect("structured output prompt should succeed");

    assert_smoke_structured_output(&response);
}

#[tokio::test]

]
async fn prompt_typed_structured_output() {
    let client = support::completions_client();
    let model = support::model_name();
    let agent = client
        .agent(model)
        .preamble(WEATHER_PREAMBLE)
        .temperature(0.0)
        .build()

#[ignore = "requires a local llama.cpp OpenAI-compatible server"


d retries. */
@Documented
@Constraint(validatedBy = RetryPolicyConstraint.RetryValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RetryPolicyConstraint {
  /** input constraint message. */
  String message()

extends Payload>[] payload() default {};

  /** RetryPolicy validator. */
  class RetryValidator implements ConstraintValidator<RetryPolicyConstraint, RetryPolicy> {
    private static final String DUMMY_EVALUATED_RESULT = "2";
    private static final Lon

 default "";

  /** input constraint groups. */
  Class<?>[] groups() default {};

  /** input constraint payload. */
  Class<?


r.MethodSource;

public class SdkTemporaryPathCredentialTest extends BaseCRUDTestWithMockCredentials {
  private TemporaryCredentialsApi temporaryCredentialsApi;

  @Override
  protected CatalogOperations createCatalogOperations(ServerConfig serverConfig)

serverConfig));
  }

  @Override
  protected SchemaOperations createSchemaOperations(ServerConfig serverConfig) {
    return new SdkSchemaOperations(TestUtils.createApiClient(serverConfig));
  }

  @BeforeEach
  @Override
  public void setUp() {
    super.

{
    return new SdkCatalogOperations(TestUtils.createApiClient(


ops }: SelectPrimitive.Group.Props) {
  return (
    <SelectPrimitive.Group
      data-slot="select-group"
      className={cn("scroll-my-1 p-1", className)}
      {...props}
    />
  )
}

function SelectValue({ className, ...props }: SelectPrimitive.Value

"select-value"
      className={cn("flex flex-1 text-left", className)}
      {...props}
    />
  )
}

function SelectTrigger({
  className,
  size = "default",
  children,
  ...props
}: SelectPrimitive.Trigger.Props & {
  size?: "sm" | "default"
}) {
  re

.Props) {
  return (
    <SelectPrimitive.Value
      data-slot=


      log.plain(pc.bold(snippet.codeTitle));
      if (snippet.codeDescription) log.dim(snippet.codeDescription);
      log.blank();
      for (const code of snippet.codeList) {
        log.plain("```" + code.language);
        log.plain(code.code);

   }
  }
}

export function registerDocsCommands(program: Command): void {
  program
    .command("library")
    .argument("<name>", "Library name to search for")
    .argument("[query]", "What to look up in the library's documentation")
    .option("--jso

  log.plain("```");
        log.blank();
      }
    }
  }

  if (ctx.infoSnippets) {
    for (const snippet of ctx.infoSnippets) {
      if (snippet.breadcrumb) log.plain(pc.bold(snippet.breadcrumb));
      log.plain(snippet.content);
      log.blank();


lepath.Join("..", "config", "testdata", "good", st.Name()))
				if err != nil {
					t.Fatal(err)
				}
				defer fin.Close() //nolint:errcheck

				if _, err := ParseConfig(t.Context(), fin, fin.Name(), anubis.DefaultDifficulty, "info", false); err != nil

		})
	}
}

func TestBadConfigs(t *testing.T) {
	ctx := thothmock.WithMockThoth(t)

	finfos, err := os.ReadDir("../config/testdata/bad")
	if err != nil {
		t.Fatal(err)
	}

	for _, st := range finfos {
		t.Run(st.Name(), func(t *testing.T) {
			fin, err :=


string);
  }

  /**
   * Asserts the call fails with PERMISSION_DENIED (HTTP 403) and the exception message contains
   * {@code containsMessage}. Use this when the test cares that a specific authz check fired -- e.g.
   * a staging-table ownership check -

 static void assertPermissionDenied(Executable executable, String containsMessage) {
    assertApiException(executable, ErrorCode.PERMISSION_DENIED, containsMessage);
  }

  /**
   * Asserts the call fails with PERMISSION_DENIED (HTTP 403). Only checks the

- rather than just that something produced a 403.
   */
  public


t:blank",
    "--password-store=basic",
    "--disable-hang-monitor",
    "--no-default-browser-check",
    "--disable-session-crashed-bubble",
    "--disable-search-engine-choice-screen",
)

STEALTH_ARGS = (
    # Explanation: https://peter.sh/experiments

"--test-type",
    "--lang=en-US",
    "--mute-audio",
    "--disable-sync",
    "--hide-scrollbars",
    "--disable-logging",
    "--start-maximized",  # For headless check bypass
    "--enable-async-dns",
    "--accept-lang=en-US",
    "--use-mock-keycha

/chromium-command-line-switches/
    # Generally this will make the browser faster and less detectable
    # "--incognito",


 m[1] : '';
}
/** Extract all values of a named attribute across repeated tags. */
function extractAllAttr(xml, tag, attr) {
    const re = new RegExp(`<${tag}\\b[^>]*?\\b${attr}="([^"]*)"`, 'g');
    const out = [];
    let m;
    while ((m = re.exec(xml)

]);
    return out;
}
/** Find the href of the first <link> tag matching a given rel. */
function findLinkHref(xml, rel) {
    const re = /<link\b([^>]*)\/?>/g;
    let m;
    while ((m = re.exec(xml)) !== null) {
        const attrs = m[1];
        if (ne


ver:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
        link: "text-primary underline-offset-4 hover:underline",

:
          "h-7 gap-1 px-2 text-xs/relaxed has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
        xs: "h-5 gap-1 rounded-sm px-2 text-[0.625rem] has-data-[icon=inline-end]:pr-1.5 has-data-[ic


enter gap-2 rounded-md border bg-muted px-2.5 text-xs/relaxed font-medium [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
          className
        ),
      },
      props
    ),
    render,
    state: {
      slot: "button-group-text"

orientation = "vertical",
  ...props
}: React.ComponentProps<typeof Separator>) {
  return (
    <Separator
      data-slot="button-group-separator"
      orientation={orientation}
      className={cn(
        "relative self-stretch bg-input data-horizonta

,
    },
  })
}

function ButtonGroupSeparator({
  className,


s import MSO_SHAPE_TYPE

from markitdown import MarkItDown
from markitdown.converters._pptx_converter import PptxConverter

TEST_FILES_DIR = os.path.join(os.path.dirname(__file__), "test_files")

# A tiny synthetic PPTX whose only picture is an SVG without

:blip> has no r:embed, only an <asvg:svgBlip> extension
# pointing to an embedded SVG. Its alt text is "Red square SVG".
SVG_NO_FALLBACK_PPTX = os.path.join(TEST_FILES_DIR, "test_svg_no_fallback.pptx")

_SVG_NS = "http://schemas.microsoft.com/office/drawin


tStatus> {
    if !store.path().exists() {
        writeln!(printer.stdout(), "{}", "Nothing to clean".bold())?;
        return Ok(ExitStatus::Success);
    }

    let num_paths = walkdir::WalkDir::new(store.path()).into_iter().count();
    let reporter =

all(store.path(), Some(&reporter))?;

    match (removal.num_files, removal.num_dirs) {
        (0, 0) => {
            write!(printer.stderr(), "No cache entries found")?;
        }
        (0, 1) => {
            write!(printer.stderr(), "Removed 1 direc

CleaningReporter::new(printer, num_paths);

    if let Err(e) = fix_permissions(store.cache_path(CacheBucket::Go))
        && e.kind() != io::ErrorKind::NotFound
    {
        error!("Failed to fix permissions: {}", e);
    }

    let removal = remove_dir_


t.jupiter.api.Test;

/**
 * SDK-based access control tests for Registered Model and Model Version CRUD operations.
 *
 *
This test class verifies:
 *
 *

 *
Model creation requires CREATE MODEL permission on schema
 *
Model get requires

filtered based on ownership
 *
Model update requires ownership
 *
Model version creation requires ownership of parent model
 *
Model version get requires ownership
 *
Model version list requires ownership
 *
Model version upd


RENT_TIMESTAMP NOT NULL,         -- last modified timestamp
  PRIMARY KEY (workflow_id)
);

CREATE TABLE IF NOT EXISTS maestro_workflow_timeline (  -- table to store the workflow changes
  workflow_id   TEXT NOT NULL COLLATE "C",
  change_event  JSONB NOT

 DEFAULT CURRENT_TIMESTAMP NOT NULL,
  PRIMARY KEY (workflow_id, create_ts, hash_id)
);

CREATE TABLE IF NOT EXISTS maestro_workflow_version (   -- table of workflow version history, immutable
  workflow_id   TEXT NOT NULL COLLATE "C",
  version_id    INT8

NULL,
  hash_id       INT8 NOT NULL,
  create_ts     TIMESTAMPTZ


ut, /claude\b/);
  assert.match(r.stdout, /gemini\b/);
  assert.match(r.stdout, /antigravity\b.*\(soft\)/);
});

test('unknown flag exits 2 with error', () => {
  const r = run('--bogus');
  assert.equal(r.status, 2);
  assert.match(r.stderr, /unknown flag

 mutually exclusive', () => {
  const r = run('--all', '--minimal');
  assert.equal(r.status, 2);
  assert.match(r.stderr, /mutually exclusive/);
});

test('--only without arg fails', () => {
  const r = run('--only');
  assert.equal(r.status, 2);
  assert


tar.gz">archiveok'
        resp = _make_response(html)
        urls = LinkExtractor().extract(resp)
        assert urls == ["https://example.com/d"]

    def test_custom_deny_extensions_overrides_default(self):
        html = '<a href=

>zip</a>'
        resp = _make_response(html)
        urls = LinkExtractor(deny_extensions={"zip"}).extract(resp)
        # .pdf now allowed because we replaced the set
        assert urls == ["https://example.com/a.pdf"]

    def test_custom_deny_extensio


r error

	if network == "" {
		// keep compatibility
		network, address, err = parseBindNetFromAddr(address)
	}

	if err != nil {
		return nil, "", fmt.Errorf("can't parse bind and network: %w", err)
	}

	switch network {
	case "unix":
		formattedAddress =

":") { // assume it's just a port e.g. :4259
			formattedAddress = "http://localhost" + address
		} else {
			formattedAddress = "http://" + address
		}
	default:
		formattedAddress = fmt.Sprintf(`(%s) %s`, network, address)
	}

	ln, err := net.Listen(netw

 "unix:" + address
	case "tcp":
		if strings.HasPrefix(address,


    ):
        self.attempts = attempts

        if message is None:
            if attempts is None:
                message = "File conversion failed."
            else:
                message = f"File conversion failed after {len(attempts)} attempts:\

f" -  {type(attempt.converter).__name__} provided no execution info."
                    else:
                        message += f" - {type(attempt.converter).__name__} threw {attempt.exc_info[0].__name__} with message: {attempt.exc_info[1]}\n"

n"
                for attempt in attempts:
                    if attempt.exc_info is None:
                        message +=


ocusChangedEvent(self, event: AgentFocusChangedEvent) -> None:
		"""Re-apply headers when the agent switches to a different tab."""
		try:
			await self.browser_session.set_extra_headers(CUSTOM_HEADERS, target_id=event.target_id)
		except Exception as e:

:8]}: {e}')

async def main():
	browser = Browser(headless=False)

	# Start the browser so watchdogs are initialized
	await browser.start()

	# Attach our custom watchdog to the browser session
	CustomHeadersWatchdog.model_rebuild()
	headers_watchdog = Cu

self.logger.debug(f'Could not set headers on {event.target_id[


instead when:**
- You want to delegate an entire web task as a black box
- You don't need control over individual browser actions

## Pick Your Integration

| Your agent type | Best approach | Control level |
|----------------|---------------|-------------

 | [CLI commands](#shell-command-agents-cli) | Per-command |
| TypeScript/JS | [CDP + Playwright](#typescriptjs-cdp--playwright) | Playwright API |
| MCP client (Claude Desktop, Cursor) | [Local MCP server](#mcp-native-agents) | MCP tools |
| Existing Play


ask='test', llm=mock_llm, browser_session=browser_session, tools=tools)

		results = await agent.multi_act(actions)

		# go_back should terminate the sequence — only 1 result
		assert len(results) == 1, f'Expected 1 result but got {len(results)}: {results}

, remaining actions skipped
# ---------------------------------------------------------------------------

class TestRuntimeGuard:
	"""Verify that URL/focus changes detected at runtime abort remaining actions."""

	async def test_click_link_aborts_remaini


s",
        [
            {"real_chrome": True, "disable_resources": True},
            {"wait_selector": "h1", "wait_selector_state": "attached"},
            {"wait_selector": "h1", "wait_selector_state": "visible"},
            {
                "google

    "extra_headers": {"ayo": ""},
                "useragent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:131.0) Gecko/20100101 Firefox/131.0",
                "cookies": [{"name": "test", "value": "123", "domain": "example.com", "path": "/"}],

_search": True,
                "real_chrome": True,
                "wait": 10,
                "locale": "en-US",


        encoding = stream_info.charset or "utf-8"
        notebook_content = file_stream.read().decode(encoding=encoding)
        return self._convert(json.loads(notebook_content))

    def _convert(self, notebook_content: dict) -> DocumentConverterResult:

 converts notebook JSON content to Markdown."""
        try:
            md_output = []
            title = None

            for cell in notebook_content.get("cells", []):
                cell_type = cell.get("cell_type", "")
                source_lines


l.Type{cel.StringType, cel.StringType},
				cel.BoolType,
				cel.BinaryBinding(func(addr, pattern ref.Val) ref.Val {
					addrStr, ok := addr.(types.String)
					if !ok {
						return types.ValOrErr(addr, "addr is not a string")
					}
					patternStr, ok

if !ok {
						return types.ValOrErr(pattern, "pattern is not a string")
					}
					p := string(patternStr)
					return types.Bool(dnsObj.VerifyFCrDNS(string(addrStr), &p))
				}),
			),
		),

		// arpaReverseIP transforms ip into arpa reverse notation li


tal_tokens > 0);

            Ok(())
        },
    )
    .await
}

#[tokio::test]
async fn extract_and_extract_with_usage_return_same_data() -> Result<()> {
    with_xai_cassette_result(
        "extractor_usage/extract_and_extract_with_usage_return_same_

    let text = "Bob Johnson is a 55 year old retired teacher.";
            let person = extractor.extract(text).await?;
            let response = extractor.extract_with_usage(text).await?;

            anyhow::ensure!(person.name.as_deref() == Some("Bob

data",
        |client| async move {
            let extractor = client.extractor::<Person>(xai::GROK_3_MINI).build();


class SearchResult(BaseModel):
    title: str
    url: str

agent = Agent(task="...", llm=llm, output_model_schema=SearchResult)
history = await agent.run()
result = history.structured_output  # SearchResult instance
```

---

## Prompting Guide

### Be

= """
1. Go to https://quotes.toscrape.com/
2. Use extract action with the query "first 3 quotes with their authors"
3. Save results to quotes.csv using write_file action
"""

# Bad
task = "Go to web and make money"
```

### Name Actions Directly

```pytho


 preview, upload nothing
//   (any extra args are passed through to `clawhub skill publish`)

const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');

const root = path.join(__dirname, '..');
const skillsDir

parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version;

// Every generated skill dir with a SKILL.md is publishable. Reading the dir
// (instead of a hardcoded list) covers whatever build-openclaw-skills emits,
// with nothing to keep in

= path.join(root, '.openclaw', 'skills');

const version = JSON.


P_MAX_SIZE = 64 * 1024 * 1024  # 64 MiB cap, defends against gzip bombs

@dataclass
class SitemapResult:
    """Parsed sitemap body.

    `urls` holds the entries from a `<urlset>`; `sitemaps` holds child sitemap
    URLs from a `<sitemapindex>` (each of

   """

    urls: List[str] = field(default_factory=list)
    sitemaps: List[str] = field(default_factory=list)

class SitemapSpider(Spider):
    """A Spider that seeds a crawl from sitemap(s), and follows the rules.

    Override `rules()` to return a li


lf._started:
            return

        for sid, session in self._sessions.items():
            if sid not in self._lazy_sessions and not session._is_alive:
                await session.__aenter__()

        self._started = True

    async def close(self

for sid, session in self._sessions.items():
            if sid in self._lazy_sessions and not session._is_alive:
                continue
            _ = await session.__aexit__(None, None, None)

        self._started = False

    async def fetch(self, re

) -> None:
        """Close all registered sessions."""


          AS last_name,
    la.cntry                           AS country,
    ci.cst_marital_status              AS marital_status,
    CASE
        WHEN ci.cst_gndr != 'n/a' THEN ci.cst_gndr -- CRM is the primary source for gender
        ELSE COALESCE(

                     AS gender,
    ca.bdate                           AS birthdate,
    ci.cst_create_date                 AS create_date
FROM silver.crm_cust_info ci
LEFT JOIN silver.erp_cust_az12 ca
    ON ci.cst_key = ca.cid
LEFT JOIN silver.erp_loc_a1

ca.gen, 'n/a')  			   -- Fallback to ERP data
    END


meSummary =
        StepRuntimeSummary.builder()
            .stepId("test-summary")
            .stepAttemptId(2)
            .stepInstanceId(1)
            .dbOperation(DbOperation.DELETE)
            .build();
    Optional<Details> details = syncManager

 stepRuntimeSummary);
    assertTrue(details.isPresent());
    assertEquals("Failed to sync a Maestro step state change", details.get().getMessage());
    assertFalse(details.get().getErrors().isEmpty());
    assertEquals(
        "MaestroInternalError: In


 TestStealthySession:

    """All the code is tested in the async version tests, so no need to repeat it here. The async class inherits from this one."""
    @pytest.fixture(autouse=True)
    def setup_urls(self, httpbin):
        """Fixture to set up URLs

    self.status_501 = f"{httpbin.url}/status/501"
        self.basic_url = f"{httpbin.url}/get"
        self.html_url = f"{httpbin.url}/html"
        self.delayed_url = f"{httpbin.url}/delay/10"  # 10 Seconds delay response
        self.cookies_url = f"{ht

 for testing"""
        self.status_200 = f"{httpbin.url}/status/200"
        self.status_404 = f"{httpbin.url}/status/404"


_kwargs, self._include_headers, self._keep_fragments)

        if not request.dont_filter and fingerprint in self._seen:
            log.debug("Dropped duplicate request: %s", request)
            return False

        self._seen.add(fingerprint)

 counter, request)
        self._pending[counter] = item
        await self._queue.put(item)
        return True

    async def dequeue(self) -> Request:
        """Get the next request to process (stays tracked until complete())."""
        _, counter, re

# Negative priority so higher priority = dequeued first
        counter = next(self._counter)
        item = (-request.priority,


el use arithmetic tools instead of answering from scratch.

use anyhow::Result;
use rig::completion::Prompt;
use rig::prelude::*;
use rig::providers::openai;
use rig::tool::{DynamicTool, ToolOutput};
use serde::Deserialize;
use serde_json::json;

#[derive(

fn runtime_tools() -> Vec<DynamicTool> {
    let parameters = json!({
        "type": "object",
        "properties": {
            "x": { "type": "integer" },
            "y": { "type": "integer" }
        },
        "required": ["x", "y"]
    });
    vec

Deserialize)]
struct OperationArgs {
    x: i32,
    y: i32,
}


=("$1")
      shift
      ;;
  esac
done

# Desktop fallback keeps the legacy item name unless one was named explicitly.
if [ -n "$ACCOUNT" ] && [ "$ITEM_EXPLICIT" -eq 0 ]; then
  ITEM="npmjs"
fi

if [ "${#ARGS[@]}" -eq 0 ]; then
  usage >&2
  exit 2
fi
if

 "refusing to run: 1Password commands require a persistent tmux session" >&2
  exit 2
fi
for bin in op jq node npm; do
  command -v "$bin" >/dev/null 2>&1 || {
    echo "missing required binary: $bin" >&2
    exit 2
  }
done

SCRIPT_DIR="$(cd "$(dirname "$


of(
                    new FunctionParameterInfo()
                        .name("param2")
                        .typeName(ColumnTypeName.INT)
                        .typeText("int")
                        .typeJson("{\"type\":\"int\"}")

        new CreateFunction()
            .name(COMMON_ENTITY_NAME)
            .catalogName(CATALOG_NAME)
            .schemaName(SCHEMA_NAME)
            .parameterStyle(CreateFunction.ParameterStyleEnum.S)
            .isDeterministic(true)
            .

           .position(0)));
    CreateFunction createFunction2 =


ttrib:
            return {}
        return {k: v.strip() for k, v in element.attrib.items() if v and v.strip() and k not in forbidden}

    @classmethod
    def element_to_dict(cls, element: html.HtmlElement) -> Dict:
        parent = element.getparent()

parent is not None:
            result.update(
                {
                    "parent_name": parent.tag,
                    "parent_attribs": dict(parent.attrib),
                    "parent_text": parent.text.strip() if parent.text else None,

        result = {
            "tag": str(element.tag),
            "attributes": cls.__clean_attributes(element),
            "text": element.text.strip() if element.text else None,
            "path": cls._get_element_path(element),
        }
        if


scribeRequest(RESOURCE_URI));
		transportProvider.simulateIncomingMessage(unsubscribeRequest(RESOURCE_URI));
		transport.clearSentMessages();

		StepVerifier.create(server.notifyResourcesUpdated(new McpSchema.ResourcesUpdatedNotification(RESOURCE_URI)))

).as("no notification should be sent after the session unsubscribed")
			.isEmpty();

		server.closeGracefully().block();
	}

	@Test
	void notifyResourcesUpdated_afterSessionClose_doesNotNotifySession() {
		MockMcpServerTransport transport = new MockMcpSer

	.verifyComplete();

		assertThat(transport.getAllSentMessages()


            return NotImplemented
        return self.priority > other.priority

    def __eq__(self, other: object) -> bool:
        """Requests are equal if they have the same fingerprint."""
        if not isinstance(other, Request):
            return

:
            raise RuntimeError("Cannot compare requests before generating their fingerprints!")
        return self._fp == other._fp

    def __getstate__(self) -> dict[str, Any]:
        """Prepare state for pickling - store callback as name string for

 NotImplemented
        if self._fp is None or other._fp is None


ted && isDeactivationCommand(prompt)) {
      clearMode();
      deactivated = true;
      writeHookOutput('UserPromptSubmit', 'off', 'PONYTAIL MODE OFF');
    }

    // Qoder has no SessionStart event, so UserPromptSubmit does double duty:
    // activate

this in
    // SessionStart via ponytail-activate.js; Qoder can't, so we do it here.
    // Skip when deactivated — user just turned ponytail off.
    if (isQoder && !deactivated) {
      let currentMode = readMode();
      if (!currentMode) {
        // F

 the default mode on first prompt (if no flag exists yet), then
    // inject the ruleset on every prompt. Claude Code/Codex do


 When adding or changing a provider, verify that the integration includes:
//!
//! - for OpenAI-chat-compatible APIs: completions driven by
//!   [`GenericCompletionModel`](crate::providers::openai::completion::GenericCompletionModel)
//!   via an
//!   [`

:OpenAICompatibleProvider)
//!   impl on the provider extension (never a hand-rolled completion model,
//!   request struct, or message conversion — dialect differences go in the
//!   trait's hooks);
//! - public `Client` and `ClientBuilder` aliases with


xplanation (${words} words of prose).` };
  },

  // Leaves ONE runnable check behind for non-trivial logic.
  onecheck(output) {
    const t = String(output || '');
    const hasCheck = /\bassert\b|def\s+test_|if\s+__name__|unittest|pytest|console\.assert

    ? { pass: true, reason: 'Left a runnable check (assert/test/demo).' }
      : { pass: false, reason: 'No runnable check left behind.' };
  },
};

module.exports = (output, context) => {
  const probe = context && context.vars && context.vars.probe;
  c

|\bexpect\(|\bdescribe\(|\bit\(/.test(t);
    return hasCheck


ect" && c !== null && !("type" in c && c.type === "separator")
  );
  const values = choices.map((c) => c.value);
  const totalItems = values.length;
  let cursorPosition = choices.findIndex((c) => !c.disabled);
  if (cursorPosition < 0) cursorPosition = 0

object has 'name' property
  const getName = options?.getName ?? ((v: T) => (v as { name: string }).name);

  const keypressHandler = (_str: string | undefined, key: readline.Key) => {
    if (key.name === "up") {
      let next = cursorPosition - 1;


focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
        link: "text-primary underline-offset-4 hover:underline",
      },
      size: {
        default:
          "h-7 gap-1 px-

_svg:not([class*='size-'])]:size-2.5",
        sm: "h-6 gap-1 px-2 text-xs/relaxed has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
        lg: "h-8 gap-1 px-2.5 text-xs/relaxed has-data-[icon=inl

2 text-xs/relaxed has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
        xs: "h-5 gap-1 rounded-sm px-2 text-[0.625rem] has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&


ment=[historical_element],
		),
		metadata=StepMetadata(step_start_time=1, step_end_time=2, step_number=2, step_interval=0.1),
	)

	history = AgentHistoryList(history=[navigate_step, click_step])

	try:
		# Should succeed via ax_name matching (Level 4)
		#

all fail but ax_name matches
		results = await agent.rerun_history(
			history,
			skip_failures=False,
			max_retries=1,
			summary_llm=mock_summary_llm,
		)

		# Navigation + click + summary
		assert len(results) == 3
		# Click should succeed (matched vi


muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 disabled:pointer-events-none disabled:cursor-not-allowed aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 data-[size=sm]:h-6 data

bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40"
        {...props}
      />
      <HugeiconsIcon icon={UnfoldMoreIcon} strokeWidth={2} className="pointer-events-none absolute top-1/2 right-1


nd]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",
        "group

   "data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",
        "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizont


ent),
        }
        if parent is not None:
            result.update(
                {
                    "parent_name": parent.tag,
                    "parent_attribs": dict(parent.attrib),
                    "parent_text": parent.text.strip() if

       }
            )

            siblings = [child.tag for child in parent.iterchildren() if child != element]
            if siblings:
                result.update({"siblings": tuple(siblings)})

        children = [child.tag for child in element.iter


 config -> default false (toast still shows)
    assert.equal(readQuietStartup(), false);

    // Config file true -> respected
    mkdirSync(configDir, { recursive: true });
    writeFileSync(configPath, JSON.stringify({ quietStartup: true }), "utf8");

), true);

    // Env var overrides config
    process.env.PONYTAIL_QUIET_STARTUP = "false";
    assert.equal(readQuietStartup(), false);
    process.env.PONYTAIL_QUIET_STARTUP = "1";
    assert.equal(readQuietStartup(), true);
  } finally {
    if (previo


://schemas.openxmlformats.org/'
            'presentationml/2006/main" xmlns:a="http://schemas.'
            'openxmlformats.org/drawingml/2006/main" xmlns:r="http://'
            'schemas.openxmlformats.org/officeDocument/2006/relationships" '

    self.part = _FakePart()

    @property
    def image(self):
        raise ValueError("no embedded image")

def test_is_picture_true_for_svg_placeholder() -> None:
    # _is_picture must not let shape.image's ValueError propagate for SVG
    # placehol

 'xmlns:asvg="%s"><a:blip><a:extLst><a:ext uri="{96DAC541-7B7A-'
            '43D3-8B79-37D633B846F1}"><asvg:svgBlip r:embed="rId9"/></a:ext>'
            "</a:extLst></a:blip></p:pic>" % _SVG_NS
        )
        self._element = etree.fromstring(xml)


r the relevant workflow stage

#### Scenario: Updating slash commands for OpenCode
- **WHEN** `.opencode/command/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
- **THEN** refresh each file using shared templates
- **AND**

 stage

#### Scenario: Updating slash commands for Windsurf
- **WHEN** `.windsurf/workflows/` contains `openspec-proposal.md`, `openspec-apply.md`, and `openspec-archive.md`
- **THEN** refresh each file using shared templates wrapped in OpenSpec markers
-

ensure templates include instructions for the relevant workflow


erge class-level parser arguments into per-request ``selector_config``.

    Values from ``Fetcher.configure(...)`` act as the base; any explicit
    ``selector_config`` passed on the call overrides them.
    """
    selector_config = kwargs.get("selector_

 Fetcher(BaseFetcher):
    """A basic `Fetcher` class type that can only do basic GET, POST, PUT, and DELETE HTTP requests based on `curl_cffi`."""

    @classmethod
    def get(cls, url: str, **kwargs: Unpack[GetRequestParams]) -> Response:
        return

config") or {}
    kwargs["selector_config"] = {**cls._generate_parser_arguments(), **selector_config}
    return kwargs

class


rvers emit one JSON
// object per line). We line-buffer in both directions and parse opportunistically.
function makeLineBuffer(onLine) {
  let buf = '';
  return chunk => {
    buf += chunk.toString('utf8');
    let nl;
    while ((nl = buf.indexOf('\n'))

slice(nl + 1);
      if (line.trim()) onLine(line);
    }
  };
}

function transformResponse(msg) {
  // Compress description fields on list-style responses. Match by method
  // shape — we don't always know the original request's method, so we
  // detect

 !== -1) {
      const line = buf.slice(0, nl);
      buf = buf.


se serde_json::json;

    #[test]
    fn test_sanitize_strips_ref_sibling_keywords() {
        let mut schema = json!({
            "type": "object",
            "properties": {
                "location": {
                    "$ref": "#/$defs/Location",

 "Location": {
                    "type": "object",
                    "properties": {
                        "city": { "type": "string" },
                        "state": { "type": "string" }
                    }
                }
            }

                    "description": "The user's location"
                }
            },
            "$defs": {


List<String> args, Map<String, String> env) {
		Assert.notNull(command, "The command can not be null");
		Assert.notNull(args, "The args can not be null");

		this.command = command;
		this.args = args;
		this.env = new HashMap<>(getDefaultEnvironment());

static Builder builder(String command) {
		return new Builder(command);
	}

	public static class Builder {

		private String command;

		private List<String> args = new ArrayList<>();

		private Map<String, String> env = new HashMap<>();

		public Builder(

		if (env != null && !env.isEmpty()) {
			this.env.putAll(env);
		}
	}

	public String getCommand() {
		return this.command;
	}

	public List<String> getArgs() {
		return this.args;
	}

	public Map<String, String> getEnv() {
		return this.env;
	}

	public


- duration: [TIME]

      first echo second

    ----- stderr -----
    ");
}

#[cfg(unix)]
#[test]
fn shell_runs_multiline_entry_as_one_script() {
    let context = TestContext::new();
    context.init_project();
    context.write_pre_commit_config(indoc:

  language: system
            entry: |
              echo first
              echo second
            shell: sh
            pass_filenames: false
            verbose: true
    "});
    context.git_add(".");

    cmd_snapshot!(context.filters(), context.ru

:indoc! {r"
    repos:
      - repo: local
        hooks:
          - id: shell-script
            name: shell-script


'utf8');
}

// Read inside each test (not at module scope) so a missing or malformed manifest
// surfaces as a clean per-test assertion failure, not a load-time crash that
// collapses every case into one unreadable stack trace.
function loadManifest() {

} must exist`);
  return JSON.parse(read(MANIFEST));
}

test('manifest names the ponytail extension with a pinned version', () => {
  const manifest = loadManifest();
  assert.equal(manifest.name, EXTENSION_NAME);
  assert.match(manifest.version, PINNED_SE


	assert metadata_default.step_interval is None

def test_step_interval_calculation():
	"""Test step_interval calculation logic (uses previous step's duration)"""
	# Previous step (Step 1): runs from 100.0 to 102.5 (duration: 2.5s)
	previous_start = 100.0

duration
	calculated_step_interval = max(0, previous_end - previous_start)

	assert abs(calculated_step_interval - expected_step_interval) < 0.001  # Float comparison
	assert calculated_step_interval == 2.5

def test_step_metadata_serialization_with_step_

	previous_end = 102.5
	previous_duration = previous_end - previous_start

	# Current step (Step 2): should have step_interval = previous step's duration
	# This tells the rerun system "wait 2.5s before executing Step 2"
	expected_step_interval = previous_


MA_NEW_FULL_NAME = CATALOG_NAME + "." + SCHEMA_NEW_NAME;
  public static final String SCHEMA_NEW_COMMENT = "new test comment";
  public static final String TABLE_FULL_NAME = CATALOG_NAME + "." + SCHEMA_NAME + "." + TABLE_NAME;
  public static final String

_NAME + "." + SCHEMA_NAME + "." + VOLUME_NAME;
  public static final String FUNCTION_FULL_NAME =
      CATALOG_NAME + "." + SCHEMA_NAME + "." + FUNCTION_NAME;
  public static final String MODEL_FULL_NAME = CATALOG_NAME + "." + SCHEMA_NAME + "." + MODEL_NAM


   INTEGER PRIMARY KEY AUTOINCREMENT,
  config_name     TEXT    NOT NULL,
  index_type      TEXT    NOT NULL,
  params          TEXT    NOT NULL,   -- JSON: {"R":48,"L":128,"quantizer":"binary"}
  dataset         TEXT    NOT NULL,   -- "cohere1m"
  subset_

             INTEGER NOT NULL,
  n_queries       INTEGER NOT NULL,
  phase           TEXT    NOT NULL DEFAULT 'both',
    -- 'build', 'query', or 'both'
  status          TEXT    NOT NULL DEFAULT 'pending',
    -- pending → inserting → training → querying


f struct MG_StrExprParseResult MG_StrExprParseResult;
struct MG_StrExprParseResult
{
  MG_StrExpr *root;
  MD_MsgList msgs;
  MD_Node *next_node;
};

////////////////////////////////
//~ rjf: Table Generation Types

typedef struct MG_NodeArray MG_NodeArray

struct MG_NodeGrid MG_NodeGrid;
struct MG_NodeGrid
{
  U64 x_stride;
  U64 y_stride;
  MG_NodeArray cells;
  MG_NodeArray row_parents;
};

typedef enum MG_ColumnKind
{
  MG_ColumnKind_DirectCell,
  MG_ColumnKind_CheckForTag,
  MG_ColumnKind_TagChild,
  MG_

;
struct MG_NodeArray
{
  MD_Node **v;
  U64 count;
};

typedef


NITS.len() - 1);
    (bytes_f32 / 1024_f32.powi(i as i32), UNITS[i])
}

pub(crate) fn dir_size_bytes(path: &Path) -> u64 {
    if !path.exists() {
        return 0;
    }

    walkdir::WalkDir::new(path)
        .follow_links(false)
        .into_iter()

entry.metadata() {
            Ok(metadata) if metadata.is_file() => Some(metadata.len()),
            _ => None,
        })
        .sum()
}

#[cfg(test)]
mod tests {
    use super::{dir_size_bytes, human_readable_bytes};
    use assert_fs::fixture::TempD

      .filter_map(Result::ok)
        .filter_map(|entry| match


sportProvider);

		transportProvider.simulateIncomingMessage(initRequest());
		transportProvider.simulateIncomingMessage(initializedNotification());
		transportProvider.simulateIncomingMessage(subscribeRequest(RESOURCE_URI));
		transport.clearSentMessages(

)
			.verifyComplete();

		assertThat(transport.getAllSentMessages())
			.as("notification for a different URI should not reach a session subscribed to a different URI")
			.isEmpty();

		server.closeGracefully().block();
	}

	@Test
	void notifyResourcesUp

);

		StepVerifier
			.create(server.notifyResourcesUpdated(new McpSchema.ResourcesUpdatedNotification("test://other/resource"))


h_none(self):
        """Test that None is returned as-is."""
        result = _select_random_browser(None)
        assert result is None

    def test_select_random_browser_with_list(self):
        """Test that a browser is randomly selected from a list."

 "firefox", "safari"]
        result = _select_random_browser(browsers)
        assert result in browsers

    def test_select_random_browser_with_empty_list(self):
        """Test that empty list returns None."""
        result = _select_random_browser([]


frame'

		# Try clicking the iframe element
		print('\n🖱  Testing Click on Iframe Element:')
		tools = Tools()

		link_idx, link_element = iframe_elements[0]
		print(f'   Attempting to click element [{link_idx}] from iframe...')

		try:
			result = await

	# Check for errors
			if result.error:
				pytest.fail(f'Click on iframe element [{link_idx}] failed with error: {result.error}')

			if result.extracted_content and (
				'not available' in result.extracted_content.lower() or 'failed' in result.extracted


ormation
    if table.index_stats("embedding").await?.is_none() {
        table
            .create_index(
                &["embedding"],
                lancedb::index::Index::IvfPq(IvfPqIndexBuilder::default()),
            )
            .execute()

will be used by the vector store to perform the vector search.
    let search_params = SearchParams::default();
    let vector_store_index = LanceDbVectorIndex::new(table, model, "id", search_params).await?;

    let query = "My boss says I zindle too much

        .await?;
    }

    // Define search_params params that


"C",   -- signal name is to group signal instances
  seq_id            INT8        NOT NULL,               -- sequence number to keep the order of signal instances per signal name
  instance_id       TEXT        NOT NULL COLLATE "C",   -- unique id, used f


print in self._seen:
            log.debug("Dropped duplicate request: %s", request)
            return False

        self._seen.add(fingerprint)

        # Negative priority so higher priority = dequeued first
        counter = next(self._counter)

)."""
        _, counter, request = await self._queue.get()
        self._inflight.setdefault(id(request), []).append(counter)
        return request

    def complete(self, request: Request) -> None:
        """Mark a request as finished so it stops being

  item = (-request.priority, counter, request)
        self._pending[counter] = item
        await self._queue.put(item)
        return True

    async def dequeue(self) -> Request:
        """Get the next request to process (stays tracked until complete()


_id   TEXT NOT NULL COLLATE "C",
  external_job_type TEXT NOT NULL COLLATE "C",
  workflow_id       TEXT NOT NULL,
  payload           JSON NOT NULL,
  create_ts         TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
  modify_ts         TIMESTAMPTZ DEFAULT CURRENT

-------

CREATE TABLE IF NOT EXISTS output_data (
  external_job


t at most this many times. If the authorization error persists after
	 * exhausting all retries, the transport will propagate the
	 * {@link McpHttpClientTransportAuthorizationException}.
	 * <p>
	 * Defaults to {@code 1}.
	 * @return the maximum number of

 * A no-op handler, used in the default use-case.
	 */
	McpHttpClientAuthorizationErrorHandler NOOP = new Noop();

	/**
	 * Create a {@link McpHttpClientAuthorizationErrorHandler} from a synchronous handler.
	 * Will be subscribed on {@link Schedulers#boun

 retries
	 */
	default int maxRetries() {
		return 1;
	}

	/**


ORMAL);
	cairo_set_font_size(Clay__Cairo, config->fontSize);

	// Use glyph extents for better precision
	cairo_scaled_font_t *scaled_font = cairo_get_scaled_font(Clay__Cairo);
	if (!scaled_font) {
		fprintf(stderr, "Failed to get scaled font\n");
		cairo_

);

	if (status != CAIRO_STATUS_SUCCESS || !glyphs || num_glyphs == 0) {
		fprintf(stderr, "Failed to generate glyphs: %s\n", cairo_status_to_string(status));
		cairo_restore(Clay__Cairo);
		free(text);
		return (Clay_Dimensions){0, 0};
	}

	// Measure the

restore(Clay__Cairo);
		free(text);
		return (Clay_Dimensions){0, 0};
	}

	cairo_glyph_t *glyphs = NULL;
	int num_glyphs = 0;
	cairo_status_t status = cairo_scaled_font_text_to_glyphs(
		scaled_font, 0, 0, text, -1, &glyphs, &num_glyphs, NULL, NULL, NULL


given network and address.
func parseBindNetFromAddr(address string) (string, string, error) {
	defaultScheme := "http://"
	if !strings.Contains(address, "://") {
		if strings.HasPrefix(address, ":") {
			address = defaultScheme + "localhost" + address
		}

tcp", "http", "https":
		return "tcp", bindUri.Host, nil
	default:
		return "", "", fmt.Errorf("unsupported network scheme %s in address %s", bindUri.Scheme, address)
	}
}

// SetupListener sets up a network listener based on the input from configuration
/

 else {
			address = defaultScheme + address
		}
	}

	bindUri, err := url.Parse(address)
	if err != nil {
		return "", "", fmt.Errorf("failed to parse bind URL: %w", err)
	}

	switch bindUri.Scheme {
	case "unix":
		return "unix", bindUri.Path, nil
	case "


kspace file for the set')
    .option('--force', 'Overwrite an existing --code-workspace file')
    .action(
      async (options: {
        store?: string;
        storePath?: string;
        json?: boolean;
        codeWorkspace?: string;
        force?:

try {
          const root = await resolveRootForCommand(
            { store: options.store, storePath: options.storePath },
            { json: options.json, failurePayload: FAILURE_PAYLOAD, allowImplicitRoot: false }
          );
          if (!root) {


le AssistantGenTextExtension chunks into one.
func ConcatAssistantGenTextExtensions(chunks []*AssistantGenTextExtension) (*AssistantGenTextExtension, error) {
	if len(chunks) == 0 {
		return nil, fmt.Errorf("no assistant generated text extension found")
	}

// ConcatResponseMetaExtensions merges multiple ResponseMetaExtension chunks into one.
func ConcatResponseMetaExtensions(chunks []*ResponseMetaExtension) (*ResponseMetaExtension, error) {
	if len(chunks) == 0 {
		return nil, fmt.Errorf("no response meta ex

	if len(chunks) == 1 {
		return chunks[0], nil
	}

	ret := &AssistantGenTextExtension{
		Citations: make([]*TextCitation, 0, len(chunks)),
	}

	for _, ext := range chunks {
		ret.Citations = append(ret.Citations, ext.Citations...)
	}

	return ret, nil
}


p tests fast.
- Optional constructor root param is a minimal DI surface that avoids global
  stubbing and keeps code simple.

## Risks & Mitigations

- Risk: Tests forget to restore `process.cwd()`.
  - Mitigation: Add `afterAll` guard restoring cwd; reset

  - Create and use a temp fixture root.
  - Do not read real `openspec/changes` during execution.
  - Pass consistently regardless of directory order or stray folders.
- No change to CLI behavior for end users (paths still default to cwd).

## Rollout

-

 `process.exitCode` in
    `afterEach` where modified.
- Risk: Behavior divergence if DI root is misused.
  - Mitigation: Default to `process.cwd()`; only tests pass custom roots.

## Acceptance Criteria

- Tests that previously depended on repo state now:


n',   // Qoder plugin
  'gemini-extension.json',       // Gemini CLI extension
  'package.json',                // pi-package / repo root
  'ponytail-mcp/package.json',   // MCP server (private, internal-only)
];

function readVersion(relPath) {
  try {

.parse).
    const raw = fs.readFileSync(path.join(root, relPath), 'utf8').replace(/^\uFEFF/, '');
    return JSON.parse(raw).version;
  } catch (e) {
    throw new Error(`${relPath}: ${e.message}`);
  }
}

let failed = false;
const versions = VERSION_FILE

// Strip a UTF-8 BOM some Windows editors prepend (breaks JSON


if (textEl.querySelector('${SEL.INDICATOR}') ||
          textEl.getAttribute('data-show-indicator') === 'true') continue;
      const isUser = container.classList.contains('justify-end');
      let text = '';
      const children = textEl.querySelectorAll

.length > 0) {
        text = Array.from(children).map(c => c.innerText || c.textContent || '').join('');
      } else {
        text = textEl.innerText?.trim() || textEl.textContent?.trim() || '';
      }
      if (!text) continue;
      results.push({ ro


provider supports streaming;
//! - provider-response error preservation plus `ProviderResponseExt` and
//!   telemetry fields consistent with nearby providers where applicable;
//! - unit, cassette, or live-test coverage appropriate to the changed behavior

 updates for companion provider crates; and
//! - examples and documentation that match the actual API, feature flags, and
//!   credential requirements.
//!
//! # Example
//! ```no_run
//! use rig_core::{
//!     client::{CompletionClient, ProviderClient}


go-v2/service/s3"
)

type Store struct {
	s3     S3API
	bucket string
}

func (s *Store) Delete(ctx context.Context, key string) error {
	normKey := strings.ReplaceAll(key, ":", "/")
	// Emulate not found by probing first.
	if _, err := s.s3.HeadObject(ctx

 nil {
		return fmt.Errorf("%w: %w", store.ErrNotFound, err)
	}
	if _, err := s.s3.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &s.bucket, Key: &normKey}); err != nil {
		return fmt.Errorf("can't delete from s3: %w", err)
	}
	return nil
}

func (s *Stor

, &s3.HeadObjectInput{Bucket: &s.bucket, Key: &normKey}); err !=


x in CANDIDATE_MIME_TYPE_PREFIXES:
            if mimetype.startswith(prefix):
                return self._check_xml(file_stream)

        return False

    def _check_xml(self, file_stream: BinaryIO) -> bool:
        cur_pos = file_stream.tell()

doc: Any) -> str | None:
        if doc.getElementsByTagName("rss"):
            return "rss"
        elif doc.getElementsByTagName("feed"):
            root = doc.getElementsByTagName("feed")[0]
            if root.getElementsByTagName("entry"):

try:
            doc = minidom.parse(file_stream)
            return self._feed_type(doc) is not None
        except BaseException as _:
            pass
        finally:
            file_stream.seek(cur_pos)
        return False

    def _feed_type(self,


n}
      style={{ "--gap": spacing } as React.CSSProperties}
      className={cn(
        "group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] rounded-md data-[size=sm]:rounded-[min(var(--radius-md),8px)] data-vertical:flex-col

      className
      )}
      {...props}
    >
      <ToggleGroupContext.Provider
        value={{ variant, size, spacing, orientation }}
      >
        {children}
      </ToggleGroupContext.Provider>
    </ToggleGroupPrimitive>
  )
}

function ToggleGro


hOperation.PATH_READ_WRITE);
      TemporaryCredentials temporaryCredentials =
          temporaryCredentialsApi.generateTemporaryPathCredentials(generateTemporaryPathCredential);
      EchoAwsStsClient.assertAwsCredential(temporaryCredentials);
    }

temporaryCredentialsApi.generateTemporaryPathCredentials(
                new GenerateTemporaryPathCredential()
                    .url(AWS_EXTERNAL_LOCATION_PARENT_PATH)
                    .operation(PathOperation.PATH_READ_WRITE)),
        ErrorCode.FA

// Should fail because the path is not covered by external location
    TestUtils.assertApiException(
        () ->


"--disable-print-preview",
    "--disable-dev-shm-usage",
    # '--disable-popup-blocking',
    "--metrics-recording-only",
    "--disable-crash-reporter",
    "--disable-partial-raster",
    "--disable-gesture-typing",
    "--disable-checker-imaging",

   "--force-color-profile=srgb",
    "--font-render-hinting=none",
    "--aggressive-cache-discard",
    "--disable-cookie-encryption",
    "--disable-domain-reliability",
    "--disable-threaded-animation",
    "--disable-threaded-scrolling",
    "--enabl


assName
      )}
      data-slot="native-select-wrapper"
      data-size={size}
    >
      <select
        data-slot="native-select"
        data-size={size}
        className="h-7 w-full min-w-0 appearance-none rounded-md border border-input bg-input/20

select-none selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 disabled:pointer-events-none disabled:cursor-not-allowed aria-invalid:border-dest

py-0.5 pr-6 pl-2 text-xs/relaxed transition-colors outline-none


LUME_FULL_NAME =
      CATALOG_NAME + "." + SCHEMA_NAME + "." + VOLUME_NAME;
  public static final String FUNCTION_FULL_NAME =
      CATALOG_NAME + "." + SCHEMA_NAME + "." + FUNCTION_NAME;
  public static final String MODEL_FULL_NAME = CATALOG_NAME + "." +

 + MODEL_NEW_NAME;
  public static final String COMMENT = "test comment";
  public static final String COMMENT2 = "test comment 2";
  public static final String CATALOG_NEW_NAME = "uc_newtestcatalog";
  public static final String CATALOG_NEW_COMMENT = "new

 SCHEMA_NAME + "." + MODEL_NAME;
  public static final String MODEL_NEW_FULL_NAME =
      CATALOG_NAME + "." + SCHEMA_NAME + "."


uffer, 5, "</p>")
		if templ_7745c5c3_Err != nil {
			return templ_7745c5c3_Err
		}
		if showMeta {
			templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "<meta http-equiv=\"refresh\" content=\"")
			if templ_7745c5c3_Err != nil {

			templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.ResolveAttributeValue(fmt.Sprintf("%d; url=%s", difficulty+1, redir))
			if templ_7745c5c3_Err != nil {
				return templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 17, Col: 86}

return templ_7745c5c3_Err
			}
			var templ_7745c5c3_Var6 string


(v) => v.name */
  getName?: (value: T) => string;
}

export async function checkboxWithHover<T>(
  config: CheckboxConfig<T>,
  options?: CheckboxWithHoverOptions<T>
): Promise<T[]> {
  const choices = config.choices.filter(
    (c): c is CheckboxChoice<T

 => c.value);
  const totalItems = values.length;
  let cursorPosition = choices.findIndex((c) => !c.disabled);
  if (cursorPosition < 0) cursorPosition = 0;

  // Default getName assumes object has 'name' property
  const getName = options?.getName ?? ((v

> =>
      typeof c === "object" && c !== null && !("type" in c && c.type === "separator")
  );
  const values = choices.map((c)


nting
if TYPE_CHECKING:
    from .._markitdown import MarkItDown

ACCEPTED_MIME_TYPE_PREFIXES = [
    "application/zip",
]

ACCEPTED_FILE_EXTENSIONS = [".zip"]

class ZipConverter(DocumentConverter):
    """Converts ZIP files to markdown by extracting and

 ZIP contents to a temporary directory, processes each file
    using appropriate converters based on file extensions, and then combines the results
    into a single markdown document. The temporary directory is cleaned up after processing.

    Example o

 converting all contained files.

    The converter extracts the


ava.util.function.Function;

/**
 * An implementation of {@link McpTransportStream} using Project Reactor types.
 *
 * @param <CONNECTION> the resource serving the stream
 * @author Dariusz Jędrzejczyk
 */
public class DefaultMcpTransportStream<CONNECTION>

 AtomicReference<>();

	// Used only for internal accounting
	private final long streamId;

	private final boolean resumable;

	private final Function<McpTransportStream<CONNECTION>, Publisher<CONNECTION>> reconnect;

	/**
	 * Constructs a new instance rep

 implements McpTransportStream<CONNECTION> {

	private static final Logger logger = LoggerFactory.getLogger(DefaultMcpTransportStream.class);

	private static final AtomicLong counter = new AtomicLong();

	private final AtomicReference<String> lastId = new


erverConfig));
    schemaOperations = new SdkSchemaOperations(TestUtils.createApiClient(serverConfig));
    tableOperations = new SdkTableOperations(TestUtils.createApiClient(serverConfig));
    client = WebClient.builder(uri).auth(AuthToken.ofOAuth2(token

  protected void cleanUp() {
    try {
      if (catalogOperations.getCatalog(TestUtils.CATALOG_NAME) != null) {
        catalogOperations.deleteCatalog(TestUtils.CATALOG_NAME, Optional.of(true));
      }
    } catch (Exception e) {
      // Ignore
    }


port { HugeiconsIcon } from "@hugeicons/react"
import { UnfoldMoreIcon } from "@hugeicons/core-free-icons"

type NativeSelectProps = Omit<React.ComponentProps<"select">, "size"> & {
  size?: "sm" | "default"
}

function NativeSelect({
  className,
  size =

fit has-[select:disabled]:opacity-50",
        className
      )}
      data-slot="native-select-wrapper"
      data-size={size}
    >
      <select
        data-slot="native-select"
        data-size={size}
        className="h-7 w-full min-w-0 appearance

 "default",
  ...props
}: NativeSelectProps) {
  return (
    <div
      className={cn(
        "group/native-select relative w-


focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground [

size-'])]:size-3.5",
        "group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list


se
        })
        .check(true)
        .output()
        .await?
        .stdout)
}

pub(super) fn matching_git_index_paths_by_executable_bit<'a>(
    stdout: &'a [u8],
    file_base: &'a Path,
    filenames: &'a FxHashSet<&Path>,
    executable: bool,

split(|&b| b == b'\0')
        .filter_map(move |entry| parse_stage_entry(entry, file_base, filenames, executable))
}

fn parse_stage_entry<'a>(
    entry: &'a [u8],
    file_base: &Path,
    filenames: &FxHashSet<&Path>,
    executable: bool,
) -> Option<

) -> impl Iterator<Item = &'a Path> + 'a {
    stdout
        .


 writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under

error)

// MarshalOutput is the function type for marshalling the output.
type MarshalOutput func(ctx context.Context, output any) (string, error)

type toolOptions struct {
	um         UnmarshalArguments
	m          MarshalOutput
	scModifier SchemaModifie

the License.
 */

package utils

import (
	"context"
	"reflect"

	"github.com/eino-contrib/jsonschema"
)

// UnmarshalArguments is the function type for unmarshalling the arguments.
type UnmarshalArguments func(ctx context.Context, arguments string) (any,


                   id: first_response.message_id.clone(),
                    content: first_response.choice.clone(),
                })
                .build();

            let second_response = model
                .completion(second_request)

expect("history containing redacted_thinking should be accepted");

            let text: String = second_response
                .choice
                .iter()
                .filter_map(|content| match content {
                    AssistantContent::T


targets are still responsive."""

		try:
			self.logger.debug(f'[CrashWatchdog] Checking browser health for target {self.browser_session.agent_focus_target_id}')
			cdp_session = await self.browser_session.get_or_create_cdp_session()

			for target in self

await self.browser_session.get_or_create_cdp_session(target_id=target.target_id)
					await cdp_session.cdp_client.send.Page.navigate(
						params={'url': 'about:blank'}, session_id=cdp_session.session_id
					)

			# Quick ping to check if session is ali

.browser_session.session_manager.get_all_page_targets():
				if self._is_new_tab_page(target.url) and target.url != 'about:blank':
					self.logger.debug(f'[CrashWatchdog] Redirecting chrome://new-tab-page/ to about:blank {target.url}')
					cdp_session =


        if (dryRun) {
            return summarizeSubmission({
                pdfFile,
                email,
                venue,
                message: 'Input validation passed. No remote request was sent.',
                dryRun: true,

', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                filename: pdfFile.fileName,
                venue,
            }),
        });
        ensureSuccess(uploadUrlR

 });
        }
        const { response: uploadUrlResponse, payload: uploadUrlPayload } = await requestJson('/api/get-upload-url


'--dry-run');
  assert.match(out, /\(dry run\)/);
  assert.match(out, /6 added/);
  assert.ok(!fs.existsSync(path.join(tmp, '.cursor')));
  assert.ok(!fs.existsSync(path.join(tmp, '.windsurf')));
  assert.ok(!fs.existsSync(path.join(tmp, '.clinerules')));

 out = runInit(tmp, '--only', 'cline');
  assert.match(out, /1 added/);
  assert.ok(fs.existsSync(path.join(tmp, '.clinerules/caveman.md')));
  assert.ok(!fs.existsSync(path.join(tmp, '.cursor')));
});

test('detects sentinel and skips files that already h

  assert.ok(!fs.existsSync(path.join(tmp, '.github/copilot-instructions.md')));
  assert.ok(!fs.existsSync(path.join(tmp, '.opencode')));
  assert.ok(!fs.existsSync(path.join(tmp, 'AGENTS.md')));
});

test('--only filters to one target', (tmp) => {
  const


n(messages)} messages:')
	for msg in messages:
		print(f'  • {msg["datetime"]}: {msg["message"][:30]}... to {msg["contact"]}')

	now = datetime.now()
	immediate = []
	future = []

	for msg in messages:
		msg_time = datetime.strptime(msg['datetime'], '%Y-%m

:
			immediate.append(msg)
		else:
			future.append(msg)

	if args.test:
		print('\n=== TEST MODE - Preview ===')
		if immediate:
			print(f'\nWould send {len(immediate)} past-due messages NOW:')
			for msg in immediate:
				print(f'  📱 To {msg["contact"]}


imple)

## 7. Update CLAUDE.md Template
- [x] 7.1 Update `src/core/templates/claude-template.ts` with streamlined content
- [x] 7.2 Include three-stage workflow prominently
- [x] 7.3 Add comprehensive CLI quick reference (list, show, diff, archive, etc.)
-

. Testing and Validation
- [x] 8.1 Test all documented CLI commands for accuracy
- [x] 8.2 Run `openspec init` to verify CLAUDE.md generation
- [x] 8.3 Validate instruction clarity with example scenarios
- [x] 8.4 Ensure no critical information was lost in

 [x] 7.4 Add "Before Any Task" checklist
- [x] 7.5 Add "Before Creating Specs" rule
- [x] 7.6 Keep complexity management principles
- [x] 7.7 Add critical scenario formatting note (#### Scenario: headers)
- [x] 7.8 Include debugging command reference

## 8


roll_page)
        assert response.status == 200

    @pytest.mark.parametrize(
        "kwargs",
        [
            {"real_chrome": True, "disable_resources": True},
            {"wait_selector": "h1", "wait_selector_state": "attached"},
            {"

     {
                "google_search": True,
                "real_chrome": True,
                "wait": 10,
                "locale": "en-US",
                "extra_headers": {"ayo": ""},
                "useragent": "Mozilla/5.0 (Windows NT 10.0; Win6

wait_selector": "h1", "wait_selector_state": "visible"},


minimal');
  assert.equal(r.status, 2);
  assert.match(r.stderr, /mutually exclusive/);
});

test('--only without arg fails', () => {
  const r = run('--only');
  assert.equal(r.status, 2);
  assert.match(r.stderr, /--only requires an argument/);
});

test

, /--config-dir requires a path/);
});

test('--config-dir followed by another flag fails', () => {
  const r = run('--config-dir', '--all');
  assert.equal(r.status, 2);
  assert.match(r.stderr, /--config-dir requires a path/);
});

test('aider alias rewr

('--config-dir without arg fails', () => {
  const r = run('--config-dir');
  assert.equal(r.status, 2);
  assert.match(r.stderr


eString(templ_7745c5c3_Var7))
			if templ_7745c5c3_Err != nil {
				return templ_7745c5c3_Err
			}
			templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "</p><p>")
			if templ_7745c5c3_Err != nil {
				return templ_7745c5c3_Err
			}

"))
			if templ_7745c5c3_Err != nil {
				return templ.Error{Err: templ_7745c5c3_Err, FileName: `proofofwork.templ`, Line: 27, Col: 39}
			}
			_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
			if templ_7

	var templ_7745c5c3_Var8 string
			templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T("anubis_compromise


ext("Failed to create Conda environment")?;
        }

        if !hook.additional_dependencies.is_empty() {
            let mut install_cmd = Cmd::new(conda);
            install_cmd
                .arg("install")
                .arg("-p")

             .output()
                .await
                .context("Failed to install Conda dependencies")?;
        }

        info.persist_env_path();

        reporter.on_install_complete(progress);

        Ok(InstalledHook::Installed {

   .arg(&info.env_path)
                .args(&hook.additional_dependencies);
            if let Some(repo_path) = hook.repo_path() {
                install_cmd.current_dir(repo_path);
            }
            install_cmd
                .check(true)


ommand).toBeDefined();
    expect(command.site).toBe('yahoo');
    expect(command.name).toBe('search');
    expect(command.access).toBe('read');
    expect(command.browser).toBe(true);
    expect(command.strategy).toBe('public');
    expect(command.domain)

  it('should define keyword positional arg', () => {
    const kwArg = command.args.find(a => a.name === 'keyword');
    expect(kwArg).toBeDefined();
    expect(kwArg.positional).toBe(true);
    expect(kwArg.required).toBe(true);
  });

  it('should defi


EPTED_MIME_TYPE_PREFIXES = [
    "text/html",
    "application/xhtml",
]

ACCEPTED_FILE_EXTENSIONS = [
    ".html",
    ".htm",
]

class HtmlConverter(DocumentConverter):
    """Anything with content type text/html"""

    def accepts(
        self,

   **kwargs: Any,  # Options to pass to the converter
    ) -> bool:
        mimetype = (stream_info.mimetype or "").lower()
        extension = (stream_info.extension or "").lower()

        if extension in ACCEPTED_FILE_EXTENSIONS:
            return Tru

   file_stream: BinaryIO,
        stream_info: StreamInfo,


_size['width'] != self.size['width'] or self.padded_size['height'] != self.size['height']:
					new_img = Image.new('RGB', (self.padded_size['width'], self.padded_size['height']), (0, 0, 0))
					# Center the image
					x_offset = (self.padded_size['width'

offset, y_offset))
					img = new_img

				# 3. Convert to numpy array for imageio
				img_array = np.array(img)

			self._writer.append_data(img_array)
		except Exception as e:
			logger.warning(f'Could not process and add video frame: {e}')

	def stop_an

] - self.size['width']) // 2
					y_offset = (self.padded_size['height'] - self.size['height']) // 2
					new_img.paste(img, (x_


ntext
//   3. Detects missing statusline config and emits setup nudge

const fs = require('fs');
const path = require('path');
const { getDefaultMode, getClaudeDir, isShellSafe } = require('./ponytail-config');
const { getPonytailInstructions } = require('

 {
  clearMode,
  isCodex,
  isCopilot,
  setMode,
  writeHookOutput,
} = require('./ponytail-runtime');

const claudeDir = getClaudeDir();
const settingsPath = path.join(claudeDir, 'settings.json');

const mode = getDefaultMode();

// "off" mode — skip ac


.length; i++) {
		Clay_RenderCommand *command = Clay_RenderCommandArray_Get(&commands, i);

		switch(command->commandType) {
		case CLAY_RENDER_COMMAND_TYPE_RECTANGLE: {
            Clay_RectangleRenderData *config = &command->renderData.rectangle;
			Clay

_path(cr);
			cairo_arc(cr, bb.x + config->cornerRadius.topLeft,
					  bb.y + config->cornerRadius.topLeft,
					  config->cornerRadius.topLeft,
					  M_PI, 3 * M_PI / 2); // 180° to 270°
			cairo_arc(cr, bb.x + bb.width - config->cornerRadius.topRight,

_BoundingBox bb = command->boundingBox;

			cairo_set_source_rgba(cr, CLAY_TO_CAIRO(config->backgroundColor));

			cairo_new_sub


ription}`,
  ];

  if (result.totalSnippets !== -1 && result.totalSnippets !== undefined) {
    formattedResult.push(`- Code Snippets: ${result.totalSnippets}`);
  }

  const reputationLabel = getSourceReputationLabel(result.trustScore);
  formattedResult.

formattedResult.push(`- Benchmark Score: ${result.benchmarkScore}`);
  }

  if (result.versions !== undefined && result.versions.length > 0) {
    formattedResult.push(`- Versions: ${result.versions.join(", ")}`);
  }

  if (result.source) {
    formattedR

push(`- Source Reputation: ${reputationLabel}`);

  if (result.benchmarkScore !== undefined && result.benchmarkScore > 0) {


{pc.white("to update now")}`,
    `${pc.white("Or run")} ${pc.yellow(info.upgradePlan.displayCommand)}`,
  ]);
  await markUpdateNotificationShown(info.latestVersion);
  log.blank();
}

async function upgradeCommand(options: UpgradeOptions): Promise<void>

await checkForUpdates({ force: true });
  const plan = info?.upgradePlan ?? getUpgradePlan();

  if (!info) {
    log.warn("Couldn't check for updates right now.");
    log.info(`Try again later or run ${pc.cyan(plan.displayCommand)} manually.`);
    retur

{
  trackEvent("command", { name: "upgrade" });

  const info =


ART, NewStreamGraphMultiBranch(func(ctx context.Context, in *schema.StreamReader[string]) (endNode map[string]bool, err error) {
		in.Close()
		return map[string]bool{"1": true, "2": true}, nil
	}, map[string]bool{"1": true, "2": true, "3": true}))
	assert

.AddEdge("3", END)
	assert.NoError(t, err)

	ctx := context.Background()
	r, err := g.Compile(ctx)
	assert.NoError(t, err)

	result, err := r.Invoke(ctx, "start")
	assert.NoError(t, err)
	assert.Equal(t, map[string]any{
		"1": "start",
		"2": "start",
	},

.NoError(t, err)

	err = g.AddEdge("1", END)
	assert.NoError(t, err)
	err = g.AddEdge("2", END)
	assert.NoError(t, err)
	err = g


t();
  assert.ok(manifest.contextFileName, 'contextFileName must be set so rules load every session');
  const context = read(manifest.contextFileName);
  for (const phrase of RULE_INVARIANTS) {
    assert.ok(context.includes(phrase), `context file missing

 of [...REUSED_COMMANDS, ...REUSED_SKILLS]) {
    assert.ok(fs.existsSync(path.join(root, rel)), `reused file missing: ${rel}`);
  }
});

test('Gemini cannot auto-discover Claude/Codex hook events', () => {
  assert.equal(
    fs.existsSync(path.join(root,

 rule invariant: "${phrase}"`);
  }
});

test('the commands and skills the adapter reuses are present', () => {
  for (const rel


tractParamDefinition {
  private final Boolean value;

  @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
  @JsonPOJOBuilder(withPrefix = "")
  static final class BooleanParamDefinitionBuilderImpl
      extends BooleanParamDefinitionBuilder<

 BooleanParamDefinitionBuilderImpl> {
    @Override
    public BooleanParamDefinition build() {
      BooleanParamDefinition param = new BooleanParamDefinition(this);
      param.validate();
      return param;
    }
  }

  @Override
  public ParamType get


1  log compression deltas to stderr

const { spawn } = require('child_process');
const { compressDescriptionsInPlace, compress } = require('./compress');

const args = process.argv.slice(2);
if (args.length === 0) {
  process.stderr.write('caveman-shrink:

 process.stderr.write('Usage: caveman-shrink <upstream-command> [...args]\n');
  process.exit(2);
}

const debug = process.env.CAVEMAN_SHRINK_DEBUG === '1';
const fields = (process.env.CAVEMAN_SHRINK_FIELDS || 'description')
  .split(',').map(s => s.trim()


text: context,
      };
    }
    process.stdout.write(JSON.stringify(output));
    return;
  }
  if (isQoder) {
    // Qoder: hookSpecificOutput JSON, same shape as Codex minus systemMessage.
    // UserPromptSubmit additionalContext is injected into the

      output.hookSpecificOutput = {
        hookEventName: event,
        additionalContext: context,
      };
    }
    process.stdout.write(JSON.stringify(output));
    return;
  }
  // Native Claude: SessionStart accepts raw stdout, but SubagentStart ne

Agent's conversation.
    const output = {};
    if (context) {


in string result that is sent back to the model as
// a tool message. The framework handles JSON decoding automatically when using
// the [utils.InferTool] or [utils.NewTool] constructors.
type InvokableTool interface {
	BaseTool

	// InvokableRun executes

] that yields string chunks
// incrementally. The caller (ToolsNode) is responsible for closing the reader.
type StreamableTool interface {
	BaseTool

	StreamableRun(ctx context.Context, argumentsInJSON string, opts ...Option) (*schema.StreamReader[string]

 the tool with arguments encoded as a JSON string.
	InvokableRun(ctx context.Context, argumentsInJSON string, opts ...Option) (string, error)
}

// StreamableTool is a streaming variant of [InvokableTool].
//
// StreamableRun returns a [schema.StreamReader


erns(allow)
        self.deny: Tuple[Pattern[str], ...] = _compile_patterns(deny)
        self.allow_domains: Tuple[str, ...] = tuple(d.lower() for d in _to_str_tuple(allow_domains))
        self.deny_domains: Tuple[str, ...] = tuple(d.lower() for d in _to

Tuple[str, ...] = _to_str_tuple(restrict_xpath)
        self.tags: Tuple[str, ...] = tuple(tags)
        self.attrs: Tuple[str, ...] = tuple(attrs)
        self.canonicalize = canonicalize
        self.strip = strip
        self.keep_fragment = keep_fragme

_str_tuple(deny_domains))
        self.restrict_css: Tuple[str, ...] = _to_str_tuple(restrict_css)
        self.restrict_xpath:


tAll(env);
			}
			return this;
		}

		public Builder addEnvVar(String key, String value) {
			Assert.notNull(key, "The key can not be null");
			Assert.notNull(value, "The value can not be null");
			this.env.put(key, value);
			return this;
		}

		public

object including only environment variables deemed
	 * safe to inherit.
	 */
	private static Map<String, String> getDefaultEnvironment() {
		return System.getenv()
			.entrySet()
			.stream()
			.filter(entry -> DEFAULT_INHERITED_ENV_VARS.contains(entry.ge

 ServerParameters build() {
			return new ServerParameters(command, args, env);
		}

	}

	/**
	 * Returns a default environment


  int rc = diskann_prune_select(NULL, NULL, 0, alpha, max_neighbors,
                                   NULL, &outCount);
    assert(rc == 0 /* SQLITE_OK */);
    assert(outCount == 0);
    return 0;
  }

  /* Allocate arrays */
  int n = num_candidates;

(n * n * sizeof(float));
  float *p_distances = malloc(n * sizeof(float));
  int *outSelected = malloc(n * sizeof(int));
  if (!inter_distances || !p_distances || !outSelected) {
    free(inter_distances);
    free(p_distances);
    free(outSelected);


ui():
	with gr.Blocks(title='Browser Use GUI') as interface:
		gr.Markdown('# Browser Use Task Automation')

		with gr.Row():
			with gr.Column():
				api_key = gr.Textbox(label='OpenAI API Key', placeholder='sk-...', type='password')
				task = gr.Textbox

					placeholder='E.g., Find flights from New York to London for next week',
					lines=3,
				)
				model = gr.Dropdown(choices=['gpt-4.1-mini', 'gpt-5', 'o3', 'gpt-5-mini'], label='Model', value='gpt-4.1-mini')
				headless = gr.Checkbox(label='Run Head


            data_uri = f"data:{content_type};base64,{base64_image}"

            actual_prompt = prompt or self.default_prompt
            response = self.client.chat.completions.create(
                model=self.model,
                messages=[

                   "image_url": {"url": data_uri},
                            },
                        ],
                    }
                ],
            )

            text = response.choices[0].message.content
            return OCRResult(

            {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": actual_prompt},
                            {
                                "type": "image_url",


it puppeteer.connect({
  browserWSEndpoint: "wss://connect.browser-use.com?apiKey=KEY&proxyCountryCode=us"
});
```

Browser auto-starts on connect, auto-stops on disconnect. Pricing: $0.05/hour.

---

## Decision Summary

| Condition | Best option |
|-----

CLI commands |
| TypeScript/JS | CDP WebSocket + Playwright |
| MCP client (Claude Desktop, Cursor) | Local MCP server |
| HTTP only / any language | Cloud REST: `POST /browsers` → CDP URL |
| Existing Playwright/Puppeteer scripts | CDP WebSocket (stealth

------|------------|
| Agent has terminal access (sandbox/VM) |


'-')
	elif 'llama_4_maverick' in model_part:
		model = model_part.replace('llama_4_maverick', 'llama-4-maverick').replace('_', '-')
	elif 'gpt_oss_120b' in model_part:
		model = model_part.replace('gpt_oss_120b', 'gpt-oss-120b')
	elif 'qwen_3_32b' in model

	model = model_part.replace('qwen_3_235b_a22b_instruct', 'qwen-3-235b-a22b-instruct-2507')
	elif 'qwen_3_235b_a22b_thinking' in model_part:
		if model_part.endswith('_2507'):
			model = model_part.replace('qwen_3_235b_a22b_thinking_2507', 'qwen-3-235b-a22b

_part:
		model = model_part.replace('qwen_3_32b', 'qwen-3-32b')
	elif 'qwen_3_235b_a22b_instruct' in model_part:
		if model_part.endswith('_2507'):
			model = model_part.replace('qwen_3_235b_a22b_instruct_2507', 'qwen-3-235b-a22b-instruct-2507')
		else:


one = StepMetadata(step_number=0, step_start_time=0.0, step_end_time=1.0, step_interval=None)
	assert metadata_none.step_interval is None

	# Omitted (defaults to None)
	metadata_default = StepMetadata(step_number=0, step_start_time=0.0, step_end_time=1.0)

interval_calculation():
	"""Test step_interval calculation logic (uses previous step's duration)"""
	# Previous step (Step 1): runs from 100.0 to 102.5 (duration: 2.5s)
	previous_start = 100.0
	previous_end = 102.5
	previous_duration = previous_end - previ

	assert metadata_default.step_interval is None

def test_step_


o
GROUP BY cst_id
HAVING COUNT(*) > 1 OR cst_id IS NULL;

-- Check for Unwanted Spaces
-- Expectation: No Results
SELECT
    cst_key
FROM silver.crm_cust_info
WHERE cst_key != TRIM(cst_key);

-- Data Standardization & Consistency
SELECT DISTINCT
    cst

 'silver.crm_prd_info'
-- ====================================================================
-- Check for NULLs or Duplicates in Primary Key
-- Expectation: No Results
SELECT
    prd_id,
    COUNT(*)
FROM silver.crm_prd_info
GROUP BY prd_id
HAVING COUN


r && err.code === 'PAID_CONTENT');
    // upower 没有权益查询端点，不应再打 nav API
    expect(mockApiGet).toHaveBeenCalledTimes(1);
    expect(mockDownloadMedia).not.toHaveBeenCalled();
  });

  it('fails closed when successful view payload lacks paid-content metadata

 err instanceof CommandExecutionError && /paid-content metadata/.test(err.message),
    );
    expect(mockDownloadMedia).not.toHaveBeenCalled();
  });

  it('skips pre-check entirely with --force', async () => {
    const rows = await command.func(page, {

', async () => {
    mockApiGet.mockResolvedValueOnce({ code: 0, data: { bvid: 'BV1xx411c7mD' } });

    await expect(
      command.func(page, { bvid: 'BV1xx411c7mD', output: './o', quality: 'best', force: false }),
    ).rejects.toSatisfy(
      (err) =>


emp.path().join("missing");

        assert_eq!(dir_size_bytes(&missing), 0);

        Ok(())
    }

    #[test]
    fn dir_stats_empty_directory() -> anyhow::Result<()> {
        let temp = TempDir::new()?;

        assert_eq!(dir_size_bytes(temp.path()),

)?;
        let nested = temp.path().join("nested/deep");
        fs_err::create_dir_all(&nested)?;
        fs_err::write(temp.path().join("root.txt"), b"hello")?;
        fs_err::write(temp.path().join("nested/data.txt"), b"abc")?;
        fs_err::write(t

 0);

        Ok(())
    }

    #[test]
    fn dir_stats_nested_files() -> anyhow::Result<()> {
        let temp = TempDir::new(


yOn(console, 'log').mockImplementation((...args: unknown[]) => {
      lines.push(args.join(' '));
    });
    const context = loadChangeContext(tempDir, 'my-change');
    const instructions = generateInstructions(context, artifactId);
    const isBlocked

 output = capture('specs');

    expect(output).toContain('skip_specs: true');
    expect(output).toContain('Do not create spec files');
    expect(output).toContain('</artifact>');
    expect(output).not.toContain('<task>');
    expect(output).not.toConta

= instructions.dependencies.some((d) => !d.done);
    printInstructionsText(instructions, isBlocked);
    vi.restoreAllMocks();
    return lines.join('\n');
  }

  it('emits only the warning for a skipped artifact, no creation directive', () => {
    const


: 1 });
  });

  it('identifies the tracked artifact by apply.tracks even when it is not named "tasks"', async () => {
    const schemaDir = path.join(projectRoot, 'openspec', 'schemas', 'custom-track');
    await fs.mkdir(schemaDir, { recursive: true });

    '    template: proposal.md',
        '    requires: []',
        '  - id: checklist',
        '    generates: "work/*.md"',
        '    description: Work checklist',
        '    template: tasks.md',
        '    requires: [proposal]',
        'apply:

    await fs.writeFile(
      path.join(schemaDir, 'schema.yaml'),
      [
        'name: custom-track',
        'version: 1',
        'artifacts:',
        '  - id: proposal',
        '    generates: proposal.md',
        '    description: Proposal',


err := config.Valid(); err != nil {
		return nil, fmt.Errorf("%w: %w", store.ErrBadConfig, err)
	}

	if config.BucketName == "" {
		return nil, fmt.Errorf("%w: %s", store.ErrBadConfig, ErrNoBucketName)
	}

	// If a client was injected (e.g., tests), use it

		return &Store{
			s3:     f.Client,
			bucket: config.BucketName,
		}, nil
	}

	cfg, err := awsConfig.LoadDefaultConfig(ctx)
	if err != nil {
		return nil, fmt.Errorf("can't load AWS config from environment: %w", err)
	}

	client := s3.NewFromConfig(cfg


 global
  stubbing and keeps code simple.

## Risks & Mitigations

- Risk: Tests forget to restore `process.cwd()`.
  - Mitigation: Add `afterAll` guard restoring cwd; reset `process.exitCode` in
    `afterEach` where modified.
- Risk: Behavior divergence

`; only tests pass custom roots.

## Acceptance Criteria

- Tests that previously depended on repo state now:
  - Create and use a temp fixture root.
  - Do not read real `openspec/changes` during execution.
  - Pass consistently regardless of directory or

if DI root is misused.
  - Mitigation: Default to `process.cwd()


ema': schema,
				},
			}

		try:
			raw_response = await acompletion(**params)
		except RateLimitError as e:
			raise ModelRateLimitError(
				message=str(e),
				model=self.name,
			) from e
		except Timeout as e:
			raise ModelProviderError(
				message

model=self.name,
			) from e
		except APIConnectionError as e:
			raise ModelProviderError(
				message=str(e),
				model=self.name,
			) from e
		except APIError as e:
			status = getattr(e, 'status_code', 502) or 502
			raise ModelProviderError(
				mess


ked via trap EXIT
cleanup() {
  rm -rf "$WORK"
  unset ITEM_JSON NPM_OTP
}
trap cleanup EXIT

name="$(node -p 'require("./package.json").name')"
version="$(node -p 'require("./package.json").version')"
if npm view "$name@$version" version >/dev/null 2>&1;

sh"

resolve_op_item
ensure_npm_auth
unset ITEM_JSON

who="$(npm_auth_whoami 2>"$WORK/npm-whoami.log" || true)"
if [ -z "$who" ]; then
  echo "npm auth check failed" >&2
  redact <"$WORK/npm-whoami.log" >&2
  exit 4
fi
echo "npm auth ok as $who"

publish_l

then
  echo "$name@$version is already published" >&2
  exit 5
fi

# shellcheck source=npm-auth.sh
source "$SCRIPT_DIR/npm-auth.